<script setup>
	import { getOrgIdList, getStoreHouseList, getWarehouseList } from '@/api/grainReserves/gopsPlan'

	import { add, update, getDetails } from '@/api/grainQualityManagement/qualityDataInput'

	import commonSelect from '@/components/CommonSelector/index.vue'
	import commonCascader from '@/components/CommonSelector/cascader.vue'
	import aqTable from './qTable.vue'
	import { message } from 'ant-design-vue'
	import { just_required, number_required, required_array } from '@/utils/rules'
	import { deleteField, genKey } from '@/utils/systemUtils'

	const props = defineProps({
		visible: {
			type: Boolean,
			required: false,
			default: false
		},
		editData: {
			type: Object,
			required: false,
			default: null
		},
		action: {
			type: String,
			required: false,
			default: null
		}
	})

	const isView = computed(() => props.action === 'view')
	const isAdd = computed(() => props.action === 'add')
	const isEdit = computed(() => props.action === 'edit')
	const isApprove = computed(() => props.action === 'approve')
	const readonly = computed(() => {
		return isView.value || isApprove.value
	})

	const orgOptions = ref([])
	const houseOptions = ref([])
	const wareOptions = ref([])

	const show = ref(props.visible)
	const formData = ref({})
	const tableList_7602 = ref([])
	const tableList_7603 = ref([])
	const tableList_7604 = ref([])
	const tableMap = {
		tableList_7602,
		tableList_7603,
		tableList_7604
	}
	const t_7602 = ref()
	const t_7603 = ref()
	const t_7604 = ref()
	const formRef = ref()
	const refMap = {
		t_7602,
		t_7603,
		t_7604
	}

	const emit = defineEmits(['update:visible', 'on-approve', 'on-save'])

	const submitLoading = ref(false)

	const getOrgOptions = () => {
		orgOptions.value = []
		getOrgIdList().then((list) => {
			orgOptions.value = (list || []).map((d) => {
				return {
					label: d.orgName,
					value: d.orgId,
					raw: d
				}
			})
		})
	}

	const getHouseOptions = (orgId) => {
		houseOptions.value = []
		getStoreHouseList(orgId).then((list) => {
			houseOptions.value = (list || []).map((d) => {
				return {
					label: d.storehouseName,
					value: d.storehouseId,
					raw: d
				}
			})
		})
	}

	const getWareOptions = (houseId) => {
		wareOptions.value = []
		getWarehouseList(houseId).then((list) => {
			wareOptions.value = (list || []).map((d) => {
				return {
					label: d.warehouseName,
					value: d.warehouseId,
					raw: d
				}
			})
		})
	}

	const orgChanged = (n) => {
		if (n) {
			const o = orgOptions.value.find((d) => d.value === n)
			formData.value.orgName = o.label
			getHouseOptions(n)
		} else {
			formData.value.orgName = null
			formData.value.basicStorehouseId = null
			formData.value.storeHouseName = null
			formData.value.warehouseId = null
			formData.value.warehouseName = null
			houseOptions.value = []
			wareOptions.value = []
		}
	}

	const houseChanged = (n) => {
		if (n) {
			const o = houseOptions.value.find((d) => d.value === n)
			formData.value.storeHouseName = o.label
			getWareOptions(n)
		} else {
			formData.value.storeHouseName = null
			formData.value.warehouseId = null
			formData.value.warehouseName = null
			wareOptions.value = []
		}
	}

	const wareChanged = (n) => {
		if (n) {
			const o = wareOptions.value.find((d) => d.value === n)
			formData.value.warehouseName = o.label
		} else {
			formData.value.warehouseName = null
		}
	}

	const pzChanged = (n, o) => (formData.value.grainVarietyName = o?.label)

	const djChanged = (n, o) => (formData.value.grainGradeName = o?.label)

	const xzChanged = (n, o) => {
		if (n) {
			formData.value.grainNatureId = parseInt(n[n.length - 1])
			formData.value.grainGradeName = o[o.length - 1].label
		} else {
			formData.value.grainNatureId = null
			formData.value.grainGradeName = null
		}
	}

	const init = () => {
		resetForm()
		getOrgOptions()
		if (isEdit.value || isView.value) {
			getData()
		}
	}

	const getData = () => {
		getDetails(props.editData.id).then((resp) => {
			const items = resp.items

			if (resp.zbjgpd) {
				resp.zbjgpd = resp.zbjgpd.split('|')
			}
			if (resp.zblb) {
				resp.zblbArr = resp.zblb.split(',').map((d) => parseInt(d))
				for (let id of resp.zblbArr) {
					const list = resp.items.filter((d) => d.parentInspectionItemId == id)
					list.forEach((d) => {
						d.inspectionItemId = parseInt(d.inspectionItemId)
						d.key = genKey('temp')
					})
					console.log('lll', list)
					tableMap[`tableList_${id}`].value = list
				}
			}
			resp.xzId = resp.grainNatureId
			deleteField(resp, ['items'])
			getHouseOptions(resp.orgId)
			getWareOptions(resp.basicStorehouseId)
			formData.value = resp
		})
	}

	const resetForm = () => {
		formData.value = {
			zblbArr: [],
			xzId: null,

			basicStorehouseId: null, // integer(int32) basic_storehouse的id；仓房id
			bgcjsj: null, // string(date-time) 报告出具时间，格式：yyyy-MM-dd
			bz: null, // string 备注
			checkResult: null, // integer(int32) 检验结果
			createdate: null, // string(date-time) 创建日期
			dbsl: null, // number 代表数量，单位：公斤
			grainGradeId: null, // integer(int32) 粮食等级；basic_enum的id
			grainGradeName: null, // string false
			grainNatureId: null, // integer(int32) 粮食性质；basic_enum的id
			grainNatureName: null, // string 性质名称
			grainVarietyId: null, // integer(int32) 粮食品种；basic_enum的id
			grainVarietyName: null, // string 品种名称
			jdrxm: null, // string 监督人姓名
			jydw: null, // string 检验单位
			jylb: null, // string 检验类别，01：入仓验收；02：出仓检验；03：3
			jyr: null, // string 检验人，检验人员姓名，若有多个保管员，则用“|”进行分隔
			jysj: null, // string(date-time) 检验时间，格式：yyyy-MM-dd
			jyyj: null, // string 检验依据，1：国标,
			orgId: null, // integer(int32) 库区id
			orgName: null, // string 库区名称
			produceArea: null, // string 产地
			qfrq: null, // string 签发日期，格式：yyyy-MM-dd
			qydbh: null, // string 抽样单编号；扦样单编号
			qyqy: null, // string 扦样区域
			qyrxm: null, // string 抽样人员；扦样人姓名
			qysj: null, // string(date-time) 抽样日期；扦样时间，格式：yyyy-MM-dd
			receiveYear: null, // string 收获年度
			rkrq: null, // string(date-time) 入库日期，格式：yyyy-MM-dd
			samplePackageModel: null, // string 样品包装型号
			sampleStatus: null, // string 样品状态
			sfzcccnx: null, // string 是否正常存储年限，0：否,
			shrxm: null, // string 审核人姓名
			spaqzbsfhg: null, // string 食品安全指标是否合格，0：不合格,
			storeHouseName: null, // string 仓房名称
			updatedate: null, // string(date-time) 更新日期
			updatename: null, // string 更新人
			warehouseId: null, // integer(int32) basic_warehouse的id；货位id
			warehouseName: null, // string 货位名称
			ypbh: null, // string 样品编号
			ypdj: null, // string 样品等级，参考LS/T
			ypsl: null, // number 样品数量，单位：公斤
			zbjgpd: [], // string 指标结果判定，与指标类别对应，例如：达标|综合判定#宜存#合格
			zblb: null, // string 指标类别，7602:质量指标检验,7603：储存品质检验,7604：食品安全检验
			zjbgdh: null // string 质检报告单号，由检验类别+检验日期（yyyyMMdd）+4位顺序号组成
		}
	}

	const formRules = {
		orgId: just_required,
		jylb: just_required,
		basicStorehouseId: just_required,
		warehouseId: just_required,
		grainVarietyId: just_required,
		grainGradeId: just_required,
		xzId: just_required,
		produceArea: just_required,
		rkrq: just_required,
		jydw: just_required,
		jyyj: just_required,
		jysj: just_required,
		shrxm: just_required,
		spaqzbsfhg: just_required,
		zblbArr: required_array,
		zbjgpd: required_array,
		sfzcccnx: just_required,
		qysj: just_required,
		qydbh: just_required,
		ypsl: number_required(2),
		dbsl: number_required(2),
		ypdj: just_required
	}

	watch(
		() => props.visible,
		(n, o) => {
			if (n) {
				init()
			}
			show.value = n
		}
	)

	const close = () => emit('update:visible', false)

	const getLocalData = () => {
		const d = {
			...formData.value
		}
		if (d.zbjgpd) {
			if (d.zbjgpd.length > 0) {
				d.zbjgpd = d.zbjgpd.join('|')
			}
		} else {
			d.zbjgpd = null
		}
		// if (d.grainNatureId) {
		// 	if(d.grainNatureId)
		// }
		d.items = []
		if (d.zblbArr && d.zblbArr.length > 0) {
			const curr = getCurrentInstance()
			for (let id of d.zblbArr) {
				const list = refMap[`t_${id}`].value.getTableData()
				list.forEach((dd) => (dd.parentInspectionItemId = parseInt(id)))
				d.items.push(...list)
			}
			d.zblb = d.zblbArr.join(',')
		}
		deleteField(d, ['zblbArr', 'xzId'])
		return d
	}

	const save = () => {
		formRef.value.validate().then((_) => {
			let fun
			if (isEdit.value) {
				fun = update
			} else if (isAdd.value) {
				fun = add
			}
			fun(getLocalData())
				.then((resp) => {
					emit('on-save')
					close()
				})
				.catch((err) => {
					console.log('err', err)
				})
		})
	}

	onMounted(() => {})
