<template>
  <div class="template-table">
    <component ref="templateComponent" :sn="sn" :is="getTemplateComponent()" :templateData="templateData"
      :fillType="fillType">
    </component>
    <SubPackageDialog ref="subPackageDialogRef"></SubPackageDialog>
    <TagPrintDialog ref="tagPrintDialogRef"></TagPrintDialog>
    <SelectReagentDialog ref="selectReagentDialogRef" />
    <SelectInstrumentDialog ref="selectInstrumentDialogRef" />
    <SelectMixReagentDialog ref="selectMixReagentDialogRef" />
    <EditSign ref="editSignRef" @cancel="handleEditSignCancel" @callback="handleEditSignCallback" />
  </div>
</template>

<script>
import { EventBus } from "@/utils/eventBus";
import { debounce } from 'lodash-es'
import SubPackageDialog from "./dialog/SubPackageDialog.vue";//分装弹窗
import TagPrintDialog from "./dialog/PrintTagDialog.vue";//标签打印弹窗
import SelectReagentDialog from "./dialog/SelectReagentDialog.vue";//选择试剂弹窗
import SelectInstrumentDialog from "./dialog/SelectInstrumentDialog.vue";//选择仪器弹窗
import SelectMixReagentDialog from "./dialog/SelectMixReagentDialog.vue";//选择试剂/供试品/给药制剂弹窗
import EditSign from "./dialog/EditSign.vue";//电子签名弹窗

//色谱
import SP001 from "./comps/sp/SP001.vue";
import SP002 from "./comps/sp/SP002.vue";
import SP003 from "./comps/sp/SP003.vue";
import SP00456 from "./comps/sp/SP00456.vue";
import SP007 from "./comps/sp/SP007.vue";
//色谱生物样品分析方法学样品制备表-10个类似
import SP008 from "./comps/sp/SWYPFXFFXYPZBB/SP008.vue";
import SP009 from "./comps/sp/SWYPFXFFXYPZBB/SP009.vue";
import SP010 from "./comps/sp/SWYPFXFFXYPZBB/SP010.vue";
import SP011 from "./comps/sp/SWYPFXFFXYPZBB/SP011.vue";
import SP012 from "./comps/sp/SWYPFXFFXYPZBB/SP012.vue";
import SP013 from "./comps/sp/SWYPFXFFXYPZBB/SP013.vue";
import SP014 from "./comps/sp/SWYPFXFFXYPZBB/SP014.vue";
import SP015 from "./comps/sp/SWYPFXFFXYPZBB/SP015.vue";
import SP016 from "./comps/sp/SWYPFXFFXYPZBB/SP016.vue";
import SP017 from "./comps/sp/SWYPFXFFXYPZBB/SP017.vue";
import SP018 from "./comps/sp/SWYPFXFFXYPZBB/SP018.vue";
import Demo from "./comps/sp/Demo.vue";
//供试品
import SYWZPZJHB from "./comps/gsp/SYWZPZJHB.vue";
import MJYLQSQD from "./comps/gsp/MJYLQSQD.vue";

// PCR
import PCR001 from "./comps/pcr/PCR001.vue";
import PCR002 from "./comps/pcr/PCR002.vue";

