<!-- 生物样品分析方法学样品制备表-准确度与精密度 -->
<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" />
					<BaseInfoFormPackage fieldItemLabel="template.common.storageCondition" label="template.common.storageCondition" ref="storageConditionRef"
						:formConfig="storageFormConfig" :formData="formData" />
					<LineLabel label="template.common.operationSteps" />
					<div class="template-form-item">
						<BaseInfoFormPackage v-if="sn!='SP013'" fieldItemLabel="template.common.operationSteps" ref="stepFormPackageRef" :formConfig="stepFormConfig"
							:formData="formData" />

						<CustomTable
							@blur="onHandleTableBlur"
							:ref="`tableRef`"
							:columns="tableStepColumns"
							:formData="formData"
							:prefixKey = "`table`"
							fieldItemLabel = "template.common.operationSteps"
							:showOperation="fillType === 'preFill'"
						>
							<template slot="operation" slot-scope="{ row, rowIndex, columns }">
								<TableOpertaion
									:fillType="fillType"
									:row="row"
									:rowIndex="rowIndex"
									:columns="columns"
									@deleteRow="(rowIndex) => deleteRow(rowIndex)"
									@subPackageSubmit="subPackageSubmit"
									@startConfig="startConfig"
									@configComplete="configComplete"
								></TableOpertaion>
							</template>
						</CustomTable>
					</div>
					<Step ref="stepRef" :formData="formData.stepData"></Step>
					<BaseInfoFormPackage fieldItemLabel="template.common.remark" label="template.common.remark" ref="remarkRef" :formConfig="remarkConig"
						:formData="formData" />

				</div>
			</div>
		</div>
		<!-- <button @click = "onSave">保存</button> -->
	</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";
import CustomTable from '@/components/Template/CustomTable.vue';
import { getLatestSnArr } from '@/api/template';
import {getSWYPFXFFXYPZBBTableConfig} from "../../formConfig/SWYPFXFFXYPZBBTableConfig.js";
import TableOpertaion from "@/components/Template/operation/TableOpertaion.vue"
import { EventBus } from "@/utils/eventBus";
import { addTj,uniqeResource,uniqeResourceOne,addDecimals } from "@/utils/calUnitTools";

