﻿<template>
	<div class="mesQiInspTemp-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" :width="800" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="产品" prop="productCode">
							<!--							<el-input v-model="state.ruleForm.productCode" placeholder="请输入产品编码" maxlength="100" show-word-limit clearable />-->
							<el-input v-model="state.ruleForm.productCode" placeholder="请选择产品" maxlength="100" show-word-limit clearable>
								<template #append>
									<el-button @click="openChoose">选择</el-button>
								</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="选择零件" prop="partCode">
							<!-- <el-cascader style="width: 100%" @change="onBomChange" :options="bomTreeData" :props="{ checkStrictly: true }" :collapse-tags-tooltip="true"> </el-cascader> -->
							<el-tree-select v-model="state.ruleForm.partCode" :data="bomTreeData" clearable :check-strictly="true" :render-after-expand="false" style="width: 100%" @change="onPartChange" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="工序编码" prop="processCode">
							<el-select clearable filterable v-model="state.ruleForm.processCode" placeholder="请选择工序编码" @change="onProcessChange">
								<el-option v-for="(item, index) in bindProcessList" :key="index" :value="item.processCode" :label="`[${item.processCode}]${item.processName}`" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="检验类型" prop="inspType">
							<el-select clearable v-model="state.ruleForm.inspType" placeholder="请选择检验类型">
								<el-option v-for="(item, index) in dl('checkTypes')" :key="index" :value="parseInt(item.value)" :label="`${item.name}`"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序" prop="sorts">
							<el-input-number v-model="state.ruleForm.sorts" placeholder="请输入排序" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" placeholder="请输入备注" maxlength="500" show-word-limit clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div>
				<div v-for="item in curTens">
					<el-tag type="warning">{{ item.technicalName }}</el-tag>
				</div>
			</div>
			<template v-if="state.ruleForm.id && isCopy == false">
				<el-tabs v-model="tabActive">
					<el-tab-pane label="检验项目及标准" name="item"></el-tab-pane>
					<el-tab-pane label="检验规则" name="rule"></el-tab-pane>
				</el-tabs>
				<MesQiInspTempItem :qiInspTempId="state.ruleForm.id" v-if="tabActive == 'item'"></MesQiInspTempItem>
				<MesQiInspTempRule :qiInspTempId="state.ruleForm.id" v-if="tabActive == 'rule'"></MesQiInspTempRule>
			</template>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<!--  选择产品  -->
		<choose-material title="选择产品" ref="chooseMaterialRef" type="2" :is-any="false" @finish="onChooseMaterialFinish"></choose-material>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormRules } from 'element-plus';
import { addMesQiInspTemp, updateMesQiInspTemp, detailMesQiInspTemp } from '/@/api/mes/mesQiInspTemp';
import { pageMesQiInspTemp, deleteMesQiInspTemp } from '/@/api/mes/mesQiInspTemp';
import { getMesProcessProcessCodeDropdown } from '/@/api/mes/mesQiInspTemp';
import ChooseMaterial from '/@/businessComponents/chooseMaterial.vue';
import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
import MesQiInspTempItem from '/@/views/mes/mesQiInspTempItem/index.vue';
import MesQiInspTempRule from '/@/views/mes/mesQiInspTempRule/index.vue';
import { getBomList } from '/@/api/mes/mesProduct';
import { pageMesTechnical } from '/@/api/mes/mesTechnical';

//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: '',
	},
});
//父级传递来的函数，用于回调
const emit = defineEmits(['reloadTable']);
const ruleFormRef = ref();
const state = reactive({
	isShowDialog: false,
	ruleForm: {} as any,
});

//自行添加其他规则
const rules = ref<FormRules>({
	productCode: [{ required: true, message: '请输入产品编码！', trigger: 'blur' }],
	inspType: [{ required: true, message: '请选择检验类型！', trigger: 'change' }],
});

// 页面加载时
onMounted(() => {});

const tabActive = ref('item');
const chooseMaterialRef = ref();
const openChoose = () => {
	chooseMaterialRef.value.openDialog({});
};
const onChooseMaterialFinish = async (row) => {
	state.ruleForm.productName = row?.materialName;
	state.ruleForm.productCode = row?.materialCode;

	await loadBomTree(state.ruleForm.productCode);
	// state.ruleForm.productNo = row?.materialNo;
};
const isCopy = ref(false);

