<!-- 生物样品内标工作液制备表 -->
<template>
	<div>
		<div class="detail-container">
			<div class="detail-title"><img src="@/assets/images/detail-title.png">{{ formData.templateMc ||
				"生物样品内标工作液制备表" }}<img src="@/assets/images/detail-title.png" /></div>
			<div class="detail-content">
				<div class="content">
					<BaseInfoFormPcakge label="试验基本信息" ref="baseInfoRef" :formConfig="baseInfoFormConfig"
						:formData="formData" />
					<TableList label="试验试剂信息" :columns="sysjColumns" :dataSource="resource" />
					<TableList label="仪器使用信息" :columns="yqsColumns" :dataSource="resource" />
					<BaseInfoFormPcakge label="存储条件" ref="storageConditionRef" :formConfig="storageFormConfig"
						:formData="formData" />
					<LineLabel label="操作步骤" />
					<div v-if="fillType === 'preFill'" class="mt-20">
						<el-button type="primary" @click="handleAddParalle">新增平行配制</el-button>
						<el-button type="primary" @click="handleAddLadder">新增阶梯配制</el-button>
					</div>

					<!-- 阶梯配制区域 -->
					<div v-for="(ladderConfig, ladderIndex) in formData.ladderConfigs" :key="'ladder_' + ladderIndex">

						<div class="template-form-item">
							<div class="config-header">
								<div>阶梯配制</div>
								<el-button v-if="fillType === 'preFill'" type="text" icon="el-icon-delete"
									@click="deleteLadderConfig(ladderIndex)">删除</el-button>
							</div>
							<BaseInfoFormPcakge @clickable="(e) => handleClickable('ladder', ladderIndex, e)"
								:ref="`ladderStepFormPackageRef_${ladderIndex}`" :formConfig="ladderStepFormConfig"
								@blur="onHandleBlur" :formData="ladderConfig" fieldItemLabel="阶梯配制"
								:prefixKey="'ladder_' + ladderIndex" />
							<CustomTable @blur="(e)=>onHandleTableBlur('ladder', ladderIndex,e)" :ref="`ladderStepTableRef_${ladderIndex}`"
								:columns="ladderStepColumns" :formData="ladderConfig" :prefixKey="'ladder_' + ladderIndex"
								fieldItemLabel="阶梯配制">
								<template slot="operation" slot-scope="{ row, rowIndex}">
									<TableOpertaion :fillType="fillType" :row="row" :rowIndex="rowIndex"
										@deleteRow="(rowIndex) => deleteRow(rowIndex, 'ladder', ladderIndex)">
									</TableOpertaion>
								</template>
							</CustomTable>

							<Step class="mt-0 s-container" :ref="`ladderStepRef_${ladderIndex}`"
								:formData="ladderConfig.ladderStepData" fieldItemLabel="阶梯配制"
								:prefixKey="'ladder_' + ladderIndex"></Step>
						</div>
					</div>

					<!-- 平行配制区域 -->
					<div label="平行配制" v-for="(paralleConfig, paralleIndex) in formData.paralleConfigs"
						:key="'paralle_' + paralleIndex">

						<div class="template-form-item">
							<div class="config-header">
								<div>平行配制</div>
								<el-button v-if="fillType === 'preFill'" type="text" icon="el-icon-delete"
									@click="deleteParalleConfig(paralleIndex)">删除</el-button>
							</div>
							<BaseInfoFormPcakge @clickable="(e) => handleClickable('paralle', paralleIndex, e)"
								:ref="`paralleStepFormPackageRef_${paralleIndex}`" :formConfig="paralleStepFormConfig"
								@blur="onHandleBlur" :formData="paralleConfig" :prefixKey="'paralle' + paralleIndex"
								fieldItemLabel="平行配制" />
							<CustomTable @blur="(e)=>onHandleTableBlur('paralle', paralleIndex,e)" :ref="`paralleStepTableRef_${paralleIndex}`"
								:columns="paralleStepColumns" :formData="paralleConfig"
								@clickable="(col,rowIndex) => handleTableClickable('paralle', paralleIndex, col,rowIndex)"
								:prefixKey="'paralle' + paralleIndex" fieldItemLabel="平行配制">
								<template slot="operation" slot-scope="{ row, rowIndex}">
									<TableOpertaion :fillType="fillType" :row="row" :rowIndex="rowIndex"
										@deleteRow="(rowIndex) => deleteRow(rowIndex, 'paralle', paralleIndex)">
									</TableOpertaion>
								</template>
							</CustomTable>

							<Step class="mt-0 s-container" :ref="`paralleStepRef_${paralleIndex}`"
								:formData="paralleConfig.paralleStepData" fieldItemLabel="平行配制"
								:prefixKey="'paralle' + paralleIndex"></Step>
						</div>
					</div>
					<BaseInfoFormPcakge label="备注" ref="remarkRef" :formConfig="remarkConig" :formData="formData" />

				</div>
			</div>
			<button @click="onSave">保存</button>
		</div>
		<SelectReagentDialog @submit="onSelectReagentSubmit"
			ref="selectReagentDialogRef">
		</SelectReagentDialog>
	</div>
