<template>
	<div class="mesBusLog-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" width="50%" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>添加载具</span>
				</div>
			</template>
			<div style="width: 100%">
				<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" @submit.native.prevent>
					<el-row :gutter="35">
						<el-col :span="24" class="mb20">
							<el-form-item label="扫描载具条码" prop="packCode">
								<el-input
									v-model.trim="ruleForm.packCode"
									placeholder="可搜索、可扫描"
									clearable
									@keyup.enter.stop="getPackList(false)"
									:disabled="props.processform.isFirstProcess == 0 && tableData.length > 0"
								>
									<template #append>
										<el-icon class="el-input__icon" style="cursor: pointer" @click="getPackList(false)">
											<ele-FullScreen />
										</el-icon>
									</template>
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<div>
					<el-table :data="tableData" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id" border="">
						<!-- <el-table-column type="selection" width="55" /> -->
						<el-table-column type="index" label="序号" width="55" align="center" />
						<el-table-column prop="packCode" label="载具编码" show-overflow-tooltip="" />
						<el-table-column prop="packName" label="载具名称" show-overflow-tooltip="" />
						<el-table-column prop="maxNum" label="最大载容量" show-overflow-tooltip="" />
						<el-table-column prop="batchNo" label="批次号" show-overflow-tooltip="" v-if="props.processform.isFirstProcess == 0" />
						<el-table-column label="操作" width="120" align="center" fixed="right" v-if="sign == 1">
							<template #default="scope">
								<el-button icon="ele-Delete" size="small" type="primary" @click="subDelete(scope.row, scope.$index)"> 删除 </el-button>
							</template>
						</el-table-column>
					</el-table>
					<!-- <el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize" :total="tableParams.total" :page-sizes="[10, 20, 50, 100, 200, 500]" small="" background="" @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" /> -->
				</div>
			</div>
			<!-- 消耗载具部分 -->
			<div style="width: 100%; margin-top: 30px" v-if="props.processform.isFirstProcess == 0 && props.processform.isAssemble == 0">
				<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules" @submit.native.prevent>
					<el-row :gutter="35">
						<el-col :span="24" class="mb20">
							<el-form-item label="扫描消耗载具" prop="attaPackCode">
								<el-input v-model.trim="ruleForm.attaPackCode" placeholder="可搜索、可扫描" clearable @keyup.enter.stop="getPackList(true)">
									<template #append>
										<div style="display: flex; flex-direction: row; width: 150px">
											<el-select v-model="orderAttrPackSelect" placeholder="选择" style="width: 120px; margin-right: 20px" @change="onOrderAttrPackChange">
												<el-option v-for="(atItem, idx) in orderAttrPackList" :key="idx" :label="`[${atItem.packCode}]${atItem.packName}`" :value="atItem.packCode" />
											</el-select>
											<el-icon class="el-input__icon" style="cursor: pointer; width: 30px" @click="getPackList(true)">
												<ele-FullScreen />
											</el-icon>
										</div>
									</template>
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<div>
					<el-table :data="attaTableData" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id" border="">
						<!-- <el-table-column type="selection" width="55" /> -->
						<el-table-column type="index" label="序号" width="55" align="center" />
						<el-table-column prop="packCode" label="载具编码" show-overflow-tooltip="" />
						<el-table-column prop="packName" label="载具名称" show-overflow-tooltip="" />
						<el-table-column prop="materialCode" label="MES编码" show-overflow-tooltip="" />
						<el-table-column prop="materialName" label="MES名称" show-overflow-tooltip="" />
						<el-table-column prop="batchNo" label="批次号" show-overflow-tooltip="" />
						<el-table-column prop="num" label="装载数量" show-overflow-tooltip="" />
						<el-table-column prop="processCode" label="来源工序" show-overflow-tooltip="" />
						<el-table-column prop="produceWorkOrderNo" label="生产工单" show-overflow-tooltip="" />
						<!-- <el-table-column prop="maxNum" label="最大载容量" show-overflow-tooltip="" /> -->
						<el-table-column label="操作" width="120" align="center" fixed="right">
							<template #default="scope">
								<el-button icon="ele-Delete" size="small" type="primary" @click="subDelete2(scope.row, scope.$index)"> 删除 </el-button>
							</template>
						</el-table-column>
					</el-table>
					<!-- <el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize" :total="tableParams.total" :page-sizes="[10, 20, 50, 100, 200, 500]" small="" background="" @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" /> -->
				</div>
			</div>
			<!-- 装配消耗载具部分 -->
			<div style="width: 100%; margin-top: 30px" v-if="props.processform.isAssemble == 1">
				<div v-for="(item, idx) in boms" :key="item.id">
					<el-form :model="ruleForm[item.materialCode]" ref="ruleFormRef" label-width="auto" :rules="rules" style="margin-top: 20px" @submit.native.prevent>
						<el-row :gutter="35">
							<el-col :span="24" class="mb10">
								<el-form-item :label="`${item.materialName}[${item.materialCode}] 扫描消耗载具`" prop="attaPackCode">
									<el-input
										v-model.trim="ruleForm[item.materialCode].attaPackCode"
										placeholder="可搜索、可扫描"
										style="width: 250px"
										clearable
										@keyup.enter.stop="getPackList(true, item.materialCode)"
									>
										<template #append>
											<el-icon class="el-input__icon" style="cursor: pointer" @click="getPackList(true, item.materialCode)">
													<ele-FullScreen />
												</el-icon>
										</template>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
					<div>
						<el-table :data="assembleData[item.materialCode]" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id" border="">
							<!-- <el-table-column type="selection" width="55" /> -->
							<el-table-column type="index" label="序号" width="55" align="center" />
							<el-table-column prop="packCode" label="载具编码" show-overflow-tooltip="" />
							<el-table-column prop="packName" label="载具名称" show-overflow-tooltip="" />
							<el-table-column prop="materialCode" label="MES编码" show-overflow-tooltip="" />
							<el-table-column prop="materialName" label="MES名称" show-overflow-tooltip="" />
							<el-table-column prop="batchNo" label="批次号" show-overflow-tooltip="" />
							<el-table-column prop="num" label="装载数量" show-overflow-tooltip="" />
							<el-table-column prop="processCode" label="来源工序" show-overflow-tooltip="" />
							<el-table-column prop="produceWorkOrderNo" label="生产工单" show-overflow-tooltip="" />
							<!-- <el-table-column prop="maxNum" label="最大载容量" show-overflow-tooltip="" /> -->
							<el-table-column label="操作" width="120" align="center" fixed="right">
								<template #default="scope">
									<el-button icon="ele-Delete" size="small" type="primary" @click="subDelete2(scope.row, scope.$index, item.materialCode)"> 删除 </el-button>
								</template>
							</el-table-column>
						</el-table>
						<!-- <el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize" :total="tableParams.total" :page-sizes="[10, 20, 50, 100, 200, 500]" small="" background="" @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" /> -->
					</div>
				</div>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="relPackHandle">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormRules } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { queryPackList, relPack, getAttaPackList, getAssembleBomList, getPreWorkOrderProcessPack } from '/@/api/mes/mesControlBoard';

