import moment from "moment";
export default {
  dicts: ['business_pztj','business_cctj','business_nddw','business_tjdw','business_yxqdw','business_rqcz'],
  props: {
    templateData: {
      type: Object,
      default: () => { },
    },
  },
  watch: {
    templateData: {
      immediate: true,
      handler(v) {
        if (v) {
          let n = { ...v };
          if (v.bdnr) {
            this.formData = { ...n, ...JSON.parse(v.bdnr) };
          }
          this.templateDetail = n;
          this.setTemplateData(n);
        }
      }
    }
  },
  data() {
    return {
      formData: {},
      templateDetail: {}
    }
  },
  mounted() {
    // this.setTemplateStatus("actFill");
    this.setTemplateStatus(this.fillType);
  },
  unmounted() {
    this.setTemplateStatus("");
    this.setTemplateData({});
  },
  methods: {
    //统一校验form表单是否填写
    async validFormFields(refArr = []) {
      let result = {};
      const refs = refArr.map(ref => {
        const refData = this.$refs[ref].getFormData();
        return refData;
      });
      const validFormData = await Promise.all(refs).catch(err => {
        // this.$message.error(err);
        if(err.errorType && err.errorType === "step"){
          this.$message.error("请添加步骤");
          return
        }
        console.log(err,"err")
        this.$message.error("表单内容未填完,请填写后再提交");
      });
      if(validFormData){
        validFormData.forEach(item => {
            result = {...result,...item}
        })
        return result;
      }
      return false;
    },
    //试验配制条件options
    getDictOptions(dictType) {
      return this.dict.type[dictType] || [];
    },
    setTemplateStatus(status) {
      this.$store.commit('template/SET_TEMPLATE_STATUS', status)
    },
    setConditionOptions(options) {
      this.$store.commit('template/SET_CONDITION_OPTIONS', options)
    },
    setTemplateData(data) {
      this.$store.commit('template/SET_TEMPLATE_DATA', data)
    },
    //统一处理删除行
    deleteRow(index) {
      this.$refs.stepTableRef.deleteRow(index);
    },
    //获取版本号
    getVersionNum() {
      return this.formData.versionNum || "";
    },
    //统一处理blur事件，因为有效周期和过期日期是相关的，所以需要在有效周期失焦时更新过期日期
    onHandleBlur(fields) {
      const { key, effectivePeriodUnit, effectivePeriod, codeSTD, targetStartSolution } = fields;
      const { createTime } = this.formData;
      if (key === "effectivePeriod") {//统一处理有效周期失焦，计算失效事件，保证字段名不能变
        const start = moment(createTime);
        const end = start.add(Number(effectivePeriod), effectivePeriodUnit).format("YYYY-MM-DD HH:mm:ss");
        this.$refs.stepFormPackageRef.updateFormData("expireDate", end);
      } else if (key === "codeSTD") {//起始编号STD失焦时，更新stepDataSource
        const arr = Array.from({ length: codeSTD }, (item, index) => ({
          actSolutionVolumePrecision: 3,//小数点精度默认为3
          actSolutionConcentrationPrecision: 3,//小数点精度默认为3
          targetDiluentVolumePrecision: 3,//小数点精度默认为3
          targetStartSolutionVolumePrecision: 3,//小数点精度默认为3
          targetSolutionCode: `STD${Number(codeSTD) - index}`
        }));
        this.$refs.stepTableRef.updateDataSource(arr);
      } else if (key === "targetStartSolution") {//起始溶液体积失焦时，更新目标溶液预计浓度
        const arr = this.$refs.stepTableRef.getDataSource();
        arr.forEach((item, rowIndex) => {
          this.updateTargetStartSolutionVolume(rowIndex, item, targetStartSolution);
        })
      }
    },
    //统一处理table失焦事件
    onHandleTableBlur(params) {
      const { rowIndex, colKey, value, item } = params;
      console.log(rowIndex, colKey, value, item, "params")
      if (colKey === "targetSolutionVolume" || colKey === "targetSolutionConcentration" || colKey === "targetStartSolutionVolumePrecision" || colKey === "targetDiluentVolumePrecision") {
        const volume = this.$refs.stepFormPackageRef.getFormDataByKey("targetStartSolution") || 0;
        if (volume) {
          this.updateTargetStartSolutionVolume(rowIndex, item, volume);
        }
      }
    },
    //更新起始溶液体积时，更新目标溶液预计浓度
    updateTargetStartSolutionVolume(rowIndex, item, volume) {
      const precision = item.targetStartSolutionVolumePrecision || 0;
      const concentration = item.targetSolutionConcentration || 0;
      const targetVolume = item.targetSolutionVolume || 0;
      //目标溶液预计浓度:（目标溶液预计体积 乘以 起始溶液浓度）除以 起始溶液体积
      const result = ((concentration * targetVolume) / volume).toFixed(precision);
      this.$refs.stepTableRef.updateDataSourceByRowIndex(rowIndex, { targetStartSolutionVolume: result });
      if (targetVolume) {
        //预设稀释液体积:目标溶液预计体积 减去 源溶液预计体积；
        const precision1 = item.targetDiluentVolumePrecision || 0;
        const result1 = (targetVolume - result).toFixed(precision1);
        this.$refs.stepTableRef.updateDataSourceByRowIndex(rowIndex, { targetDiluentVolume: result1 });
      }
    }

  },

}
