import { deepClone, isNilOrEmptyStr } from "../../../../utils/util";
import fieldMixin from "../fieldMixin";

export default {
  methods: {
    isUtcTransformEnabled() {
      return !!this.field?.options?.utcTransformEnabled;
    },
    transformUtcToLocalValue(value) {
      if (isNilOrEmptyStr(value) || !this.isUtcTransformEnabled()) {
        return value;
      }
      if (Array.isArray(value)) {
        return value.map((item) => this.transformUtcToLocalSingle(item));
      }
      return this.transformUtcToLocalSingle(value);
    },
    transformUtcToLocalSingle(value) {
      if (isNilOrEmptyStr(value)) {
        return value;
      }
      const localValue = this.$utcToLocal(value);
      if (!localValue) {
        return localValue;
      }
      const widgetType = this.field?.type;
      const options = this.field?.options || {};
      if (widgetType === "time") {
        const parts = String(localValue).split(" ");
        return parts.length > 1 ? parts[1] : localValue;
      }
      if (widgetType === "time-range") {
        return localValue;
      }
      const dateType = options.type;
      const valueFormat = options.valueFormat || "";
      if (widgetType === "date" || widgetType === "date-range") {
        if (
          dateType === "datetime"
          || (valueFormat && /[HhmSs]/.test(valueFormat))
        ) {
          return localValue;
        }
        return String(localValue).split(" ")[0];
      }
      return localValue;
    },
    getUtcTransformedFieldValue() {
      if (!this.isUtcTransformEnabled()) {
        return this.fieldModel;
      }
      return this.transformUtcToLocalValue(this.fieldModel);
    },
    initFieldModel(flag) {
      fieldMixin.methods.initFieldModel.call(this, flag);
      // flag=true 来自 initValueWatchEvent；行数据已是本地时间，再转换会重复偏移并触发 watch 死循环
      if (this.designState || !this.isUtcTransformEnabled() || flag) {
        return;
      }
      const transformed = this.getUtcTransformedFieldValue();
      if (transformed === this.fieldModel) {
        return;
      }
      const currentData =
        this.tableParam && this.tableParam.row
          ? this.tableParam.row
          : this.formModel;
      this.fieldModel = transformed;
      this.oldFieldValue = deepClone(transformed);
      if (transformed !== currentData[this.fieldKeyName]) {
        this.syncUpdateFormModel(transformed);
      }
    },
  },
};