</script>

<template>
	<xn-form-container title="详细信息" width="80%" v-model:visible="show" :destroy-on-close="true" @close="close">
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-divider>详细信息</a-divider>
			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="质检报告单号" name="zjbgdh">
						<a-input disabled placeholder="保存后自动生成" v-model:value="formData.zjbgdh" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="库区名称" name="orgId">
						<a-select :disabled="readonly" v-model:value="formData.orgId" @change="orgChanged">
							<a-select-option v-for="item in orgOptions" :value="item.value" :key="item.value">{{
								item.label
							}}</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="库区地址" name="registeredAddress">
						<a-input :disabled="readonly" v-model:value="formData.registeredAddress" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="检验类别" name="jylb">
						<common-select :readonly="readonly" v-model:value="formData.jylb" type="JYLB" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="仓房名称" name="basicStorehouseId">
						<a-select :disabled="readonly" v-model:value="formData.basicStorehouseId" @change="houseChanged">
							<a-select-option v-for="item in houseOptions" :value="item.value" :key="item.value">{{
								item.label
							}}</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="货位名称" name="warehouseId">
						<a-select :disabled="readonly" v-model:value="formData.warehouseId">
							<a-select-option
								v-for="item in wareOptions"
								:value="item.value"
								:key="item.value"
								@change="wareChanged"
								>{{ item.label }}</a-select-option
							>
						</a-select>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="品种" name="grainVarietyId">
						<common-select
							:readonly="readonly"
							v-model:value="formData.grainVarietyId"
							type="1061"
							load-type="enum"
							@on-change="pzChanged"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="粮食等级" name="grainGradeId">
						<common-select
							:readonly="readonly"
							v-model:value="formData.grainGradeId"
							type="1002"
							load-type="enum"
							@on-change="djChanged"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="粮食性质" name="xzId">
						<common-cascader
							v-model:value="formData.xzId"
							type="1032"
							load-type="enum"
							@on-change="xzChanged"
							:readonly="readonly"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="入库日期" name="rkrq">
						<a-date-picker v-model:value="formData.rkrq" valueFormat="YYYY-MM-DD" :disabled="readonly" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="收获年度" name="receiveYear">
						<a-date-picker v-model:value="formData.receiveYear" picker="year" valueFormat="YYYY" :disabled="readonly" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="产地" name="produceArea">
						<a-input :disabled="readonly" v-model:value="formData.produceArea" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="检验单位" name="jydw">
						<a-input :disabled="readonly" v-model:value="formData.jydw" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="检验依据" name="jyyj">
						<common-select :readonly="readonly" v-model:value="formData.jyyj" type="JYYJ" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="检验结果" name="checkResult">
						<common-select :readonly="readonly" v-model:value="formData.checkResult" type="JYJG" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="检验日期" name="jysj">
						<a-date-picker
							v-model:value="formData.jysj"
							valueFormat="YYYY-MM-DD HH:mm:ss"
							value
							:show-time="true"
							:disabled="readonly"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="检验人" name="jyr">
						<a-input :disabled="readonly" v-model:value="formData.jyr" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="报告出具时间" name="bgcjsj">
						<a-date-picker
							v-model:value="formData.bgcjsj"
							valueFormat="YYYY-MM-DD HH:mm:ss"
							:show-time="true"
							:disabled="readonly"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="签发日期" name="qfrq">
						<a-date-picker v-model:value="formData.qfrq" valueFormat="YYYY-MM-DD" :disabled="readonly" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="审核人姓名" name="shrxm">
						<a-input :disabled="readonly" v-model:value="formData.shrxm" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="食品安全指标是否合格" name="spaqzbsfhg">
						<common-select :readonly="readonly" v-model:value="formData.spaqzbsfhg" type="AQZB" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="指标类别" name="zblbArr">
						<common-select
							:readonly="readonly"
							v-model:value="formData.zblbArr"
							type="7601"
							load-type="enum"
							:multiple="true"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="指标判定结果" name="zbjgpd">
						<common-cascader v-model:value="formData.zbjgpd" type="PDJG" :multiple="true" :readonly="readonly" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="是否正常存储年限" name="sfzcccnx">
						<common-select :readonly="readonly" v-model:value="formData.sfzcccnx" type="CCNX" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-divider>样品信息</a-divider>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="抽样日期" name="qysj">
						<a-date-picker
							v-model:value="formData.qysj"
							valueFormat="YYYY-MM-DD HH:mm:ss"
							:show-time="true"
							:disabled="readonly"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="抽样单编号" name="qydbh">
						<a-input :disabled="readonly" v-model:value="formData.qydbh" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="抽样人员" name="qyrxm">
						<a-input :disabled="readonly" v-model:value="formData.qyrxm" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="扦样区域" name="qyqy">
						<a-input :disabled="readonly" v-model:value="formData.qyqy" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="监督人姓名" name="jdrxm">
						<a-input :disabled="readonly" v-model:value="formData.jdrxm" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="样品编号" name="ypbh">
						<a-input :disabled="readonly" v-model:value="formData.ypbh" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="样品数量" name="ypsl">
						<a-input :disabled="readonly" v-model:value="formData.ypsl" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="代表数量" name="dbsl">
						<a-input :disabled="readonly" v-model:value="formData.dbsl" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="样品等级" name="ypdj">
						<a-input :disabled="readonly" v-model:value="formData.ypdj" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="样品状态" name="sampleStatus">
						<a-input :disabled="readonly" v-model:value="formData.sampleStatus" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="样品包装型号" name="samplePackageModel">
						<a-input :disabled="readonly" v-model:value="formData.samplePackageModel" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-divider>检验项目及依据</a-divider>
			<aq-table
				ref="t_7602"
				v-show="formData.zblbArr && formData.zblbArr.includes(7602)"
				enum-id="7587"
				title="质量指标检验"
				:data-list="tableList_7602"
				:readonly="readonly"
			/>
			<aq-table
				ref="t_7603"
				v-show="formData.zblbArr && formData.zblbArr.includes(7603)"
				enum-id="7587"
				title="储存品质检验"
				:data-list="tableList_7603"
				:readonly="readonly"
			/>
			<aq-table
				ref="t_7604"
				v-show="formData.zblbArr && formData.zblbArr.includes(7604)"
				enum-id="7587"
				title="食品安全检验"
				:data-list="tableList_7604"
				:readonly="readonly"
			/>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="close">关闭</a-button>
			<a-button v-if="!readonly" style="margin-right: 8px" type="primary" @click="save" :loading="submitLoading">
				保存
			</a-button>
		</template>
	</xn-form-container>
</template>

<style scoped></style>