const tenList = ref([]);
// 打开弹窗
const openDialog = async (row: any) => {
	// state.ruleForm = JSON.parse(JSON.stringify(row));
	// 改用detail获取最新数据来编辑

	var tenRes = await pageMesTechnical({ page: 1, pageSize: 999 });
	tenList.value = tenRes.data.result?.items || [];

	await getMesProcessProcessCodeDropdownList();
	isCopy.value = false;
	let rowData = JSON.parse(JSON.stringify(row));
	if (rowData.id) {
		state.ruleForm = (await detailMesQiInspTemp(rowData.id)).data.result;
		isCopy.value = row.isCopy;
		state.ruleForm.isCopy = isCopy.value;
	} else state.ruleForm = rowData;
	if (state.ruleForm.productCode){
		await loadBomTree(state.ruleForm.productCode);
	}
	if (state.ruleForm.processCode){
		await onPartChange(state.ruleForm.partCode)
		await onProcessChange(state.ruleForm.processCode)
	}
	state.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit('reloadTable');
	state.isShowDialog = false;
};

// 取消
const cancel = () => {
	state.isShowDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = state.ruleForm;
			if (state.ruleForm.id == undefined || state.ruleForm.id == null || state.ruleForm.id == '' || state.ruleForm.id == 0) {
				await addMesQiInspTemp(values);
			} else {
				await updateMesQiInspTemp(values);
			}
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: 'error',
			});
		}
	});
};

const mesProcessProcessCodeDropdownList = ref<any>([]);
const getMesProcessProcessCodeDropdownList = async () => {
	let list = await getMesProcessProcessCodeDropdown();
	mesProcessProcessCodeDropdownList.value = list.data.result ?? [];
	// bindProcessList.value = mesProcessProcessCodeDropdownList.value;
};

const bomTreeData = ref([]);
const bomTreeList = ref([]);
const loadBomTree = async (produceCode: any) => {
	var res = await getBomList({ productCode: produceCode });
	var treeData = res.data.result.filter((u: any) => u.pid == 0); //&& u.processList && u.processList.length>0

	treeData.forEach((el: any) => {
		el.value = el.materialCode;
		el.label = `${el.materialName}[${el.materialCode}]`;
		el.disabled = !el.processList || el.processList.length == 0;

		if (el.processList && el.processList.length > 0) {
			el.processList.forEach((u: any) => {
				var p = mesProcessProcessCodeDropdownList.value.find((el5) => el5.value == u.processCode);
				if (p) u.processName = p?.label;

				var tens = [];
				(u.technicalCodes || []).forEach((el3: any) => {
					var tenName = tenList.value.find((y) => y.technicalCode == el3);
					tens.push(JSON.parse(JSON.stringify(tenName)));
				});
				u.tens = tens;
			});
		}

		recBom(res.data.result, el);
	});
	console.log(treeData);
	bomTreeData.value = treeData;
	bomTreeList.value = res.data.result;
};
const recBom = (bomList: any[], row: any) => {
	if (bomList) {
		var list = bomList.filter((u: any) => u.pid == row.productBomId); //&& u.processList && u.processList.length>0
		row.children = list;
		list.forEach((el: any) => {
			el.value = el.materialCode;
			el.label = `${el.materialName}[${el.materialCode}]`;
			el.disabled = !el.processList || el.processList.length == 0;

			if (el.processList && el.processList.length > 0) {
				el.processList.forEach((u: any) => {
					var p = mesProcessProcessCodeDropdownList.value.find((el5) => el5.value == u.processCode);

					if (p) u.processName = p?.label;

					var tens = [];
					(u.technicalCodes || []).forEach((el3: any) => {
						var tenName = tenList.value.find((y) => y.technicalCode == el3);
						tens.push(JSON.parse(JSON.stringify(tenName)));
					});
					u.tens = tens;
				});
			}

			recBom(bomList, el);
		});
	}
};
const bindProcessList = ref([]);
const onPartChange = async(e: any) => {
	// state.ruleForm.processCode = null;

	// if (!e) {
	// 	bindProcessList.value = mesProcessProcessCodeDropdownList.value;
	// 	return;
	// }
	var el = bomTreeList.value.find((u: any) => u.value == e);
	console.log(el);
	// var procsssList = [] as any[];
	// (el.processList || []).forEach((u: any) => {
	// 	var temp = mesProcessProcessCodeDropdownList.value.find((y) => y.value == u.processCode);
	// 	var tenNames = [];
	// 	if (u.technicalCodes) {
	// 		u.technicalCodes.forEach((el: any) => {
	// 			var temp = tenList.value.find((u) => u.technicalCode == el);
	// 			if (temp) {
	// 				tenNames.push(temp.technicalName);
	// 			}
	// 		});
	// 	}

	// 	temp.tens = tenNames;
	// 	if (temp) procsssList.push(temp);
	// });
	bindProcessList.value = el.processList;
};
const curTens = ref([]);
const onProcessChange = async (e: any) => {
	console.log('ddd', bindProcessList.value);

	var el = bindProcessList.value.find((u: any) => u.processCode == e);

	curTens.value = el?.tens||[];
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
