<!-- Ames实验（掺入法）平皿培养记录表 -->
<template>
  <div>
    <div class="detail-container">
      <div class="detail-title">
        <img src="@/assets/images/detail-title.png" />{{ formData.bdmc
        }}<img src="@/assets/images/detail-title.png" />
      </div>
      <div class="detail-content">
        <div class="content">
          <BaseInfoFormPackage
            fieldItemLabel="template.common.baseInfo"
            label="template.common.baseInfo"
            :ref="refConf.base"
            :formConfig="baseInfoFormConfig"
            :formData="formData"
          />

          <!-- <LineLabel label="template.dl.dl003.sysj" /> -->
          <TableList label="template.common.reagentInfo" :columns="sysjColumns" :dataSource="resource" />

          <LineLabel label="template.dl.dl007.yqsyxx" />
          <CustomTable
            :columns="yqsyColumns"
            :ref="refConf.yqsy"
            @onRegentSubmit="(e) => onRegentSubmit(e)"
            :showOperation="fillType === 'actFill'"
            :showAddRow="fillType === 'actFill'"
            :formData="formData"
            :prefixKey="`yqsyTable`"
          >
            <template slot="operation" slot-scope="{ row, rowIndex, columns }">
              <TableOpertaionDelete
                :row="row"
                :rowIndex="rowIndex"
                :columns="columns"
                @deleteRow="() => deleteTableRow(rowIndex, 'yqsyTableRef')"
              ></TableOpertaionDelete>
            </template>
          </CustomTable>

          <LineLabel label="template.common.operationSteps" />
          <div class="template-form-item">
            <BaseInfoFormPackage
              fieldItemLabel="template.common.operationSteps"
              :ref="refConf.czInfo"
              :formConfig="czInfoFormConfig"
              :formData="formData"
              @clickButton="handleClickButton"
              @onRegentSubmit="onRegentSubmit"
            />
            <CustomTable
              fieldItemLabel="template.common.operationSteps"
              :columns="jzjzColumns"
              @blur="operateBlur"
              :ref="'jzjzTableRef'"
              @onRegentSubmit="(e) => onRegentSubmit(e)"
              :showOperation="fillType === 'actFill'"
              :showAddRow="fillType === 'actFill'"
              :formData="{stepTableFormData:formData.stepTableFormData_1,headerSelectFields:{}}"
              :showHeaderSelect="fillType === 'actFill'"
              :prefixKey="`jzjzTable`"
            >
              <template slot="operation" slot-scope="{ row, rowIndex, columns }">
                <TableOpertaionDelete
                  :row="row"
                  :rowIndex="rowIndex"
                  :columns="columns"
                  @deleteRow="() => deleteTableRow(rowIndex, 'jzjzTableRef')"
                ></TableOpertaionDelete>
              </template>
            </CustomTable>
          </div>

          <BaseInfoFormPackage
            fieldItemLabel="template.dl.dl007.bz"
            label="template.dl.dl007.bz"
            :ref="refConf.remark"
            :formConfig="remarkConig"
            :formData="formData"
          />
          
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BaseInfoFormPackage from '@/components/Template/BaseInfoFormPackage'
import TableOpertaionDelete from '@/components/Template/operation/TableOpertaionDelete.vue'
import CustomTable from '@/components/Template/CustomTable.vue'
import LineLabel from '@/components/Template/LineLabel'
import TableList from '@/components/Template/Table'
import Step from '@/components/Template/Step'
import templateMixin from '../../mixins/templateMixin'
import moment from 'moment'

const refConf = {
  base: 'baseInfoRef',
  yqsy: 'yqsyTableRef',
  czInfo: 'czInfoRef',
  remark: 'remarkRef',
  jzjz: 'jzjzTableRef'
}
const refNames = Object.values(refConf)