</template>

<script>
import { EventBus } from "@/utils/eventBus";
import BaseInfoFormPcakge from "@/components/Template/BaseInfoFormPcakge";
import LineLabel from "@/components/Template/LineLabel";
import TableList from "@/components/Template/Table";
import Step from "@/components/Template/Step";
import templateMixin from "../../mixins/templateMixin";
import CustomTable from '@/components/Template/CustomTable.vue';
import SelectReagentDialog from '../../dialog/SelectReagentDialog.vue';
import TableOpertaion from "@/components/Template/operation/TableOpertaion.vue"
import { getLadderColumnsConfig, getParallelColumnsConfig, getLadderFormConfig, getBaseInfoFormConfig, getRemarkFormConfig, getStorageConditionFormConfig, getParalleStepFormConfig } from "../../formConfig/paralleAndLadderConfig.js";
export default {
	name: "SWYPBQGZYZBB",
	components: { BaseInfoFormPcakge, LineLabel, TableList, Step, CustomTable, SelectReagentDialog, TableOpertaion },
	mixins: [templateMixin],
	props: {
		fillType: {
			type: String,
			default: 'preFill',
		},
	},
	watch: {
		fillType: {
			immediate: true,
			handler(v) {
				console.log(v, "fillType")
			}
		},
		formData: {
			immediate: true,
			handler(v) {
				if(v &&this.fillType === "actFill"){
					this.handleUpdateCode();
				}
			}
		}
	},
	computed: {
		// 存储条件表单配置
		storageFormConfig() {
			return getStorageConditionFormConfig(this);
		},
		// 备注表单配置
		remarkConig() {
			return getRemarkFormConfig();
		},
		// 试验基本信息表单配置
		baseInfoFormConfig() {
			return getBaseInfoFormConfig(this);
		},
		paralleStepFormConfig() {
			return getParalleStepFormConfig(this);
		},
		// 操作步骤表单配置
		ladderStepFormConfig() {
			return getLadderFormConfig(this);
		},
		paralleStepColumns() {
			return getParallelColumnsConfig(this);
		},
		// 阶梯配置表格列配置
		ladderStepColumns() {
			return getLadderColumnsConfig(this);
		},
	},
	data() {
		return {
			subSolutionVisible: false,
			currentSubKey: "",//当前点击的子项key
			currentType: "",//当前点击的类型
			currentRowIndex: "",//当前点击的行索引
			dataSource: [],
			currentTableIndex: "",//当前点击的表格索引
			currentTableKey: "",//当前点击的表格key
			targetAcSolutionFromTable:true,//是否从表格中获取实际原始溶液浓度
		};
	},
	mounted() {
	},
	methods: {
		// 为指定的表单数据数组分配编号
		async assignNumbersToTableData(config) {
			const configs = this.formData[config]

			// 检查paralleConfigs中的paralleTableFormData数组
			if (configs && configs.length > 0) {
				for (let i = 0; i < configs.length; i++) {
					const ref = config === "paralleConfigs" ? `paralleStepTableRef_${i}` : `ladderStepTableRef_${i}`;
					const {stepTableFormData = []} = configs[i];
					if (stepTableFormData && stepTableFormData.length > 0) {
							const tableDataArray = stepTableFormData;
							// 检查表单数据中是否有任何一行的subTargetSolutionCode有值
							const hasAnyWithValue = tableDataArray.some(row => 
								row.subTargetSolutionCode && row.subTargetSolutionCode.trim() !== '');
							// 如果没有任何一行有值，则为所有行分配编号
							if (!hasAnyWithValue) {
								const length = tableDataArray.length;
								const snList = await this.getLatestSn(length);
								tableDataArray.forEach((row, idx) => {
									this.$refs[ref][0]?.updateDataSourceByRowIndex(idx,{subTargetSolutionCode: length==1?snList:snList[idx]});
								});
							}
					}
				}
			}
		
		},

		async handleUpdateCode() {
			this.assignNumbersToTableData("paralleConfigs");
			this.assignNumbersToTableData("ladderConfigs");
			this.$nextTick(() => {
				//通知后端保存数据
				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 = type === 'ladder' ?
				this.$refs[`ladderStepTableRef_${configIndex}`] :
				this.$refs[`paralleStepTableRef_${configIndex}`];
			if (tableRef && tableRef[0].addRow) {
				tableRef[0].addRow({});
			}
		},
		// 删除表格行
		deleteRow(rowIndex, type, configIndex = 0) {
			// 根据类型删除对应的表格行
			if (type === 'ladder') {
				const tableRef = this.$refs[`ladderStepTableRef_${configIndex}`];
				if (tableRef) {
					tableRef.deleteRow(rowIndex);
				}
			} else if (type === 'paralle') {
				const tableRef = this.$refs[`paralleStepTableRef_${configIndex}`];
				if (tableRef) {
					tableRef.deleteRow(rowIndex);
				}
			}
		},

		// 表格失去焦点事件
		onHandleTableBlur(type, configIndex, e) {
			const { colKey = "",item } = e;
			if (colKey === "targetStartSolutionConcentration" || colKey === "targetSolutionVolume" || colKey === "targetSolutionConcentration" || colKey === "targetStartSolutionVolumePrecision" || colKey === "targetDiluentVolumePrecision") {
				if(type === "ladder"){
					const volume = this.$refs[`ladderStepFormPackageRef_${configIndex}`][0]?.getFormDataByKey("targetStartSolution") || 0;
					if (volume) {
						this.updateTargetStartSolutionVolume(item, volume);
					}
				}else if(type === "paralle"){
					const volumne = item.targetStartSolutionConcentration || 0;
					if (volumne) {
						this.updateTargetStartSolutionVolume(item, volumne);
					}
				}
			}else if(colKey === "actStartSolutionVolume" || colKey === "actDiluentVolume"){//实际起始溶液体积和实际目标溶液体积
				if(type === "ladder"){
					const targetAcSolution = this.$refs[`ladderStepFormPackageRef_${configIndex}`][0]?.getFormDataByKey("targetAcSolution") || 0;//获取实际起始溶液浓度
					if(targetAcSolution){
					this.updateSjmbrynd(item,targetAcSolution);
					}
				}else if(type === "paralle"){
					const targetAcSolution = item.targetAcSolution || 0;//获取实际起始溶液浓度
					if(targetAcSolution){
						this.updateSjmbrynd(item,targetAcSolution);
					}
				}
				
			}
		},
		//表格点击事件
		handleTableClickable(type, rowIndex, col,tableRowIndex) {
			if(col.prop === "actStartSolutionCode"){//实际原始溶液编号点击事件
				this.currentTableKey = col.prop;
				this.currentType = type;
				this.currentRowIndex = rowIndex;
				this.currentTableIndex = tableRowIndex;
				this.$refs.selectReagentDialogRef.show();
			}
		},
		//form表单点击事件
		handleClickable(type, rowIndex, item) {
			if (this.fillType === "preFill") {
				return;
			}
			console.log(type, rowIndex, item, "handle")
			const { subKey = "" } = item;
			if (subKey === "subStartSolution" || subKey === "subSolution") {//起始源溶液点击事件
				this.$refs.selectReagentDialogRef.show()
				this.currentSubKey = subKey;
				this.currentType = type;
				this.currentRowIndex = rowIndex;
			}
		},
		//选择试剂提交事件
		onSelectReagentSubmit(code,row) {
			const { currentSubKey,currentTableKey,currentRowIndex,currentTableIndex } = this;
			if(currentSubKey){
				const ref = this.currentType === "ladder" ?"ladderStepFormPackageRef_":"paralleStepFormPackageRef_"
				const packageRef = this.$refs[`${ref}${this.currentRowIndex}`][0];
				if(currentSubKey === "subStartSolution"){
					packageRef.updateFormData("targetAcSolution", row.nd);
				}
				packageRef.updateFormData(currentSubKey, code);
				this.currentSubKey = "";
			}else if (currentTableKey === "actStartSolutionCode"){//实际原始溶液编号点击事件
				const tableRef = this.$refs[`paralleStepTableRef_${currentRowIndex}`][0];
				if(tableRef){
					tableRef.updateDataSourceByRowIndex(currentTableIndex,{
						actStartSolutionCode: code,
						targetAcSolution: row.nd,
					})
				}	
			}
			this.$refs.selectReagentDialogRef.onCancel()
		},
		//只做校验
		async validFields() {
			// 构建需要验证的引用数组
			let refsToValidate = ["baseInfoRef", "storageConditionRef", "remarkRef"];

			// 添加阶梯配制相关的引用
			if (this.formData.ladderConfigs && this.formData.ladderConfigs.length > 0) {
				for (let i = 0; i < this.formData.ladderConfigs.length; i++) {
					refsToValidate.push(`ladderStepFormPackageRef_${i}`);
					refsToValidate.push(`ladderStepTableRef_${i}`);
					refsToValidate.push(`ladderStepRef_${i}`);
				}
			}

			// 添加平行配制相关的引用
			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}`);
				}
			}
			console.log(refsToValidate,"refsToValidate")
			return await this.validFormFields(refsToValidate);
		},
		getFilledFormData() {
			const baseData = this.$refs.baseInfoRef.getFilledFormData();
			const conditionData = this.$refs.storageConditionRef.getFilledFormData();

			// 获取所有阶梯配制数据
			const ladderConfigsData = [];
			if (this.formData.ladderConfigs && this.formData.ladderConfigs.length > 0) {
				for (let i = 0; i < this.formData.ladderConfigs.length; i++) {
					const ladderFormData = this.$refs[`ladderStepFormPackageRef_${i}`][0].getFilledFormData();
					const ladderTableFormData = this.$refs[`ladderStepTableRef_${i}`][0].getFilledFormData();
					const ladderStepData = this.$refs[`ladderStepRef_${i}`][0].getFilledFormData();

					ladderConfigsData.push({
						...ladderFormData,
						...ladderTableFormData,
						ladderStepData: ladderStepData.stepData,
						showLadderConfig: true
					});
				}
			}

			// 获取所有平行配制数据
			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,
				...conditionData,
				ladderConfigs: ladderConfigsData,
				paralleConfigs: paralleConfigsData,
				...remarkData
			}
		},
		async getFormData() {
			//先校验再获取值
			const validFlag = await this.validFields();
			if (!validFlag) {
				return false;
			}
			return this.getFilledFormData();
		},
		async onSave() {
			const formData = await this.getFormData();
			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;
}
.s-container{
	box-shadow: none !important;
	padding:24px 0 !important;
}
</style>