<!-- PCR分析样品处理表 -->
<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="baseInfoRef" :formConfig="baseInfoFormConfig" :formData="formData" />
					<TableList label="template.common.reagentInfo" :columns="sysjColumns" :dataSource="resource" />

					<TableList label="template.common.instrumentInfo" :columns="yqColumns" :dataSource="yqResource" />

					<LineLabel label="template.common.operationSteps" />
					<div class="template-form-item">
						<BaseInfoFormPackage fieldItemLabel="template.common.operationSteps" ref="stepFormPackageRef"
							:formConfig="stepFormConfig" @blur="onHandleBlur" :formData="formData" />
						<div v-if="fillType == 'preFill'">
							<el-button type="primary" @click="downloadExcelTemplate">{{
								$t('template.common.downloadTemplate') }}</el-button>
							<el-button type="primary" @click="showImportExcelDialog">{{
								$t('template.common.importTemplate')
								}}</el-button>
						</div>

						<CustomTable @blur="onHandleTableBlur" @headerSelectChange="onHandleTableBlur"
							:ref="`stepTableRef`" :columns="tableStepColumns" :formData="formData" :prefixKey="`table`"
							:showOperation="fillType === 'preFill'"
							fieldItemLabel="template.common.operationSteps">
							<template slot="operation" slot-scope="{ row, rowIndex, columns }">
								<TableOpertaion :fillType="fillType" :row="row" :rowIndex="rowIndex" :columns="columns"
									@deleteRow="(rowIndex) => deleteRow(rowIndex)" ></TableOpertaion>
							</template>
						</CustomTable>
					</div>
					<Step ref="stepRef" :formData="formData.stepData"></Step>

					<BaseInfoFormPackage fieldItemLabel="template.pcr.pcr005.fj" label="template.pcr.pcr005.fj"
						ref="fjRef" :formConfig="getFjFormConfig" :formData="formData" />

					<BaseInfoFormPackage fieldItemLabel="template.common.remark" label="template.common.remark"
						ref="remarkRef" :formConfig="remarkConig" :formData="formData" />
				</div>
			</div>
		</div>
		<!-- <button @click="onSave">保存</button> -->
		<ImportExcelDialog ref="ImportExcelDialog" @onLoadData="onLoadExcelData" />
	</div>
</template>