export default {
	name: "ZQDYJMD",
	components: { BaseInfoFormPackage, LineLabel, TableList, Step, CustomTable,TableOpertaion },
	mixins: [templateMixin],
	props: {
		fillType: {
			type: String,
			default: 'preFill',
		},
		sn: {
			type: String,
			default: '',
		},
	},
	computed: {
		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,
						},
						methodCode: {
							label: 'template.common.methodCode',
							type: "input",
							fillType: "preFill",
							maxlength: 50
						},
						versionNum: {
							label: 'template.common.versionNumber',
							type: "inputNumber",
							fillType: "actFill",
							prepend: "V",
							maxlength: 50
						},
						//处理批编号
						clpbg: {
							label: 'template.sp.sp008.clpbh',
							type: "input",
							fillType: "actFill",
							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",
							compareTo: "pre",
							multiple: true,
							options: this.getDictOptions('business_pztj')
						}
					}
				},
				{
					type: "cellItem",
					label: 'template.sp.sp008.rqcz',
					config: {
						rqcz: {
							type: "select",
							multiple: true,
							fillType: "actFill",
							options: this.getDictOptions('business_rqcz'),
							otherCode: "rqczOther",
						},
					}
				},
				{
					type: "cellItem",
					label: 'template.sp.sp008.clsj',
					config: {
						startDate: {
							label: 'template.common.startTime',
							type: "input",
						},
						endDate: {
							label: 'template.common.endTime',
							type: "input",
						},
					}
				}
			]
		},
		stepFormConfig() {
			return [
				{
					type: "step",
					config: {
						jz: {
							label: 
								this.sn=='SP008'?'template.sp.sp008.xzjz':
								this.sn=='SP010'?'template.sp.sp008.xzjz':
								this.sn=='SP011'?'template.sp.sp011.xzxsy':
								this.sn=='SP012'?'template.sp.sp011.xzxsy':
								this.sn=='SP013'?'template.sp.sp011.xzxsy':
								this.sn=='SP014'?'template.sp.sp011.xzxsy':
								this.sn=='SP015'?'template.sp.sp008.xzjz':
								this.sn=='SP016'?'template.sp.sp008.xzjz':
								this.sn=='SP017'?'template.sp.sp008.xzjz':
								this.sn=='SP018'?'template.sp.sp018.xzxsy':''
							,
							type: "input",
							fillType: "preFill",
							subType: "sj",
							subKey: "subJz",
							subFillType: "actFill",
							maxlength: 20,
							labelWidth: 80,
						},
					}
				}
			]
		},
		tableStepColumns() {
			return	this.sn=='SP008'?getSWYPFXFFXYPZBBTableConfig(this,'business_sp_jmdyzqdyp'):
					this.sn=='SP010'?getSWYPFXFFXYPZBBTableConfig(this,'business_sp_qxwdx'):
					this.sn=='SP011'?getSWYPFXFFXYPZBBTableConfig(this,'business_sp_cbyhgzywdx',true):
					this.sn=='SP012'?getSWYPFXFFXYPZBBTableConfig(this,'business_sp_rxjzxy',true):
					this.sn=='SP013'?getSWYPFXFFXYPZBBTableConfig(this,'business_sp_jzxy',false,true):
					this.sn=='SP014'?getSWYPFXFFXYPZBBTableConfig(this,'business_sp_xzxytyx',true):
					this.sn=='SP015'?getSWYPFXFFXYPZBBTableConfig(this,'business_sp_zdybs'):
					this.sn=='SP016'?getSWYPFXFFXYPZBBTableConfig(this,'business_sp_xskkx'):
					this.sn=='SP017'?getSWYPFXFFXYPZBBTableConfig(this,'business_sp_cbydb'):
					this.sn=='SP018'?getSWYPFXFFXYPZBBTableConfig(this,'',true):
					'';
		},
	},
	data() {
		return {
			reagentType: "",//本表单特殊字段：选择试剂的类型1选择基质，2表格里面选择试剂

			currentSubKey: "",//当前点击的子项key
			rowIndex:0,//当前表格点击的行数

			formData: {}
		};
	},
	mounted() {
		const formData = this.getFormDataByTemplateData();
		if(this.fillType === "actFill"){
			this.getCode(formData);
		}
	},

	methods: {
		//获取目标溶液编号
		async getCode(v){
			const {stepTableFormData = []} = v;
			if(stepTableFormData && stepTableFormData.length>0 && !stepTableFormData[0].bhCode){
				let postSn = []
				for(let i=0;i<stepTableFormData.length;i++){
					postSn.push({
						pre:stepTableFormData[i].bh,
						type:1
					})
				}
				const result = await getLatestSnArr(postSn)
				if(result.code == 200){
					for(let i=0;i<stepTableFormData.length;i++){
						this.$refs.tableRef.updateDataSourceByRowIndex(i,{
							bhCode: result.data[i],
						})
					}

					const params = {
						type: "fieldChanged",
						newRecord: null,
						resourceList: null,
					}
					setTimeout(() => {
						EventBus.$emit('onModifyRecord', params,)
					}, 10);
				}
			}
		},
		//获取已填写的表单数据
		getFilledFormData(){
			return this.sn=='SP013'? 
			this.getFilledFormDataByRefs(["baseInfoRef", "storageConditionRef", "tableRef","stepRef", "remarkRef"])
			:
			this.getFilledFormDataByRefs(["baseInfoRef", "storageConditionRef", "stepFormPackageRef", "tableRef","stepRef", "remarkRef"])
		},
		async getFormData() {
			let content = this.sn=='SP013'? 
			await this.validFormFields(["baseInfoRef", "storageConditionRef","tableRef" ,"stepRef", "remarkRef"])
			:
			await this.validFormFields(["baseInfoRef", "storageConditionRef", "stepFormPackageRef","tableRef" ,"stepRef", "remarkRef"])
			return content;
		},
		getResource() {
			let content = this.getFilledFormData();
			//生成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: item.sjry,
							ph: null,
							ndz: null,
							nd: null,
							nddw: null,
							ly: 'ELN配制',
							sxrq: null,
							kc: null,
							kcdw: null,
							syl: item.sjryxql,
							type: 1,
							elnType: this.product,
							syldw:content.headerSelectFields.sjryxqlUnit,
							yxzq:null,
							yxzqdw:null,
						})
						tmpResource.push({
							mc: null,
							bh: this.sn=='SP013'?item.kbjzbh:content.subJz,
							ph: null,
							ndz: null,
							nd: null,
							nddw: null,
							ly: 'ELN配制',
							sxrq: null,
							kc: null,
							kcdw: null,
							syl: item.sjjzxql,
							type: 1,
							elnType: this.product,
							syldw:content.headerSelectFields.sjjzxqlUnit,
							yxzq:null,
							yxzqdw:null,
						})
						//分装的
						let fzTotal = 0//分装总量
						if(item.fzsj && item.fzsj.fzList && item.fzsj.fzList.length>0){
							for(let j=0;j<item.fzsj.fzList.length;j++){
								let fzItem = item.fzsj.fzList[j]
								tmpResource.push({
									mc: null,
									bh: item.fzsj.mybh+fzItem.preCode+ fzItem.subCode,
									ph: null,
									ndz: item.hhwznd + content.headerSelectFields.hhwzndUnit,
									nd: item.hhwznd,
									nddw: content.headerSelectFields.hhwzndUnit,
									ly: 'ELN配制',
									sxrq: null,
									kc: fzItem.num,
									kcdw: item.fzsj.dw,
									syl: null,
									type: null,
									elnType: this.product,
									syldw:item.fzsj.dw,
									yxzq:null,
									yxzqdw:null,
								})
								fzTotal=addDecimals(fzTotal,fzItem.num)
							}
						}
						//生成的
						const { total, unit } = addTj([item.sjjzxql, item.sjryxql], [content.headerSelectFields.sjjzxqlUnit, content.headerSelectFields.sjryxqlUnit])

						tmpResource.push({
							mc: null,
							bh: item.bh+item.bhCode,
							ph: null,
							ndz: item.hhwznd + content.headerSelectFields.hhwzndUnit,
							nd: item.hhwznd,
							nddw: content.headerSelectFields.hhwzndUnit,
							ly: 'ELN配制',
							sxrq: null,
							kc: total,
							kcdw: unit,
							syl: fzTotal>0?fzTotal:null,
							type: null,
							elnType: this.product,
							syldw:fzTotal>0?item.fzsj.dw:unit,
							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() {
			const formData = await this.getFilledFormData();

			console.log(formData, "formData")
		},
		// 删除表格行
		deleteRow(rowIndex) {
			const tableRef = this.$refs['tableRef'];
			if (tableRef) {
				tableRef.deleteRow(rowIndex);
			}
		},
		subPackageSubmit(val){
			console.log("分装数据："+JSON.stringify(val))
			if(val.fzsj.fzList && val.fzsj.fzList.length>0){
				let list = []
				for(let i=0;i<val.fzsj.fzList.length;i++){
					let item = val.fzsj.fzList[i]
					list.push({
						bh:val.fzsj.mybh+item.preCode+ item.subCode,
						kc:item.num,
						kcdw:val.fzsj.dw,
					})
				}
				let postData = {
					studyId:this.formData.studyId,
					studyFormId:this.formData.id,
					studySubjectId: this.formData.studySubjectId,
					bh:val.fzsj.mybh,
					nd:val.rowData.hhwznd,
					nddw:val.headerSelectFields.hhwzndUnit,
					list:list
				}
				console.log("分装提交数据："+JSON.stringify(postData))
				this.subPackageRequest(postData)
			}
		},
		startConfig(val){
			console.log("开始配置数据："+JSON.stringify(val))
			let postData = {
				bh:val.rowData.bh+val.rowData.bhCode,
				studyId:this.formData.studyId,
				studyFormId:this.formData.id,
				studySubjectId: this.formData.studySubjectId,
			}
			console.log("开始配置提交数据："+JSON.stringify(postData))
			this.startConfigRequest(postData);
		},
		configComplete(val){
			if(val.rowData.sjjzxql==='' || val.rowData.sjjzxql===undefined || val.rowData.sjryxql==='' || val.rowData.sjryxql===undefined){
				this.$message.error("表格内容未填完")
          		return
			}
			console.log("完成配置数据："+JSON.stringify(val))
			const { total, unit } = addTj([val.rowData.sjjzxql, val.rowData.sjryxql], [val.headerSelectFields.sjjzxqlUnit, val.headerSelectFields.sjryxqlUnit])
			let postData = {
				mc:null,
				studyId:this.formData.studyId,
				studyFormId:this.formData.id,
				studySubjectId: this.formData.studySubjectId,
				bh:val.rowData.bh+val.rowData.bhCode,
				nd:val.rowData.hhwznd,
				nddw:val.headerSelectFields.hhwzndUnit,
				kc: total,
				kcdw: unit,
			}
			this.configCompleteRequest(postData);
		},


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