//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: '',
	},
	produceWorkOrderNo: {
		type: String,
		default: '',
	},
	processform: {
		type: Object,
		default: null,
	},
});
const subDelete = (item: any, i: number) => {
	tableData.value.splice(i, 1);
};
const subDelete2 = (item: any, i: number, material: string = '') => {
	if (material) {
		assembleData.value[material].splice(i, 1);
	} else {
		attaTableData.value.splice(i, 1);
	}
};
//自行添加其他规则
const rules = ref<FormRules>({
	packCode: [{ required: true, message: '请扫描载具编码！', trigger: 'blur' }],
});

//父级传递来的函数，用于回调
const emit = defineEmits(['reloadTable']);
const ruleFormRef = ref();
const tableData = ref<any>([]);
const loading = ref(false);
const tableParams = ref({
	page: 1,
	pageSize: 10,
	total: 0,
});
const handleSizeChange = (val: number) => {
	tableParams.value.pageSize = val;
	handleQuery();
};
// 改变页码序号
const handleCurrentChange = (val: number) => {
	tableParams.value.page = val;
	handleQuery();
};
const handleQuery = () => {};

const ruleForm = ref<any>({});
const state = reactive({
	isShowDialog: false,
});

// 页面加载时
onMounted(() => {});
const sign = ref(0);
const boms = ref([]);