<script>
import BaseInfoFormPackage from "@/components/Template/BaseInfoFormPackage";
import LineLabel from "@/components/Template/LineLabel";
import TableList from "@/components/Template/Table";
import Step from "@/components/Template/Step";
import templateMixin from "../../mixins/templateMixin.js";
import CustomTable from '@/components/Template/CustomTable.vue';
import { isValueEmpty } from '@/utils/index';
import { getLatestSnArr } from '@/api/template';
import { EventBus } from "@/utils/eventBus";
import { volumeConverter } from "@/utils/volConverter";//体积单位转换
import { convertConcentration } from "@/utils/conConverter";//浓度单位转换
import SelectReagentDialog from '../../dialog/SelectReagentDialog.vue';
import { getPCR005Config } from "../../formConfig/PCRTableConfig.js";
import TableOpertaion from "@/components/Template/operation/TableOpertaion.vue"
import { addTj, uniqeResource, uniqeResourceOne, addDecimals } from "@/utils/calUnitTools";
import ImportExcelDialog from '../../dialog/ImportExcelDialog'
export default {
	name: "PCR005",
	components: { BaseInfoFormPackage, LineLabel, TableList, Step, CustomTable, TableOpertaion, SelectReagentDialog, ImportExcelDialog },
	mixins: [templateMixin],
	props: {
		fillType: {
			type: String,
			default: 'preFill',
		},
	},
	computed: {
		tableStepColumns() {
			return getPCR005Config(this);
		},
		// 附件表单配置
		getFjFormConfig() {
			return [
				{
					type: "attachment",
					config: {
						attTitle: {
							label: 'template.pcr.pcr005.fj',
							type: "attachment",
							fillType: "actFill",
						},
					}
				}
			]
		},
		// 配置条件
		storageFormConfig() {
			return [
				{
					type: "conditionItem",
					config: {
						storageCondition: {
							label: 'template.common.storageConditionLabel',
							type: "select",
							fillType: "preFill",
							options: this.getDictOptions("business_cctj"),
							otherCode: "storageConditionOther",
						},
					}
				}
			];
		},
		// 备注表单配置
		remarkConig() {
			return [
				{
					type: "cellItem",
					config: {
						remark: {
							label: "",
							type: "textarea",
							fillType: "actFill",
							span: 1,
							placeholder: 'template.common.remarkPlaceholder',
							maxlength: 1000,
							rows: 5
						}
					}
				}
			]
		},
		// 试验基本信息表单配置
		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.common.processCondition',
					config: {
						pre: {
							label: 'template.common.preFill',
							type: "select",
							multiple: true,
							fillType: "preFill",
							options: this.getDictOptions('business_pztj'),
							otherCode: "preOther",
						},
						act: {
							label: 'template.common.actualFill',
							type: "select",
							fillType: "actFill",
							otherCode: "actOther",
							multiple: true,
							compareTo: "pre",
							options: this.getDictOptions('business_pztj')
						}
					}
				},
				{
					type: "cellItem",
					label: 'template.pcr.pcr005.clpbh',
					config: {
						clpbh: {
							label: '',
							type: "input",
							fillType: "actFill",
							otherCode: "clpbh",
						}
					}
				},
				{
					type: "cellItem",
					label: 'template.common.configurationTime',
					config: {
						startDate: {
							label: 'template.common.startTime',
							type: "input",
						},
						endDate: {
							label: 'template.common.endTime',
							type: "input",
						},
					}
				}
			]
		},
		// 操作步骤表单配置
		stepFormConfig() {
			return [
				{
					type: 'step',
					config: {
						solution: {
							labelWidth: 80,
							label: 'template.pcr.pcr002.xsy',
							type: 'input',
							fillType: 'preFill',
							subType: 'sj',
							subKey: 'subSolution',
							subFillType: 'actFill',
							maxlength: 20
						},
					}
				}
			]
		},
	},
	data() {
		return {
			reagentType: null, // 1-表单 2-表格
			formData: {},
			currentSubKey: "",//当前点击的子项key
			currentType: "",//当前点击的类型
			currentRowIndex: "",//当前点击的行索引
		};
	},
	mounted() {
		const formData = this.getFormDataByTemplateData();
		this.onHandleTableBlur()
	},
	methods: {
		downloadExcelTemplate() {
			this.exportExcel(['样品名称', '样品初始浓度', '稀释倍数', '预设样品吸样体积'], 'PCR分析样品处理表导入模板')
		},
		//选择试剂提交事件
		onSelectReagentSubmit(code, row) {

		},
		showImportExcelDialog() {
			this.$refs.ImportExcelDialog.show()
		},
		onLoadExcelData(excelData) {
			excelData.shift()
			let list = []
			excelData.forEach(item => {
				list.push({
					ypmc: item[0],
					ypcsnd: item[1],
					sxbs: item[2],
					ysypxytj: item[3],
					targetDiluentVolumePrecision: 3,
					actSolutionVolumePrecision: 3
				})
			})
			this.$refs.stepTableRef.addRows(list)
			this.$refs.ImportExcelDialog.cancel()
			setTimeout(() => {
				this.justUpdateFilledFormData();
			}, 100);
			this.onHandleTableBlur()
		},
		// 失去焦点，计算
		onHandleTableBlur() {
			let content = this.getFilledFormData();
			// 预填
			let ysypxytjUnit = content.headerSelectFields.ysypxytjUnit
			let ysxsyxytjUnit = content.headerSelectFields.ysxsyxytjUnit

			let ypzndUnit = content.headerSelectFields.ypzndUnit
			let ypcsndUnit = content.headerSelectFields.ypcsndUnit
			if (this.fillType === "preFill") {
				let tableList = content.stepTableFormData
				if (tableList && tableList.length > 0) {
					for (let i = 0; i < tableList.length; i++) {
						let item = tableList[i]
						if (
							isValueEmpty(ysypxytjUnit) ||
							isValueEmpty(ysxsyxytjUnit) ||
							isValueEmpty(item.sxbs) ||
							isValueEmpty(item.ysypxytj) ||
							isValueEmpty(item.actSolutionVolumePrecision) ||
							isValueEmpty(item.ypcsnd)
						) {
							continue;
						}

						// 计算预设稀释液吸样体积  公式：(稀释倍数-1)*样品理论体积
						let ysxsyxytj = (item.sxbs - 1) * item.ysypxytj
						ysxsyxytj = volumeConverter.convert(ysxsyxytj + ysypxytjUnit, ysxsyxytjUnit).toFixed(
							item.actSolutionVolumePrecision
						)
						tableList[i].ysxsyxytj = ysxsyxytj


						// 计算样品终浓度： 样品初始浓度/稀释倍数
						let ypznd = (item.ypcsnd) / item.sxbs
						ypznd = convertConcentration.convert(ypznd + ypcsndUnit, ypzndUnit).toFixed(
							item.targetDiluentVolumePrecision
						)
						tableList[i].ypznd = ypznd

					}
				}
				this.$refs.stepTableRef.updateDataSource(tableList);
			}
		},
		//获取已填写的表单数据
		getFilledFormData() {
			return this.getFilledFormDataByRefs(["baseInfoRef", "stepFormPackageRef", "stepTableRef", "stepRef", "fjRef", "remarkRef"])
		},
		async getFormData() {
			let content = await this.validFormFields(["baseInfoRef", "stepFormPackageRef", "stepTableRef", "stepRef", "fjRef", "remarkRef"]);
			return content;
		},
		getResource() {
			let content = this.getFilledFormData();
			console.log(content)
			//生成resource
			let tmpResource = []
			if (this.fillType === "actFill") {
				let tableList = content.stepTableFormData
				if (tableList && tableList.length > 0) {
					for (let i = 0; i < tableList.length; i++) {
						//配置的试剂
						let item = tableList[i]
						console.log('表格item:' + JSON.stringify(item))

						//使用的

						tmpResource.push({
							mc: null,
							bh: content.subSolution,
							ph: null,
							ndz: null,
							nd: null,
							nddw: null,
							ly: 'ELN配制',
							sxrq: null,
							kc: null,
							kcdw: null,
							syl: item.ysxsyxytj,
							type: 1,
							elnType: this.product,
							syldw: content.headerSelectFields.sjxsyxytjUnit,
							yxzq: null,
							yxzqdw: null,
						})

					}
				}
			}
			if (tmpResource.length > 0) {
				tmpResource = uniqeResourceOne(tmpResource)
			}
			//使用的试剂、仪器
			const stepResource = this.$refs.stepRef.getStepResource()
			this.resourceTmp = uniqeResource(tmpResource, stepResource.sjResource || [])
			this.yqResourceTmp = stepResource.yqResource || []
			return this.resourceTmp;
		},
		//保存
		async onSave() {
			let content = this.$refs.stepRef.getStepResource();
			console.log(content);

		},
		// 删除表格行
		deleteRow(rowIndex) {
			const stepTableRef = this.$refs['stepTableRef'];
			if (stepTableRef) {
				stepTableRef.deleteRow(rowIndex);
			}
		},

	}
};
</script>
<style rel="stylesheet/scss" lang="scss">
.mt-20 {
	margin-top: 20px;
}

.print-btn {
	margin-bottom: 20px;
}
</style>