export default {
  name: 'DL003',
  components: {
    BaseInfoFormPackage,
    LineLabel,
    TableList,
    Step,
    CustomTable,
    TableOpertaionDelete
  },
  mixins: [templateMixin],
  props: {
    fillType: {
      type: String,
      default: 'preFill'
    }
  },
  computed: {
    // 备注表单配置
    remarkConig() {
      return [
        {
          type: 'cellItem',
          config: {
            remark: {
              label: '',
              type: 'textarea',
              fillType: 'actFill',
              span: 1,
              placeholder: 'template.common.remarkPlaceholder',
              maxlength: 1000,  
              rows: 5
            }
          }
        }
      ]
    },
    mounted() {
    
      // if (this.fillType === "actFill") {
      //   this.handleUpdateCode(formData);
      // }
      // const re = convertConcentration.convert('100mg/mL',"ng/mL")
    },
    // 试验基本信息表单配置
    baseInfoFormConfig() {
      return [
        {
          type: 'cardItem',
          config: {
            studyMc: {
              label: 'template.common.testName',
              type: 'input',
              disabled: true
            },
            studySn: {
              label: 'template.common.testNumber',
              type: 'input',
              disabled: true
            }
          }
        },
        {
          type: 'conditionItem',
          label: 'template.dl.dl007.sydd',
          config: {
            pytj: {
              span: 1,
              label: 'template.dl.dl003.pytj',
              type: 'select',
              options: this.getDictOptions('business_pytj'),
              fillType: 'actFill',
              otherCode: 'pytjOther'
            },
            sydd: {
              span: 1,
              label: 'template.dl.dl007.sydd',
              type: 'select',
              options: this.getDictOptions('business_sydd'),
              fillType: 'actFill',
              otherCode: 'syddOther'
            }
          }
        },
        {
          type: 'cellItem',
          label: 'template.dl.dl003.czsj',
          config: {
            startDate: {
              label: 'template.common.startTime',
              type: 'input',
              disabled: true
            },
            endDate: {
              label: 'template.common.endTime',
              type: 'input',
              disabled: true
            }
          }
        }
      ]
    },
    
    // 仪器使用信息
    yqsyColumns() {
      return [
        {
          label: 'template.dl.dl007.yqbh',
          prop: 'yqbh',
          bodyType: 'yq',
          bodyFillType: 'actFill'
        },
        {
          label: 'template.dl.dl007.yqmc',
          prop: 'yqmc',
          bodyType: 'input',
          bodyDisabled: true,
          bodyFillType: 'actFill',
          disabled: true
        },
        {
          label: 'template.dl.dl007.yqxh',
          prop: 'yqxh',
          bodyType: 'input',
          bodyDisabled: true,
          bodyFillType: 'actFill',
          disabled: true
        },
        {
          label: 'template.dl.dl007.xccsjzjdrq',
          prop: 'jzrq',
          bodyType: 'input',
          bodyDisabled: true,
          bodyFillType: 'actFill',
          disabled: true
        }
      ]
    },

    // 操作信息表信息
    czInfoFormConfig() {
      return [
        {
          type: 'cellItem',
          config: {
            jzkssj: {
              label: 'template.dl.dl003.jzkssj',
              type: 'input',
              fillType: 'actFill',
              maxlength: 200,
              subType: 'button',
              subKey: 'jzkssj',
              buttonName: 'template.dl.dl003.ksButton',
            },
            jzjssj: {
              label: 'template.dl.dl003.jzjssj',
              type: 'input',
              fillType: 'actFill',
              maxlength: 200,
              subType: 'button',
              subKey: 'jzjssj',
              buttonName: 'template.dl.dl003.jsButton',
            },
            fssygbh: {
              label: 'template.dl.dl003.fssygbh',
              type: 'yq',
              fillType: 'actFill',
            },
            pyx: {
              label: 'template.dl.dl003.pyx',
              type: 'yq',
              fillType: 'actFill',
            },
            fstj: {
              label: 'template.dl.dl003.fstj',
              type: 'select',
              options: this.getDictOptions('business_fstj'),
              fillType: 'actFill',
              otherCode: 'fstjOther'
            },
            czpytj: {
              label: 'template.dl.dl003.pytj',
              type: 'select',
              options: this.getDictOptions('business_pytj'),
              fillType: 'actFill',
              otherCode: 'czpytjOther'
            },
            frswd: {
              label: 'template.dl.dl003.frswd',
              type: 'input',
              fillType: 'actFill',
              maxlength: 50,
            },
            pykssj: {
              label: 'template.dl.dl007.pykssj',
              fillType: 'actFill',
              type: 'input',
              subType: 'button',
              subKey: 'pykssj',
              buttonName: 'template.dl.dl003.ksButton',
            },
            
          }
        }
      ]
    },
    // 操作信息表菌种列表
    jzjzColumns() {
      return [
        {
          label: 'template.dl.dl003.jzjzhbh',
          prop: "targetSolutionCode",
          bodyType: 'input',
          bodySubType: "span",
					bodySubKey: "subTargetSolutionCode",
          myCodeFields: ["targetSolutionCode", "subTargetSolutionCode"],//分装的母液编号字段
          bodyFillType: 'actFill'
        },
        {
          label: 'template.dl.dl003.jzlybh',
          prop: 'jzlybh',
          bodyType: 'sj',
          bodyFillType: 'actFill',
        },
        {
          label: 'template.dl.dl003.rtbh',
          prop: 'rtbh',
          bodyType: 'sj',
          bodyFillType: 'actFill',
        },
        {
          label: 'template.dl.dl003.jzjrtj',
          prop: 'jzjrtj',
          headerSelectKey: "targetDiluentVolumeUnit",
					headerOptions: this.getDictOptions('business_tjdw'),
          bodyType: 'inputNumber',
					bodyMaxlength: 10,
          bodyFillType: 'actFill',
          fillType: 'actFill',
        }
        // {
				// 	label: "template.sp.sp003.ysmbrynd",
				// 	prop: "targetSolutionConcentration",
				// 	width: 210,
				// 	showWidth: 120,
				// 	headerSelectKey: "targetSolutionConcentrationUnit",
				// 	fillType: "preFill",
				// 	headerOptions: this.getDictOptions('business_nddw'),
				// 	bodyType: "inputNumber",
				// 	bodyFillType: "preFill",
				// 	bodyMaxlength: 10,
				// 	headerSelectTo:"actSolutionConcentrationUnit",
				// },
      ]
    },
  },
  data() {
    return {
      formData: {},
      refConf
    }
  },
  methods: {
    // 删除表格行
    async deleteTableRow(rowIndex, refName) {
      this.$refs[refName].deleteRow(rowIndex)
    },
    // 点击按钮
    handleClickButton(_item, signData) {
      this.$refs.czInfoRef.updateFormData(
        _item.subKey,
        moment().format('YYYY/MM/DD HH:mm'),
        { isUpdateRecord: true, signData }
      )
     
    },
    // 获取已填写的表单数据
    getFilledFormData() {
      return this.getFilledFormDataByRefs(refNames)
    },
    // 获取填写完成的表单数据
    async getFormData() {
      return await this.validFormFields(refNames)
    },
    // 只做校验
    async validFields() {
      return await this.validFormFields(refNames)
    },
    getResource() {
      // const stepResource = this.$refs.yqsyTableRef.getStepResource()
      // 使用的试剂、仪器
      // this.resourceTmp = stepResource.sjResource || []
      // this.yqResourceTmp = stepResource.yqResource || []
      // return this.resourceTmp
    },
    onRegentSubmit(e) {
      const { selectInfo, key, rowIndex } = e
      const { row } = selectInfo

      if (key === 'yqbh') {
        const params = {
          yqmc: row.mc,
          yqxh: row.xh,
          jzrq: row.jzrq
        }
        this.$refs.yqsyTableRef.updateDataSourceByRowIndex(rowIndex, params)
      }
      if (key === 'qxbd') {
        this.$refs.czInfoRef.updateFormData('pykssj', row.startDate)
      }
    },
    // 保存
    async onSave() {
      const formData = this.getStepResource()
      console.log(formData, 'formData')
    },
		//处理table失焦事件
    async operateBlur(params) {
      let isGeneratingSubCode = false;
      const { dataSource = [], rowIndex } = params; // 重点：接收当前行索引rowIndex
      // 1. 数据源为空/正在生成中，直接返回
      if (dataSource.length === 0 || isGeneratingSubCode) {
        return;
      }

      // 2. 获取当前失去焦点的行（核心：只处理当前行，而非遍历整表）
      const currentItem = dataSource[rowIndex];
      if (!currentItem) {
        return;
      }

      // 3. 条件判断：有targetSolutionCode 且 无subTargetSolutionCode
      const hasTargetCode = !!currentItem.targetSolutionCode;
      const noSubTargetCode = !currentItem.subTargetSolutionCode;
      if (!hasTargetCode || !noSubTargetCode) {
        return; // 不满足条件，直接返回
      }

      try {
        // 4. 加锁，防止重复请求
        isGeneratingSubCode = true;

        // 5. 调用接口生成子码（仅传当前行的参数）
        const subCode = await this.getLatestSnArr([{ 
          pre: currentItem.targetSolutionCode, 
          type: 1 
        }]);

        // 6. 赋值到当前行（兼容接口返回空的情况）
        currentItem.subTargetSolutionCode = subCode[0] || '';

        // 7. 只更新当前行的表格数据（而非遍历全表，提升性能）
        if (this.$refs.jzjzTableRef) {
          this.$refs.jzjzTableRef.updateDataSourceByRowIndex(rowIndex, { ...currentItem });
        }
      } catch (error) {
        // 8. 异常捕获，给出友好提示
        this.$message.error('子码生成失败，请重试');
      } finally {
        // 9. 解锁，允许后续请求
        isGeneratingSubCode = false;
      }
    }
    //选择table header下拉框也要更新体积
		// onHeaderSelectChange(data){
		// 	const {key, headerSelectFields,dataSource=[]} = data;
		// 	const keys = [
		// 		'targetDiluentVolumeUnit',
		// 	]
		// 	if(keys.includes(key)){
		// 		const {targetStartSolution,subTargetStartSolution} = this.$refs.stepFormPackageRef?.getFilledFormData();
		// 		const params = {
		// 			subTargetStartSolution,
		// 			headerSelectFields
		// 		}
		// 		this.batchUpdateTargetStartSolutionVolume(dataSource,targetStartSolution,params)
		// 	}
		// },
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.mt-20 {
  margin-top: 20px;
}

.print-btn {
  margin-bottom: 20px;
}
.config-header-end {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 15px;
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}
</style>