const opType = ref(0); //0.上料 1.装配  2.后工序

// 打开弹窗
const openDialog = async (row: any) => {
	// 改用detail获取最新数据来编辑
	let rowData = JSON.parse(JSON.stringify(row));
	sign.value = rowData.sign;

	orderAttrPackList.value=[];
	attaTableData.value = [];
	tableData.value = [];
	assembleData.value = {};
	if (rowData.sign == 2) {
		tableData.value = [rowData];

		var res = await getAttaPackList({ packCode: rowData.packCode, produceWorkOrderNo: props.produceWorkOrderNo });
		attaTableData.value = res.data.result || [];
	}

	if (props.processform.isFirstProcess == 1 && props.processform.isAssemble == 0) {
		//上料
		opType.value = 0;
	} else if (props.processform.isAssemble == 1) {
		//装配
		opType.value = 1;
	} else {
		//后工序
		opType.value = 2;
	}

	if (opType.value == 1) {
		var res = await getAssembleBomList({ produceWorkOrderNo: props.produceWorkOrderNo });

		(res.data.result || []).forEach((item: any) => {
			ruleForm.value[item.materialCode] = {};
		});

		boms.value = res.data.result || [];
		if (attaTableData.value.length > 0) {
			attaTableData.value.forEach((item) => {
				if (!assembleData.value[item.materialCode]) assembleData.value[item.materialCode] = [];
				assembleData.value[item.materialCode].push(item);
			});
		}
	}
	if (opType.value != 0) {
		loadPreAttrPack();
	}

	state.isShowDialog = true;
};

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

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

