<!-- 试验物质配制记录表（平行稀释） -->
<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.gspsywzInfo" :columns="gspColumns" :dataSource="resourceGsp" />
					<TableList label="template.common.sjInfo" :columns="sjColumns" :dataSource="resourceSj" />
					<TableList label="template.common.instrumentInfo" :columns="yqColumns" :dataSource="yqResource" />
					<!-- 计算公式 -->
					<BaseInfoFormPackage fieldItemLabel="template.gsp.GSP003.calcConditionLabel"
						label="template.gsp.GSP003.calcConditionLabel" ref="calcConditionRef"
						:formConfig="calcFormConfig" :formData="formData" />
					<LineLabel label="template.common.operationSteps" />
					<!-- 平行配制区域 -->
					<div :label="$t('template.common.pxpz')"
						v-for="(paralleConfig, paralleIndex) in formData.paralleConfigs"
						:key="'paralle_' + paralleIndex">

						<div class="template-form-item">
							<div class="config-header-right">
								<el-button type="primary" v-if="fillType === 'preFill'" @click="handleAddParalle">{{
									$t('template.common.addBtn') }}</el-button>
								<el-button v-if="fillType === 'preFill' && formData.paralleConfigs.length > 1"
									type="danger" @click="deleteParalleConfig(paralleIndex)">{{
										$t('template.common.deleteBtn') }}</el-button>
							</div>
							<BaseInfoFormPackage @clickable="(e) => handleClickable('paralle', paralleIndex, e)"
								:ref="`paralleStepFormPackageRef_${paralleIndex}`" :formConfig="paralleStepFormConfig"
								:formData="paralleConfig" :prefixKey="'paralle' + paralleIndex"
								:fieldItemLabel="$t('template.common.pxpz')" />
							<CustomTable @blur="(e) => onHandleTableBlur('paralle', paralleIndex, e)"
								:ref="`paralleStepTableRef_${paralleIndex}`"
								:showOperation="fillType === 'actFill' || fillType === 'preFill'"
								:columns="paralleStepColumns"
								@beforeReagentSubmit="(data) => onTableBeforeReagentSubmit(data, paralleIndex, paralleConfig)"
								@onRegentSubmit="(data) => onTableRegentSubmit('paralle', paralleIndex, data)"
								:formData="paralleConfig" :prefixKey="'paralle' + paralleIndex"
								:fieldItemLabel="$t('template.common.pxpz')">
								<template slot="operation" slot-scope="{ row, rowIndex, columns }">
									<TableOpertaion @printTag="(e) => printTag(e, 'paralleConfigs', paralleIndex)"
										@startConfig="(val) => startConfig(val, 'paralleConfigs', paralleIndex)"
										@configComplete="(val) => configComplete(val, 'paralleConfigs', paralleIndex)"
										@subPackageSubmit="(val) => subPackageSubmit(val, 'paralleConfigs', paralleIndex)"
										:fillType="fillType" :row="row" :rowIndex="rowIndex" :columns="columns"
										@deleteRow="(rowIndex) => deleteRow(rowIndex, 'paralle', paralleIndex)">
									</TableOpertaion>
								</template>
							</CustomTable>

							<Step class="mt-0 s-container" :ref="`paralleStepRef_${paralleIndex}`"
								:formData="paralleConfig.paralleStepData" :fieldItemLabel="$t('template.common.pxpz')"
								:prefixKey="'paralle' + paralleIndex"></Step>
						</div>
					</div>
					<BaseInfoFormPackage fieldItemLabel="template.common.remark" label="template.common.remark"
						ref="remarkRef" :formConfig="remarkConig" :formData="formData" />
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { EventBus } from "@/utils/eventBus";
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 SelectReagentDialog from '../../dialog/SelectReagentDialog.vue';
import TableOpertaion from "@/components/Template/operation/TableOpertaion.vue";
import { getExpireDate, duplicateResource } from "@/utils/index.js";
import { isCommonUnit } from "@/utils/conTools";
import moment from "moment";
import { addTj, uniqeResource, uniqeResourceOne, addDecimals } from "@/utils/calUnitTools";
export default {
	name: "GSP004",
	components: { BaseInfoFormPackage, LineLabel, TableList, Step, CustomTable, SelectReagentDialog, TableOpertaion },
	mixins: [templateMixin],
	props: {
		fillType: {
			type: String,
			default: 'preFill',
		},
		sn: {
			type: String,
			default: '',
		},
	},
	watch: {
		fillType: {
			immediate: true,
			handler(v) {
				console.log(v, "fillType")
			}
		},
	},
	computed: {
		// 备注表单配置
		remarkConig() {
			return [
				{
					type: 'cellItem',
					config: {
						remark: {
							label: '',
							type: 'textarea',
							fillType: 'actFill',
							span: 1,
							placeholder: 'template.common.remarkPlaceholder',
							maxlength: 1000,
							rows: 5
						}
					}
				}
			];
		},
		// 计算公式
		calcFormConfig() {
			return [
				{
					type: "cardItem",
					config: {
						calcFormConfig: {
							label: 'template.gsp.GSP003.calcConditionLabel',
							type: "input",
							span:1,
							fillType: "preFill",
							maxlength: 50
						},
					}
				}
			];
		},
		// 试验基本信息表单配置
		baseInfoFormConfig() {
			return [
				{
					type: 'cardItem',
					config: {
						studyMc: {
							label: 'template.common.testName',
							type: 'input',
							disabled: true
						},
						studySn: {
							label: 'template.common.testNumber',
							type: 'input',
							disabled: true
						},
						methodCode: {
							label: 'template.common.methodCode',
							type: 'input',
							fillType: 'preFill',
							maxlength: 50
						},
						versionNum: {
							label: 'template.common.versionNumber',
							type: 'inputNumber',
							fillType: 'actFill',
							prepend: 'V',
							maxlength: 50
						}
					}
				},
				{
					type: 'conditionItem',
					label: 'template.common.testConfigurationConditions',
					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,
							options: this.getDictOptions('business_pztj'),
							compareTo: 'pre'
						}
					}
				},
				{
					type: 'conditionItem',
					label: 'template.sp.sp00456.rqcz',
					config: {
						containerMaterial: {
							label: 'template.sp.sp00456.rqcz',
							type: 'select',
							options: this.getDictOptions('business_rqcz'),
							fillType: 'actFill',
							multiple: true,
							otherCode: 'containerMaterialOther'
						}
					}
				},
				{
					type: 'cellItem',
					label: 'template.common.configurationTime',
					config: {
						startDate: {
							label: 'template.common.startTime',
							type: 'input'
						},
						endDate: {
							label: 'template.common.endTime',
							type: 'input'
						}
					}
				}
			];
		},
		paralleStepFormConfig() {
			return [
				{
					type: 'step',
					config: {
						sfxyzjfx: {
							label: 'template.gsp.GSP003.sfxyzjfx',
							type: "select",
							with:'100%',
							span:1,
							fillType: "actFill",
							options: [
								{label:'是',value:'是'},
								{label:'否',value:'否'}
							]
						},
						solution: {
							label: 'template.sp.sp00456.xsy',
							type: 'input',
							fillType: 'preFill',
							subType: 'sj',
							subKey: 'subSolution',
							subFillType: 'actFill',
							maxlength: 20
						},
						paralleStepStorageCondition: {
							label: 'template.sp.sp00456.cctj',
							type: 'select',
							fillType: 'preFill',
							options: this.getDictOptions('business_cctj'),
							otherCode: 'paralleStepStorageConditionOther'
						}
					}
				}
			];
		},
		paralleStepColumns() {
			return [
				{
					label: 'template.sp.sp00456.mbrybh',
					prop: 'targetSolutionCode',
					bodyType: 'input',
					bodySubType: 'span',
					bodySubKey: 'subTargetSolutionCode',
					bodyFillType: 'preFill',
					myCodeFields: ["targetSolutionCode", "subTargetSolutionCode"],//分装的母液编号字段
					maxVolumeField: "actSolutionVolume",//分装的最大量字段
					maxVolumeFieldUnit: "actSolutionVolumeUnit",//分装的最大量单位字段
					showWidth: 180,
					width: 280
				},
				{
					label: 'template.sp.sp00456.ysmbrynd',
					prop: 'targetSolutionConcentration',
					width: 280,
					showWidth: 120,
					headerSelectKey: 'targetSolutionConcentrationUnit',
					fillType: 'preFill',
					headerOptions: this.getDictOptions('business_nddw'),
					bodyType: 'inputNumber',
					bodyFillType: 'preFill',
					bodyMaxlength: 10,
					headerSelectTo: "actSolutionConcentrationUnit",
				},
				{
					label: 'template.sp.sp00456.sjmbrynd',
					prop: 'actSolutionConcentration',
					width: 280,
					showWidth: 120,
					headerSelectKey: 'actSolutionConcentrationUnit',
					fillType: 'preFill',
					headerOptions: this.getDictOptions('business_nddw'),
					bodyDisabled: true,
					bodyType: 'inputNumber',
					bodySubType: 'inputNumber',
					bodySubKey: 'actSolutionConcentrationPrecision',
					bodyFillType: 'actFill',
					bodySubFillType: 'preFill',
					showBodySub: this.fillType === 'preFill',
					bodyPrecisionKey: 'actSolutionConcentrationPrecision',
					bodyMaxlength: 10,
					bodySubPlaceholder: 'template.common.xswsPlaceholder',
					compareTo: 'targetSolutionConcentration', //比较哪个字段
				},
				{
					label: 'template.sp.sp00456.ysmbrytj',
					prop: 'targetSolutionVolume',
					width: 280,
					showWidth: 120,
					headerSelectKey: 'targetSolutionVolumeUnit',
					fillType: 'preFill',
					headerOptions: this.getDictOptions('business_tjdw'),
					bodyType: 'inputNumber',
					bodyFillType: 'preFill',
					bodyMaxlength: 10,
					headerSelectTo: "actSolutionVolumeUnit",
				},
				{
					label: 'template.sp.sp00456.sjmbrytj',
					prop: 'actSolutionVolume',
					width: 280,
					showWidth: 120,
					headerSelectKey: 'actSolutionVolumeUnit',
					fillType: 'preFill',
					headerOptions: this.getDictOptions('business_tjdw'),
					bodyDisabled: true,
					bodyType: 'inputNumber',
					bodySubType: 'inputNumber',
					bodySubKey: 'actSolutionVolumePrecision',
					bodyFillType: 'actFill',
					bodySubFillType: 'preFill',
					showBodySub: this.fillType === 'preFill',
					bodyPrecisionKey: 'actSolutionVolumePrecision',
					bodyMaxlength: 10,
					bodySubPlaceholder: 'template.common.xswsPlaceholder',
					compareTo: 'targetSolutionVolume', //比较哪个字段
				},
				{
					label: 'template.sp.sp00456.mbryyxzq',
					prop: 'targetSolutionCycle',
					width: 280,
					showWidth: 160,
					fillType: 'preFill',
					bodyType: 'inputNumber',
					bodySubType: 'select',
					showBodySub: true,
					bodySubKey: 'targetSolutionCyclePrecision',
					bodySubOptions: this.getDictOptions('business_yxqdw'),
					bodyFillType: 'preFill',
					bodySubFillType: 'preFill',
					bodyMaxlength: 10
				},
				{
					label: 'template.sp.sp00456.mbrysxr',
					prop: 'targetSolutionExpirationDate',
					showWidth: 120,
					width: 180,
					bodyType: 'span'
				},
				{
					label: 'template.sp.sp00456.ysysrybh',
					prop: 'startSolutionCode',
					width: 280,
					showWidth: 120,
					bodyType: 'input',
					bodyFillType: 'preFill'
				},
				{
					label: 'template.sp.sp00456.sjysrybh',
					prop: 'actStartSolutionCode',
					width: 280,
					showWidth: 180,
					bodyType: 'sj',
					bodyFillType: 'actFill',
					compareTo: 'startSolutionCode', //比较哪个字段
				},
				{
					label: 'template.sp.sp00456.ysysrynd',
					prop: 'targetStartSolutionConcentration',
					width: 280,
					showWidth: 160,
					bodyType: 'inputNumber',
					bodyFillType: 'preFill',
					bodySubType: 'select',
					bodySubKey: 'targetStartSolutionConcentrationPrecision',
					bodySubOptions: this.getDictOptions('business_nddw'),
					bodySubFillType: 'preFill',
					bodyMaxlength: 10,
					showBodySub: true,
				},
				{
					label: 'template.sp.sp00456.sjysrynd',
					prop: 'targetAcSolution',
					width: 280,
					showWidth: 120,
					bodyType: 'inputNumber',
					bodyFillType: 'actFill',
					bodyDisabled: true,
					compareTo: 'targetStartSolutionConcentration', //比较哪个字段
				},
				{
					label: 'template.sp.sp00456.ysysrytj',
					prop: 'targetStartSolutionVolume',
					headerSelectKey: 'targetStartSolutionVolumeUnit',
					fillType: 'preFill',
					headerOptions: this.getDictOptions('business_tjdw'),
					width: 280,
					showWidth: 120,
					bodyType: 'inputNumber',
					bodyFillType: 'preFill',
					bodySubType: 'inputNumber',
					bodySubKey: 'targetStartSolutionVolumePrecision',
					bodySubFillType: 'preFill',
					bodyMaxlength: 10,
					bodyPrecisionKey: 'targetStartSolutionVolumePrecision',
					bodyMaxlength: 10,
					bodySubPlaceholder: 'template.common.xswsPlaceholder',
					bodyDisabled: true,
					showBodySub: true,
					showBodySub: this.fillType === 'preFill',
					headerSelectTo: "actStartSolutionVolumeUnit",
				},

				{
					label: 'template.sp.sp00456.sjysrytj',
					prop: 'actStartSolutionVolume',
					headerSelectKey: 'actStartSolutionVolumeUnit',
					fillType: 'preFill',
					headerOptions: this.getDictOptions('business_tjdw'),
					width: 280,
					showWidth: 120,
					bodyType: 'inputNumber',
					bodyFillType: 'actFill',
					bodyMaxlength: 10,
					compareTo: 'targetStartSolutionVolume', //比较哪个字段
					copyFrom: 'targetStartSolutionVolume' //复制哪个字段
				},

				{
					label: 'template.sp.sp00456.yjxsytj',
					prop: 'targetDiluentVolume',
					headerSelectKey: 'preDiluentVolumeUnit',
					fillType: 'preFill',
					headerOptions: this.getDictOptions('business_tjdw'),
					width: 280,
					showWidth: 120,
					bodyType: 'inputNumber',
					bodyFillType: 'preFill',
					bodySubType: 'inputNumber',
					bodySubKey: 'targetDiluentVolumePrecision',
					bodySubFillType: 'preFill',
					bodyMaxlength: 10,
					bodyPrecisionKey: 'targetDiluentVolumePrecision',
					bodySubPlaceholder: 'template.common.xswsPlaceholder',
					bodyDisabled: true,
					showBodySub: this.fillType === 'preFill',
					headerSelectTo: "actDiluentVolumeUnit",
				},
				{
					label: 'template.sp.sp00456.sjxsytj',
					prop: 'actDiluentVolume',
					headerSelectKey: 'actDiluentVolumeUnit',
					fillType: 'preFill',
					headerOptions: this.getDictOptions('business_tjdw'),
					width: 280,
					showWidth: 120,
					bodyType: 'inputNumber',
					bodyFillType: 'actFill',
					bodyMaxlength: 10,
					copyFrom: "targetDiluentVolume",
					compareTo: 'targetDiluentVolume' //比较哪个字段
				}
			];
		},
	},
	data() {
		return {
			subSolutionVisible: false,
			currentSubKey: "",//当前点击的子项key
			currentType: "",//当前点击的类型
			currentRowIndex: "",//当前点击的行索引
			dataSource: [],
			currentTableIndex: "",//当前点击的表格索引
			currentTableKey: "",//当前点击的表格key
			targetAcSolutionFromTable: true,//是否从表格中获取实际原始溶液浓度
			currentRowData: {},//当前点击的行数据
		};
	},
	mounted() {
		const formData = this.getFormDataByTemplateData();
		if (this.fillType === "actFill") {
			setTimeout(() => {
				this.handleUpdateCode(formData);
			}, 0);
		}
		if (this.fillType === "preFill") {
			if (!this.formData.paralleConfigs) {
				this.handleAddParalle()
			}
		}
	},
	methods: {
		//分装
		subPackageSubmit(data, configType, index) {
			const { fzsj, rowData, headerSelectFields } = data;
			const { fzList = [], dw = "", mybh } = fzsj;
			if (fzList && fzList.length > 0) {
				const list = fzList.map((item) => {
					return {
						bh: mybh + item.preCode + item.subCode,
						kc: item.num,
						kcdw: dw,
					}
				})
				let postData = {
					studyId: this.formData.studyId,
					studyFormId: this.formData.id,
					bh: mybh,
					nd: rowData.actSolutionConcentration || 0,
					nddw: headerSelectFields.actSolutionConcentrationUnit,
					studySubjectId: this.formData.studySubjectId,
					studyId: this.formData.studyId,
					studyFormId: this.formData.id,
					list: list
				}
				this.subPackageRequest(postData);
			}
		},
		startConfig(val) {
			const { rowData } = val;
			console.log(rowData, "rowData")
			let postData = {
				bh: rowData.targetSolutionCode + rowData.subTargetSolutionCode,
				studySubjectId: this.formData.studySubjectId,
				studyId: this.formData.studyId,
				studyFormId: this.formData.id,
			}
			this.startConfigRequest(postData);
		},
		configComplete(val) {
			const { rowData, headerSelectFields } = val;
			//计算实际目标溶液体积(实际起始溶液体积+实际稀释液体积)
			const { total, unit } = addTj([rowData.actStartSolutionVolume, rowData.actDiluentVolume], [headerSelectFields.actStartSolutionVolumeUnit, headerSelectFields.actDiluentVolumeUnit])
			debugger
			let postData = {
				mc: null,
				bh: rowData.targetSolutionCode + rowData.subTargetSolutionCode,
				nd: rowData.actSolutionConcentration,//实际目标溶液浓度
				nddw: headerSelectFields.actSolutionConcentrationUnit,
				studySubjectId: this.formData.studySubjectId,
				studyId: this.formData.studyId,
				studyFormId: this.formData.id,
				kc: total,
				kcdw: unit,
			}
			this.configCompleteRequest(postData);
		},
		//标签打印
		printTag(e, configType, index) {
			const { nickName, name } = this.$store.getters;
			const { printCode, row, type } = e;
			const currentForm = this.formData[configType][index];
			const { stepStorageCondition, startDate, expireDate, paralleStepStorageCondition } = currentForm;
			const targetSolutionExpirationDate = row.targetSolutionExpirationDate;
			const lang = this.$i18n.locale;
			const printConfig = {
				"品名": "暂时还不知道品名是哪个字段",
				"存储条件": stepStorageCondition || paralleStepStorageCondition,
				"配制日期": moment(startDate).format("YYYY-MM-DD"),
				"有效期至": moment(targetSolutionExpirationDate || expireDate).format("YYYY-MM-DD HH:mm"),
				"配置者": lang === "zh_CN" ? nickName : name,
				//type==="subPackage"从分装打印过来的，
				//type==="row" 从列表上点过来的
				"编号": type === "subPackage" ? printCode : (row.targetSolutionCode + row.subTargetSolutionCode),
			}
			console.log(printConfig, "printConfig")
			EventBus.$emit('showTagPrintDialog', { printConfig })
		},
		// 为指定的表单数据数组分配编号
		async assignNumbersToTableData(config) {
			return new Promise(async (resolve, reject) => {
				const configs = this.formData[config]
				const { startDate } = this.formData;
				// 检查paralleConfigs中的paralleTableFormData数组
				if (configs && configs.length > 0) {
					for (let i = 0; i < configs.length; i++) {
						const ref = `paralleStepTableRef_${i}`;
						const { stepTableFormData = [], effectivePeriod, effectivePeriodUnit, expireDate } = configs[i];
						if (!expireDate && config === "ladderConfigs") {
							const date = getExpireDate(startDate, effectivePeriod, effectivePeriodUnit);
							configs[i].expireDate = date;
						}
						if (stepTableFormData && stepTableFormData.length > 0) {
							const tableDataArray = stepTableFormData;
							// 检查表单数据中是否有任何一行的subTargetSolutionCode有值
							const hasAnyWithValue = tableDataArray.some(row =>
								row.subTargetSolutionCode && row.subTargetSolutionCode.trim() !== '');
							// 如果没有任何一行有值，则为所有行分配编号
							if (!hasAnyWithValue) {
								const codes = stepTableFormData.map((item) => ({ pre: item.targetSolutionCode, type: 1 }));
								const snList = await this.getLatestSnArr(codes);
								tableDataArray.forEach((row, idx) => {
									let expDate = {};
									if (config === "paralleConfigs" && !row.targetSolutionExpirationDate) {
										let date = getExpireDate(startDate, row.targetSolutionCycle, row.targetSolutionCyclePrecision);
										expDate = {
											targetSolutionExpirationDate: date
										}
									}
									this.$refs[ref][0]?.updateDataSourceByRowIndex(idx, { subTargetSolutionCode: snList[idx], ...expDate });
								});
								resolve()
							} else {
								reject()
							}

						}
					}
				}
			})

		},

		async handleUpdateCode() {
			Promise.all([this.assignNumbersToTableData("ladderConfigs"), this.assignNumbersToTableData("paralleConfigs")
			]).then(() => {
				//通知后端保存数据
				const params = {
					type: "fieldChanged",
					newRecord: null,
					resourceList: null,
				}
				EventBus.$emit('onModifyRecord', params,)
			})
		},
		//新增平行配制
		handleAddParalle() {
			// 初始化平行配制配置列表
			if (!this.formData.paralleConfigs) {
				this.$set(this.formData, 'paralleConfigs', []);
			}
			// 添加新的平行配制配置
			this.formData.paralleConfigs.push({
				paralleStepData: [],
				paralleTableFormData: [],
				showParalleConfig: true
			});
		},
		//新增阶梯配制
		handleAddLadder() {
			// 初始化阶梯配制配置列表
			if (!this.formData.ladderConfigs) {
				this.$set(this.formData, 'ladderConfigs', []);
			}

			// 添加新的阶梯配制配置
			this.formData.ladderConfigs.push({
				ladderStepData: [],
				ladderTableFormData: [],
				showLadderConfig: true
			});
		},
		// 删除阶梯配制配置
		deleteLadderConfig(index) {
			this.formData.ladderConfigs.splice(index, 1);
		},
		// 删除平行配制配置
		deleteParalleConfig(index) {
			this.formData.paralleConfigs.splice(index, 1);
		},
		// 添加表格行
		handleAddRow(type, rowIndex, configIndex = 0) {
			const tableRef = this.$refs[`paralleStepTableRef_${configIndex}`];
			if (tableRef && tableRef[0].addRow) {
				tableRef[0].addRow({});
			}
		},
		// 删除表格行
		deleteRow(rowIndex, type, configIndex = 0) {
			// 根据类型删除对应的表格行
			const tableRef = this.$refs[`paralleStepTableRef_${configIndex}`];
			if (tableRef) {
				tableRef[0].deleteRow(rowIndex);
			}
		},

		// 表格失去焦点事件
		onHandleTableBlur(type, configIndex, e) {
			const { colKey = "", item, rowIndex } = e;
			debugger
			if (colKey === "targetStartSolutionConcentration" || colKey === "targetSolutionVolume" || colKey === "targetSolutionConcentration" || colKey === "targetStartSolutionVolumePrecision" || colKey === "targetDiluentVolumePrecision") {
				if (type === "paralle") {
					const volumne = item.targetStartSolutionConcentration || 0;
					if (volumne) {
						this.updateTargetStartSolutionVolume(item, volumne);
					}
				}
			} else if (colKey === "actStartSolutionVolume" || colKey === "actDiluentVolume") {//实际起始溶液体积和实际目标溶液体积
				if (type === "paralle") {
					const targetAcSolution = item.targetAcSolution || 0;//获取实际起始溶液浓度
					if (targetAcSolution) {
						const volResult = this.updateSjmbrynd(item, targetAcSolution);
						if (!volResult) {
							return
						}
						this.$refs[`paralleStepTableRef_${configIndex}`][0]?.updateDataSourceByRowIndex(rowIndex, {
							actSolutionVolume: volResult.actVol,
							actSolutionConcentration: volResult.actNd,
						});
					}
				}

			}
		},
		onTableBeforeReagentSubmit(data) {
			const { selectData, callback, key, rowData } = data;
			if (key === "actStartSolutionCode" && !isCommonUnit(selectData.row.nddw, [rowData.targetStartSolutionConcentrationPrecision])) {//选择起始源溶液需要同步更新table的变更记录。
				callback.prevent('浓度单位与预制不符，请重新选择或申请废止并重新预制。');
			}
		},
		//平行配置 table选择试剂确定弹窗
		onTableRegentSubmit(type, configIndex, data) {
			const { selectInfo, rowIndex, key, rowData } = data;
			const { row, selectedId } = selectInfo;
			if (key === "actStartSolutionCode") {//实际原始溶液编号点击事件
				const tableRef = this.$refs[`paralleStepTableRef_${configIndex}`][0];
				if (tableRef) {
					const volResult = this.updateSjmbrynd(rowData, row.nd);
					//第一次选择溶液的时候，可能其他值没填入，就需要先把浓度和code一起更新
					tableRef.updateDataSourceByRowIndex(rowIndex, {
						actStartSolutionCode: selectedId,
						targetAcSolution: row.nd,
					})
					if (!volResult) {
						return
					}
					tableRef.updateDataSourceByRowIndex(rowIndex, {
						actSolutionVolume: volResult.actVol,
						actSolutionConcentration: volResult.actNd,
					})
				}
			}
		},
		//选择试剂提交事件
		onRegentSubmit(type, rowIndex, data) {
			const { selectInfo, key } = data;
			const { row } = selectInfo;
			if (key) {
				const packageRef = this.$refs[`paralleStepFormPackageRef_${rowIndex}`][0];
				if (key === "subStartSolution") {
					packageRef.updateFormData("targetAcSolution", row.nd);
					packageRef.onValueChangeCompareTo("targetAcSolution", row.nd, "targetStartSolution");
					this.updateTableNd(row, rowIndex);
				}
			}
		},
		updateRecord() {
			this.$nextTick(() => {
				EventBus.$emit('onModifyRecord', {
					type: "fieldChanged",
					newRecord: null,
					resourceList: null,
				},)
			})
		},
		//选择实际的时候更新table的浓度
		updateTableNd(row, rowIndex) {
			const { stepTableFormData = [] } = this.$refs[`ladderStepTableRef_${rowIndex}`][0].getFilledFormData();
			const newData = JSON.parse(JSON.stringify(stepTableFormData));
			// 遍历数据，按要求更新起始溶液编号
			newData.forEach((item, index) => {
				let initNd = row.nd;//起始浓度是上一条记录的实际目标溶液浓度
				if (index === 0) {
					item.startSolutionCode = row.bh;
				} else {
					item.startSolutionCode = newData[index - 1].targetSolutionCode + newData[index - 1].subTargetSolutionCode;
					initNd = newData[i - 1].actSolutionConcentration;
				}
				const volResult = this.updateSjmbrynd(item, initNd);
				if (!volResult) {
					return
				}

				item.actSolutionVolume = volResult.actVol;
				item.actSolutionConcentration = volResult.actNd;
				// 更新stepTableRef组件的数据
			})
			this.$refs[`ladderStepTableRef_${rowIndex}`][0].updateDataSource(newData);

		},
		//只做校验
		async validFields() {
			// 构建需要验证的引用数组
			let refsToValidate = ["baseInfoRef","storageConditionRef", "remarkRef"];

			// 添加平行配制相关的引用
			if (this.formData.paralleConfigs && this.formData.paralleConfigs.length > 0) {
				for (let i = 0; i < this.formData.paralleConfigs.length; i++) {
					refsToValidate.push(`paralleStepFormPackageRef_${i}`);
					refsToValidate.push(`paralleStepTableRef_${i}`);
					refsToValidate.push(`paralleStepRef_${i}`);
				}
			}
			return await this.validFormFields(refsToValidate);
		},
		getFilledFormData() {
			const baseData = this.$refs.baseInfoRef.getFilledFormData();
			const calcConditionData = this.$refs.calcConditionRef.getFilledFormData();
			// 获取所有平行配制数据
			const paralleConfigsData = [];
			if (this.formData.paralleConfigs && this.formData.paralleConfigs.length > 0) {
				for (let i = 0; i < this.formData.paralleConfigs.length; i++) {
					const paralleFormData = this.$refs[`paralleStepFormPackageRef_${i}`][0].getFilledFormData();
					const paralleTableFormData = this.$refs[`paralleStepTableRef_${i}`][0].getFilledFormData();
					const paralleStepData = this.$refs[`paralleStepRef_${i}`][0].getFilledFormData();

					paralleConfigsData.push({
						...paralleFormData,
						...paralleTableFormData,
						paralleStepData: paralleStepData.stepData,
						showParalleConfig: true
					});
				}
			}

			const remarkData = this.$refs.remarkRef.getFilledFormData();
			return {
				...baseData,
				...calcConditionData,
				paralleConfigs: paralleConfigsData,
				...remarkData
			}
		},
		async getFormData() {
			//先校验再获取值
			const validFlag = await this.validFields();
			if (!validFlag) {
				return false;
			}
			let content = this.getFilledFormData();
			if (content) {
				const { paralleConfigs = [] } = content;
				if (paralleConfigs.length > 0) {
					const paralleConUnitDiff = paralleConfigs.every(item => {
						const { stepTableFormData = [], headerSelectFields = {} } = item;
						const conUnits = stepTableFormData.map(item => item.targetStartSolutionConcentrationPrecision);
						const { actSolutionConcentrationUnit, targetSolutionConcentrationUnit } = headerSelectFields;
						return isCommonUnit(actSolutionConcentrationUnit, [...conUnits, targetSolutionConcentrationUnit]);
					});
					if (!paralleConUnitDiff) {
						this.$message.error("起始浓度单位与目标浓度单位不符，请重新选择！");
						return false;
					}
				}
			}
			return content;
		},
		getResource() {
			let content = this.getFilledFormData();
			//生成resource
			let tmpResource = []
			if (this.fillType === "actFill") {
				//平行配置
				if (content.paralleConfigs && content.paralleConfigs.length > 0) {
					for (let i = 0; i < content.paralleConfigs.length; i++) {
						let paralleConfigs = content.paralleConfigs[i]
						let stepTableFormData = paralleConfigs.stepTableFormData
						for (let j = 0; j < stepTableFormData.length; j++) {
							//分装
							let fzTotal = 0//分装总量
							let fzsj = stepTableFormData[j].fzsj
							if (fzsj && fzsj.fzList) {
								for (let k = 0; k < fzsj.fzList.length; k++) {
									let fzItem = fzsj.fzList[k]
									tmpResource.push({
										mc: null,
										bh: fzsj.mybh + fzItem.preCode + fzItem.subCode,
										ph: null,
										ndz: stepTableFormData[j].actSolutionConcentration + paralleConfigs.headerSelectFields.actSolutionConcentrationUnit,
										nd: stepTableFormData[j].actSolutionConcentration,
										nddw: paralleConfigs.headerSelectFields.actSolutionConcentrationUnit,
										ly: 'ELN配制',
										sxrq: paralleConfigs.expireDate,
										kc: fzItem.num,
										kcdw: fzsj.dw,
										type: null,
										elnType: this.product,
										syl: null,
										syldw: paralleConfigs.headerSelectFields.actSolutionVolumeUnit,
										yxzq: paralleConfigs.effectivePeriod,
										yxzqdw: paralleConfigs.effectivePeriodUnit,
									})
									fzTotal = addDecimals(fzTotal, fzItem.num)
								}
							}
							//生成
							const { total, unit } = addTj([stepTableFormData[j].actSolutionVolume, stepTableFormData[j].actDiluentVolume], [paralleConfigs.headerSelectFields.actSolutionVolumeUnit, paralleConfigs.headerSelectFields.actDiluentVolumeUnit])
							tmpResource.push({
								mc: null,
								bh: stepTableFormData[j].targetSolutionCode + stepTableFormData[j].subTargetSolutionCode,
								ph: null,
								nd: stepTableFormData[j].actSolutionConcentration,
								ndz: stepTableFormData[j].actSolutionConcentration + paralleConfigs.headerSelectFields.actSolutionConcentrationUnit,
								nddw: paralleConfigs.headerSelectFields.actSolutionConcentrationUnit,
								ly: 'ELN配制',
								sxrq: stepTableFormData[j].targetSolutionExpirationDate,
								kc: total,
								kcdw: unit,
								type: null,
								elnType: this.product,
								syl: fzTotal > 0 ? fzTotal : null,
								syldw: fzTotal > 0 ? fzsj.dw : unit,
								yxzq: stepTableFormData[j].targetSolutionCycle,
								yxzqdw: stepTableFormData[j].targetSolutionCyclePrecision,
							})
							//稀释液 
							tmpResource.push({
								mc: null,
								bh: paralleConfigs.subSolution,
								ph: null,
								nd: null,
								nddw: null,
								ndz: null,
								ly: null,
								sxrq: null,
								kc: null,
								kcdw: null,
								type: 1,
								syl: stepTableFormData[j].actDiluentVolume,
								syldw: paralleConfigs.headerSelectFields.actDiluentVolumeUnit,
								yxzq: null,
								yxzqdw: null,
							})
						}
					}
				}
			}
			if (tmpResource.length > 0) {
				tmpResource = uniqeResourceOne(tmpResource)
			}
			//使用的试剂、仪器
			const stepResource = this.getStepResource()
			this.resourceTmp = uniqeResource(tmpResource, stepResource.sjResource || [])
			this.yqResourceTmp = stepResource.yqResource || []
			return this.resourceTmp;
		},
		getStepResource() {
			const sjResource = [], yqResource = [];
			if (this.formData.paralleConfigs && this.formData.paralleConfigs.length > 0) {
				for (let i = 0; i < this.formData.paralleConfigs.length; i++) {
					const paralleResource = this.$refs[`paralleStepRef_${i}`][0].getStepResource();
					sjResource.push(...paralleResource.sjResource);
					yqResource.push(...paralleResource.yqResource);
				}
			}
			//去重
			const { sj, yq } = duplicateResource(sjResource, yqResource)
			return { sjResource: sj, yqResource: yq };
		},
		async onSave() {
			const formData = this.getStepResource();
			console.log(formData, "formData")
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss">
.mt-20 {
	margin-top: 20px;
}

.config-section {
	margin-bottom: 20px;
	padding: 15px;
	border: 1px solid #ebeef5;
	border-radius: 4px;
	background-color: #fafafa;
}

.config-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 15px;
	font-weight: bold;
	font-size: 16px;
	color: #303133;
}

.config-header .el-button {
	color: #f56c6c;
	font-size: 14px;
}

.config-header .el-button:hover {
	color: #f78989;
}

.mt-0 {
	margin-top: 0;
}

.config-header-right {
	margin-bottom: 15px;
	font-weight: bold;
	font-size: 16px;
	color: #303133;
	text-align: right;
	width: 100%;
}

.s-container {
	box-shadow: none !important;
	padding: 24px 0 !important;
}
</style>