export default {
  props: ["formElement", "keyValue"],

  data() {
    return {
      options: {
        controls: [
          // "play-large", // The large play button in the center
          //'restart', // Restart playback
          // "rewind", // Rewind by the seek time (default 10 seconds)
          "play", // Play/pause playback
          // "fast-forward", // Fast forward by the seek time (default 10 seconds)
          "progress", // The progress bar and scrubber for playback and buffering
          "current-time", // The current time of playback
          // "duration", // The full duration of the media
          "mute", // Toggle mute
          "volume", // Volume control
          // "captions", // Toggle captions
          "settings", // Settings menu
          // "pip", // Picture-in-picture (currently Safari only)
          // "airplay", // Airplay (currently Safari only)
          "download", // Show a download button with a link to either the current source or a custom URL you specify in your options
          // "fullscreen", // Toggle fullscreen
        ],
        speed: { selected: 1, options: [0.75, 1, 1.5, 2] },
      },

      hasError: false,
      localFormElement: {},
      textValue: "",
      emit_disable: false,
      textValuePrev: "",
      textDate: [],
      objectValue: {}, // for select component {text, value}
      isUpdateitem: false,
      renderKey: 1,
      listOptions: [],
    };
  },
  // beforeMount() {
  //   this.$root.$on("catch-form-builder-event", this.listenEventBus);
  // },
  // beforeDestroy() {
  //   this.$root.$off("catch-form-builder-event", this.listenEventBus);
  // },

  mounted() {
    // this.textValue = this.value;
    // this.textItem = this.value

    this.disableEmitTemprory(2000);
    console.info("this.formElement", this.formElement);

    this.localFormElement = this.formElement;
    this.textValuePrev = this.localFormElement?.value;
    this.initTextValue();
    this.textValuePrev = this.textValue;
    // this.date = this.textValue; // for DateCompnent
  },

  watch: {
    formElement: {
      handler(newValue) {
        this.localFormElement = newValue;
      },
      deep: true,
      nested: true,
    },

    textValue(newVal) {
      // console.log(this.localFormElement.key, newVal)
      if (this.textValuePrev == newVal) {
        return;
      }
      let [emitValue, emitValueObject] = this.parseValueToEmit(newVal);

      // if (!this.emit_disable)
      // console.log(this.localFormElement.key, newVal, emitValue, this.localFormElement.value)
      if (this.localFormElement?.value != emitValue)
        this.$emit("take-value", emitValue);

      if (emitValueObject)
        this.parseAffectedToEventBus(emitValueObject); // for select only
      else this.parseAffectedToEventBus(emitValue);
    },
  },
  methods: {
    incrementRenderKey() {
      this.renderKey = this.renderKey + 1;
      this.$forceUpdate();
    },

    parseValueToEmit(newVal) {
      let emitValue = newVal;
      let emitValueObject = undefined;

      if (this.localFormElement?.type == "date") {
        // console.info(newVal);
        emitValue = newVal;
        try {
          if (this.localFormElement?.savetype == "timestamp") {
            let dtStr = newVal;
            // const dtStr = "2012/02/26";
            const [y, m, d] = dtStr.split(/-|\//);
            const date = new Date(y, m - 1, d);
            // emitValue = date.toISOString();
            emitValue = date.getTime()();
          }
          //  if( this.localFormElement?.subtype == 'time' )
          //   return "HH:mm"
        } catch {
          emitValue = newVal;
        }
        // console.info(emitValue);
      }
      // input , textarea   if multi items
      else if (this.localFormElement?.isarray) {
        let delim = this.localFormElement?.delimiter
          ? this.localFormElement.delimiter
          : "،";
        emitValue = [];
        newVal
          .split(delim)
          .filter((el) => el.trim())
          .forEach((el) => {
            emitValue.push(el.trim());
          });
      } else if (this.localFormElement?.type == "select") {
        // if(this.localFormElement.key == 'city'){
        //   debugger
        // }
        emitValue = newVal;
        //برای ذدخیره در بک کدام مقدار را بفرستد
        if (this.localFormElement?.value_save) {
          emitValueObject = this.listOptions.find(
            (item) => item.value == newVal
          );

          if (emitValueObject && this.localFormElement?.value_save == "title") {
            emitValue = emitValueObject.title ?? emitValueObject.value;
          } else if (
            emitValueObject &&
            this.localFormElement?.value_save == "object"
          ) {
            emitValue = {
              id: emitValueObject.value,
              title: emitValueObject.title,
            };
          }
        }
      } else emitValue = newVal;

      return [emitValue, emitValueObject];
    },
    listenEventBus({ value, affectedTo }) {
      // console.log(affectedTo.key, this.localFormElement.key);
      if (affectedTo.key === this.localFormElement?.key) {
        try {
          // console.log(this.localFormElement.key, affectedTo, value);
          // console.log(this[affectedTo.action])
          this[affectedTo.action](value);
        } catch (err) {}
      }
    },
    parseAffectedToEventBus(newValue) {
      if (!this.localFormElement?.["affected-to"]) return;

      // console.log("parseAffectedToEvent", newValue);
      // console.log(newValue);

      let affectedTo = this.localFormElement?.["affected-to"];
      // console.log(affectedTo);

      affectedTo.forEach((item_affectedTo) => {
        let value = newValue;
        if (
          typeof newValue == "object" &&
          item_affectedTo?.param &&
          newValue[item_affectedTo?.param]
        )
          value = newValue[item_affectedTo?.param];

        if (item_affectedTo?.emit) {
          this.$emit("action-affected-item", {
            action: item_affectedTo.emit,
            key: item_affectedTo.key,
            value,
          });
          // console.log("action-affected-item", { action:item_affectedTo.emit, key: item_affectedTo.key, value})
        } else if (item_affectedTo?.action) {
          this.$root.$emit("catch-form-builder-event", {
            value: value,
            affectedTo: item_affectedTo,
          });
        }
      });
    },
    disableEmitTemprory(timeout = 1000) {
      this.emit_disable = true;
      setTimeout(() => {
        this.emit_disable = false;
      }, timeout);
    },

    clearErrors() {
      return true;
    },
    getLabel() {
      let label = this.localFormElement?.label;
      if (this.localFormElement?.required == "1") label = "*" + label;
      return label;
    },
    validate(ev) {
      const value = ev.target.value;
      if (this.localFormElement?.validate) {
        // چک کردن برای وجود الگو
        if (value) {
          let pattern = this.localFormElement?.validate;
          // اگر الگوی ورودی معتبر باشد، تنظیم می‌کنیم که مقدار مطابقت دارد یا خیر
          this.hasError = new RegExp(pattern).test(value);
        } else {
          // اگر مقدار ورودی خالی باشد، خطا بر اساس الزامی بودن فیلد تعیین می‌شود
          this.hasError = this.localFormElement?.required ? true : false;
        }
      } else {
        // اگر الگوی validate وجود نداشته باشد، کاری انجام نمی‌دهیم
        this.hasError = false;
      }
      // اعلان خطا به والد (component اصلی)
      this.$emit("take-value-validate", this.hasError);
    },

    initTextValue(newValue = undefined) {
      // console.log('initTextValue', this.localFormElement.key, newValue)

      let value = "";
      if (newValue) value = newValue;
      else if (this.localFormElement?.value) value = this.localFormElement?.value;
      else if (this.localFormElement?.value_defualt)
        value = this.localFormElement.value_defualt;

      // در همه حالت نباید این باشد اگر لازم شد باید پیش فرض تنظیم شود
      // ذخیره هم نمیشود ...!!!
      // if (!value && this.localFormElement.type == "select") {
      //   value = this.listOptions.length > 0 ? this.listOptions[0].value : "";
      // }
      // console.log(this.localFormElement.key, value)

      var mValue = value ?? "";

      if (this.localFormElement?.type == "date") {
        //  console.info("setTextValue", mValue);
        try {
          var date = "";
          if (mValue != "") {
            if (this.localFormElement?.savetype == "timestamp") {
              let timeWithSeconds = mValue;

              if (
                this.isUnixTimestamp(mValue) &&
                mValue.toString().length == 10
              ) {
                timeWithSeconds = mValue * 1000;
              }
              date = this.$moment(new Date(timeWithSeconds)).format(
                "YYYY-MM-DD HH:mm"
              );
            } else if (
              this.localFormElement?.savetype == "datetime" ||
              this.localFormElement?.savetype == "date"
            ) {
              date = this.$moment(new Date(mValue)).format("YYYY-MM-DD HH:mm");
            } else date = mValue;
          }
          this.textDate = date;
          mValue = date;
        } catch {
          this.textDate = mValue;
        }
      } else if (this.localFormElement?.isarray) {
        if (value && Array.isArray(value)) {
          let delim = this.localFormElement?.delimiter
            ? this.localFormElement?.delimiter
            : "، ";
          mValue = value.join(delim);
        } else mValue = "";
      } else if (this.localFormElement?.type == "select") {
        if (this.localFormElement?.value_save == "title") {
          // console.log('value_defualt', this.localFormElement.value_defualt)
          let finded = this.listOptions.find((item) => {
            if (item.title == value) {
              return item;
            }
          });

          if (finded) {
            mValue = finded.value;
            // console.log('finded', finded)
          } else {
            mValue =
              this.listOptions.length > 0 ? this.listOptions[0].value : "";
          }
        } else if (this.localFormElement?.value_save == "object") {
          mValue = value.value;
        } else mValue = value ?? "";
      } else {
        mValue = value ?? "";
      }

      //نیازی به ارسال تغییر در واچ نیست
      if (this.localFormElement?.value == value) this.textValuePrev == value;

      this.textValue = mValue;

      // console.log(' this.textValue', this.localFormElement.key,  this.textValue)
    },
    isUnixTimestamp(value) {
      // Check if the value is a number
      if (typeof value !== "number" && !/^\d+$/.test(value)) {
        return false;
      }
      // Convert to number if it's a string
      value = parseInt(value);
      // Unix timestamps are non-negative integers
      return !isNaN(value) && value >= 0 && value % 1 === 0;
    },

    sendTextValue() {
      this.$emit("keydown", {
        text: this.textValue,
        key: this.keyValue,
        isUpdate: this.isUpdateitem,
      });
    },

    ////ااز هیچا فراخوانی نمیشه لذا کامنت کردم
    //فقط برای select
    // takeSelectValue($event, type) {

    //   this.objectValue = {
    //     value: $event.target.value,
    //     text: $event.target.selectedOptions[0].text,
    //   };

    //   console.log('takeSelectValue',this.localFormElement.key , objectValue)

    //   this.$emit("take-select-object", {
    //     type: type,
    //     objectValue: this.objectValue,
    //   });
    // },
  },
};