const attaTableData = ref<any>([]);
const assembleData = ref<any>({});
const getPackList = async (isAtta: boolean = false, material: string = '') => {
	if (isAtta == false) {
		// if (tableData.value.length > 0) {
		// 	ElMessage.error('已扫描载具，不能再添加');
		// 	return;
		// }

		if (!ruleForm.value.packCode) {
			return ElMessage.error('请扫描载具编码');
		}
	} else {
		if (material) {
			if (!ruleForm.value[material].attaPackCode) {
				return ElMessage.error('请扫描消耗载具编码');
			}
			if (assembleData.value[material] && assembleData.value[material].find((item) => item.packCode == ruleForm.value[material].attaPackCode)) {
				return ElMessage.error('请勿重复扫描载具');
			}
		} else {
			if (!ruleForm.value.attaPackCode) {
				return ElMessage.error('请扫描消耗载具编码');
			}
			if (attaTableData.value.find((item) => item.packCode == ruleForm.value.attaPackCode)) {
				return ElMessage.error('请勿重复扫描载具');
			}
		}
	}

	let res =
		(
			await queryPackList({
				packCode: isAtta ? (material ? ruleForm.value[material].attaPackCode : ruleForm.value.attaPackCode) : ruleForm.value.packCode,
			})
		)?.data?.result || {};

	if (isAtta == false) {
		if (res.packStatus != 0) {
			ElMessage.error('此载具不是空闲状态，不能绑定');
			return;
		}
		if (tableData.value.find((u: any) => u.packCode == res.packCode)) {
			ElMessage.error('此载具已绑定，不能重复绑定');
			return;
		}
		tableData.value.push(res);
		ruleForm.value.packCode = '';
		ruleFormRef.value.clearValidate();
	} else {
		if (res.packStatus != 2) {
			ElMessage.error('此载具未装载完成，不能绑定为消耗载具');
			return;
		}
		if(tableData.value.length>0){
			if(res.productStatus!=tableData.value[0].productStatus && tableData.value[0].num){
				return ElMessage.error(`此消耗载具产品状态[${res.productStatus}]与当前放入载具状态[${tableData.value[0].productStatus}]不一致，不能绑定`);
			}
		}

		if (opType.value == 1) {
			//装配
			if (res.materialCode != material) {
				return ElMessage.error('此载具物料与当前物料不一致，不能绑定为消耗载具');
			}
			if (assembleData.value[material] && assembleData.value[material].length > 0 && assembleData.value[material][0].batchNo != res.batchNo) {
				return ElMessage.error(`当前消耗载具绑定的批次号为：${assembleData.value[material][0].batchNo}`);
			}
		} else {
			if (attaTableData.value.length > 0) {
				if (res.batchNo != attaTableData.value[0].batchNo) return ElMessage.error('此载具与已绑定的消耗载具批次号不一致，不能绑定');
				if (res.materialCode != attaTableData.value[0].materialCode) return ElMessage.error('此载具物料与当前物料不一致，不能绑定为消耗载具');
			}
		}
		if (material) {
			if (res.num <= 0) return ElMessage.error('此载具内数量为零，不能绑定为消耗载具');
			if (res.nextProcessCode) return ElMessage.error(`此载具的工序不是最后一道工序，不能绑定为消耗载具`);
			if (!assembleData.value[material]) assembleData.value[material] = [];
			assembleData.value[material].push(res);
		} else {
			if (res.num <= 0) return ElMessage.error('此载具内数量为零，不能绑定为消耗载具');
			if (res.nextProcessCode != props.processform.processCode) return ElMessage.error(`此载具不属于当前工序，不能绑定为消耗载具`);

			attaTableData.value.push(res);
		}
		ruleForm.value.attaPackCode = '';
	}
};
//确定
const relPackHandle = async () => {
	if (tableData.value.length == 0) return ElMessage.warning('请添加载具后操作');

	var attaCodes = [];
	if (opType.value == 2 && props.processform.processCode != 'BZ') {
		if (attaTableData.value.length == 0) {
			return ElMessage.warning('请添加消耗载具后操作');
		}
		attaTableData.value.forEach((item: any) => {
			attaCodes.push(item.packCode);
		});
	} else if (opType.value == 1) {
		if (!assembleData.value || Object.keys(assembleData.value).length == 0) {
			return ElMessage.warning('请添加消耗载具后操作');
		}
		Object.keys(assembleData.value).forEach((item: any) => {
			assembleData.value[item].forEach((item2: any) => {
				attaCodes.push(item2.packCode);
			});
		});
	}
	var dataRows = [];
	tableData.value.forEach((item: any) => {
		dataRows.push(item.packCode);
	});

	await relPack({
		ProduceWorkOrderNo: props.produceWorkOrderNo,
		PackCodeList: dataRows,
		AttaPackCodeList: attaCodes,
		IsAtta: sign.value == 2 ? true : false,
	});
	ElMessage.success('操作成功');
	closeDialog();
};

const orderAttrPackList = ref([]);
const orderAttrPackSelect = ref('');
const loadPreAttrPack = () => {
	getPreWorkOrderProcessPack({ workOrderNo: props.produceWorkOrderNo,batchNo:props.processform.batchNo, processCode: props.processform.processCodePre }).then((res) => {
		orderAttrPackList.value = res.data.result;
	});
};
const onOrderAttrPackChange = (e)=>{
	ruleForm.value.attaPackCode=e;
	nextTick(()=>{
		getPackList(true);
		orderAttrPackSelect.value='';
	})
}

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