export default {
  name: "TemplateTable",
  components: {
    Demo,
    SubPackageDialog, TagPrintDialog, SelectReagentDialog, SelectInstrumentDialog, SelectMixReagentDialog, EditSign,
    //供试品
    MJYLQSQD, SYWZPZJHB,
    //色谱
    SP001, SP002, SP003, SP00456,SP007, SP008, SP009, SP010, SP011, SP012, SP013, SP014, SP015, SP016, SP017, SP018,
    // PCR
    PCR001, PCR002
  },
  props: {
    sn: {
      type: String,
      default: '',
    },
    fillType: {
      type: String,
      default: 'preFill',
    },
    templateData: {
      type: Object,
      default: () => { },
    },
    emitName: {
      type: String,
      default: 'onModifyRecord',
    },
  },
  computed: {

    templateComponentMap() {
      if (!this.componentMap) {
        this.componentMap = {
          //色谱
          'SP001': 'SP001',
          'SP002': 'SP002',
          'SP003': 'SP003',
          'SP004': 'SP00456',
          'SP005': 'SP00456',
          'SP006': 'SP00456',
          'SP007': 'SP007',
          'SP008': 'SP008',
          'SP009': 'SP009',
          'SP010': 'SP010',
          'SP011': 'SP011',
          'SP012': 'SP012',
          'SP013': 'SP013',
          'SP014': 'SP014',
          'SP015': 'SP015',
          'SP016': 'SP016',
          'SP017': 'SP017',
          'SP018': 'SP018',
          //供试品
          'SYWZPZJHB': 'SYWZPZJHB',
          'MJYLQSQD': 'MJYLQSQD',
          //PCR
          'PCR001': 'PCR001',
          'PCR002': 'PCR002'
        }
      }
      return this.componentMap || "Demo"
    }
  },
  watch: {
    sn: {
      immediate: true,
      handler(v) {
        console.log(v, "sn")
      }
    },
    templateData: {
      immediate: true,
      deep: true,
      handler(v) {
        if (v) {
          if (v.zdxgjl) {
            this.zdxgjl = JSON.parse(v.zdxgjl) || [];
          }
          if (v.fhyjjl) {
            this.fhyjjl = JSON.parse(v.fhyjjl) || [];
          }
          if (v.zdgxjl) {
            this.fieldCheckObj = JSON.parse(v.zdgxjl) || {};
          }
        }
      }
    }
  },
  provide() {
    return {
      //分发给子组件的fillType
      templateData: this.templateData,
      templateFillType: this.fillType,
      getZdxgjl: () => this.zdxgjl,
      getFhyjjl: () => this.fhyjjl,
      getFieldCheckObj: () => this.fieldCheckObj,
      //更新提交记录
      updateZdxgjl: (data) => {
        this.zdxgjl.unshift(data);
      },
      //更新复核意见记录
      updateFhyjjl: (data) => {
        this.fhyjjl.unshift(data);
      },
      //替换复核意见记录
      replaceFhyjjl: (data) => {
        this.fhyjjl = data;
      },
      //更新字段检查对象
      updateFieldCheckObj: (data) => {
        this.fieldCheckObj = { ...this.fieldCheckObj, ...data };
      },

    }
  },
  data() {
    return {
      info: {},
      zdxgjl: [],
      fhyjjl: [],
      fieldCheckObj: {},
      currentEditSignUuid: null, // 当前请求EditSign的HandleFormItem的uuid
      latestParams: {},//用于存储最新的params
      hasCustomTable: false,//是否有自定义表格
    };
  },
  created() {
    this.debouncedEmit = debounce(this.emitToParent, 100)
  },
  mounted() {
    EventBus.$on('onModifyRecord', this.handleModyfyRecord);
    //分装弹窗
    EventBus.$on("showSubPackageDialog", (data) => {
      this.$refs.subPackageDialogRef.show(data)
    })
    //标签打印弹窗
    EventBus.$on("showTagPrintDialog", (data) => {
      this.$refs.tagPrintDialogRef.show(data)
    })
    //选择仪器弹窗
    EventBus.$on("showSelectInstrumentDialog", (data) => {
      this.$refs.selectInstrumentDialogRef.show(data.studyFormId, data)
    })
    //选择试剂弹窗
    EventBus.$on("showSelectReagentDialog", (data) => {
      this.$refs.selectReagentDialogRef.show(data.studyFormId, data)
    })
    //选择试剂/供试品/给药制剂弹窗
    EventBus.$on("showSelectMixReagentDialog", (data) => {
      this.$refs.selectMixReagentDialogRef.show(data.studyFormId, data)
    })
    //显示电子签名弹窗
    EventBus.$on("showEditSignDialog", (data) => {
      this.currentEditSignUuid = data.uuid;
      this.$refs.editSignRef.show();
    })
  },
  beforeDestroy() {
    // 记得移除监听，避免内存泄漏
    EventBus.$off('onModifyRecord');
    EventBus.$off("showSubPackageDialog");
    EventBus.$off("showTagPrintDialog");
    EventBus.$off("showSelectReagentDialog");
    EventBus.$off("showSelectInstrumentDialog");
    EventBus.$off("showSelectMixReagentDialog");
    EventBus.$off("showEditSignDialog");
    this.debouncedEmit.cancel()
  },
  methods: {
    handleModyfyRecord(data) {
      const { source } = data;
      if (source === "customTable") {
        this.latestParams = data;
        // delete this.latestParams.source
        this.hasCustomTable = true
        // 取消之前的等待
        this.debouncedEmit.cancel()
        this.emitToParent()
      }else if(!source  && !this.hasCustomTable){
        this.latestParams = data
        this.debouncedEmit()
      }
    },
    emitToParent() {
      if (this.latestParams) {
        console.log(this.latestParams,"this.latestParams")
        this.$emit(this.emitName, this.latestParams)
      }
    },
    // 处理电子签名取消事件
    handleEditSignCancel() {
      if (this.currentEditSignUuid) {
        EventBus.$emit('onEditSignCancel', { uuid: this.currentEditSignUuid });
        EventBus.$emit('onFormEditSignCancel', { uuid: this.currentEditSignUuid });
        this.currentEditSignUuid = null;
      }
    },
    // 处理电子签名确认回调事件
    handleEditSignCallback(data) {
      if (this.currentEditSignUuid) {
        EventBus.$emit('onEditSignCallback', { uuid: this.currentEditSignUuid, data });
        this.currentEditSignUuid = null;
      }
    },
    async getFormData() {
      if (this.fillType === "actFill") {
        //检查是否有未填写的复核意见
        const flag = this.fhyjjl.every((item) => !!item.content && !!item.reply)
        console.log(this.fhyjjl, flag, "flag")
        if (!flag) {
          this.$message.error("疑问项还未回复，请回复后再提交");
          return;
        }
      }
      return await this.$refs.templateComponent.getFormData();
    },
    getResource() {
      return this.$refs.templateComponent.getResource();
    },
    getYqResource() {
      return this.$refs.templateComponent.getYqResource();
    },
    getFilledFormData() {
      return this.$refs.templateComponent.getFilledFormData();
    },
    getTemplateComponent() {
      return this.templateComponentMap[this.sn]
    },
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
.template-table {
  background: #fff;
  padding: 10px 10px;
  width: 100%;
}
</style>