<template>
	<div class="mesBusLog-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" width="60%" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ props.title }}</span>
				</div>
			</template>
			<div style="width: 100%">
				<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
					<el-row :gutter="35">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="扫描/输入员工码" prop="workAccount">
								<el-input v-model="ruleForm.workAccount" placeholder=" " clearable @keyup.enter.stop="onScanAccount" style="width: 70%">
									<template #append>
										<el-icon class="el-input__icon" style="cursor: pointer" @click="onScanAccount">
											<ele-FullScreen />
										</el-icon>
									</template> </el-input
								>{{ workUser?.realName || '' }}
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="批次号" prop="batchNo">
								<el-input v-model="ruleForm.batchNo" placeholder="请输入批次号" clearable :disabled="true" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="props.processCode != 'BZ'">
							<el-form-item label="载具编码" prop="packCode">
								<el-input v-model="ruleForm.packCode" placeholder="请输入载具编码" clearable :disabled="true" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="props.processCode != 'BZ'">
							<el-form-item label="载具名称" prop="packName">
								<el-input v-model="ruleForm.packName" placeholder="请输入载具名称" clearable :disabled="true" />
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item :label="sign == 1 ? '装载数量' : '报工数量'" prop="num">
								<el-input-number v-model="ruleForm.num" placeholder="请输入数量" clearable :min="0" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="报工工时(h)" prop="hours">
								<el-input-number v-model="ruleForm.hours" :min="0" :precision="1" placeholder="请输入报工工时(小时)" clearable />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="备注" prop="remark">
								<el-input type="textarea" v-model="ruleForm.remark" placeholder=" " clearable :maxlength="200" />
							</el-form-item>
						</el-col>
						<!-- <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="报工单位" prop="busCode">
                <el-input v-model="ruleForm.busCode" placeholder=" " disabled clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="速度" prop="deviceSpeed">
                <el-input v-model="ruleForm.deviceSpeed" placeholder=" " disabled clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="压力" prop="deviceYl">
                <el-input v-model="ruleForm.deviceYl" placeholder=" " disabled clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="功率" prop="deviceGl">
                <el-input v-model="ruleForm.deviceGl" placeholder=" " disabled clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="达因值≥" prop="deviceDyz">
                <el-input v-model="ruleForm.deviceDyz" placeholder=" " disabled clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="贴膜静置" prop="busCode">
                <el-input v-model="ruleForm.deviceTm" placeholder=" " disabled clearable />
              </el-form-item>
            </el-col> -->
					</el-row>
				</el-form>
				<div v-if="sign == 2">
					<el-table :data="attaTableData" style="width: 100%" 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="unitUse" label="单位用量" show-overflow-tooltip="" />
						<el-table-column prop="batchNo" 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 prop="num" label="装载数量" show-overflow-tooltip="" />
						<el-table-column label="消耗数量" width="120" align="center">
							<template #default="scope">
								<el-input-number v-model="scope.row.useNum" :min="0" :max="scope.row.freeNum" :precision="0" @change="onUseNumChange" />
							</template>
						</el-table-column>
						<el-table-column prop="freeNum" label="剩余数量" align="center"></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 style="width: 100%; margin-top: 30px" v-if="sign == 3">
					<div v-for="(item, idx) in boms" :key="item.id">
						<el-form :model="ruleForm" label-width="auto" style="margin-top: 20px">
							<el-row :gutter="35">
								<el-col :span="24" class="mb10">
									<el-form-item :label="`${item.materialName}[${item.materialCode}] 消耗载具生产批次：`" prop="attaPackCode">
										<el-text type="warning">{{ attaTableData.filter((el: any) => el.materialCode == item.materialCode)[0].batchNo }}</el-text>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
						<div>
							<el-table :data="attaTableData.filter((el: any) => el.materialCode == item.materialCode)" style="width: 100%" 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="unitUse" 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 prop="num" label="装载数量" show-overflow-tooltip="" />
								<el-table-column label="消耗数量" width="120" align="center">
									<template #default="scope">
										<el-input-number v-model="scope.row.useNum" :min="0" :max="scope.row.freeNum" :precision="0" @change="onUseNumChange" />
									</template>
								</el-table-column>
								<el-table-column prop="freeNum" label="剩余数量" align="center"></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>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</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 } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormRules } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { finishWork, getOnlineRecord, getAttaPackList, getAssembleBomList } from '/@/api/mes/mesControlBoard';
import { getPersonByAccount } from '/@/api/mes/mesControlBoard';
import { min } from 'lodash-es';

//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: '',
	},
	produceWorkOrderNo: {
		type: String,
		default: '',
	},
	preBatchNo: {
		type: String,
		default: '',
	},
	processCode: {
		type: String,
		default: '',
	},
	equipmentCode: {
		type: String,
		default: '',
	},
	productionLineCode: {
		type: String,
		default: '',
	},
});

//自行添加其他规则
const rules = ref<FormRules>({
	batchNo: [{ required: true, message: '请输入批次号！', trigger: 'blur' }],
	// num: [{ required: true, message: '请输入报工数量！', trigger: 'blur' }],
});

//父级传递来的函数，用于回调
const emit = defineEmits(['reloadTable', 'reflashWorkOrderInfo']);
const ruleFormRef = ref();
const handleQuery = () => {};

const ruleForm = ref<any>({});
const state = reactive({
	isShowDialog: false,
	batchDisabled: false,
});
const attaTableData = ref<any>([]);
// 页面加载时
onMounted(() => {});

// 获取当前在岗人员
// const onLinePersonList = ref([]);
const getonlineList = async () => {
	// let res =
	// 	(
	// 		await getOnlineRecord({
	// 			workOrderNo: props.produceWorkOrderNo,
	// 		})
	// 	)?.data?.result || [];
	// onLinePersonList.value = res;
};
const sign = ref(1); // 1.上料 2.后工序 3.装配
const boms = ref([]);
// 打开弹窗
const openDialog = async (row: any) => {
	// 改用detail获取最新数据来编辑
	let rowData = JSON.parse(JSON.stringify(row));
	sign.value = rowData.sign;
	state.isShowDialog = true;

	ruleForm.value.workAccount = workUser.value.account || '';

	ruleForm.value.batchNo = `${row.processform.batchNo}`;
	ruleForm.value.num = 0;
	ruleForm.value.packCode = row.packCode;
	ruleForm.value.packName = row.packName;
	state.batchDisabled = false;
	attaTableData.value = [];

	if (rowData.sign == 2 || rowData.sign == 3) {
		var res = await getAttaPackList({ packCode: rowData.packCode, produceWorkOrderNo: props.produceWorkOrderNo });

		var tab = res.data.result || [];
		tab.forEach((el: any) => {
			// el.totalUseNum = 0;
			// if (el.packUseRecordList) {
			// 	el.packUseRecordList.forEach((item: any) => {
			// 		el.totalUseNum += item.useNum;
			// 	});
			// }
			el.freeNum = el.num;
		});
		attaTableData.value = tab;
		if (attaTableData.value.length > 0) {
			state.batchDisabled = true;
			// ruleForm.value.batchNo = attaTableData.value[0].batchNo;
		}
	}
	if (rowData.sign == 3) {
		var res = await getAssembleBomList({ produceWorkOrderNo: props.produceWorkOrderNo });
		boms.value = res.data.result || [];
	}

	// getonlineList();
};

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

// 取消
const cancel = () => {
	state.isShowDialog = false;
};
//消耗数量输入变动
const onUseNumChange = () => {
	let num = 0;

	if (sign.value == 3) {
		var computerNum = 0;
		try {
			boms.value.forEach((item: any) => {
				var _num = 0;
				attaTableData.value.forEach((item2: any) => {
					if (item.materialCode == item2.materialCode) {
						_num = item2.useNum || 0;
					}
				});
				// tempNums[item.materialCode] = _num;
				if (!_num) {
					ruleForm.value.num = null;
					throw 'aaaa';
				} else {
					var _num2 = _num / (item.unitUse || 1);
					if (computerNum < _num2) computerNum = _num2;
				}
			});
			if (computerNum > 0) {
				ruleForm.value.num = computerNum;
			}
		} catch (error) {}
	} else {
		attaTableData.value.forEach((item: any) => {
			num = num + (item.useNum || 0);
		});
		ruleForm.value.num = parseInt((num / (attaTableData.value[0].unitUse || 1)).toFixed(0));
	}
};
const workUser = ref({});
// 报工
const submit = async () => {
	if (!workUser.value.account) return ElMessage.warning('请扫描/输入员工码，并回车');
	if (!ruleForm.value.num && !ruleForm.value.hours) {
		return ElMessage.warning('请输入报工数量或工时');
	}
	var useList = [];
	var materialNums = [];
	attaTableData.value.forEach((item: any) => {
		if (item.useNum > 0) {
			useList.push({
				PackCode: item.packCode,
				UseNum: item.useNum,
				UnitUse: item.unitUse,
				MaterialCode: item.materialCode,
			});

			var mat = materialNums.find((u: any) => u.materialCode == item.materialCode);
			if (mat) {
				mat.num += (item.useNum || 0) / (item.unitUse || 1);
			} else {
				materialNums.push({
					materialCode: item.materialCode,
					num: (item.useNum || 0) / (item.unitUse || 1),
				});
			}
		}
	});
	if (materialNums.length > 0) {
		var preNum = materialNums[0].num;
		materialNums.forEach((item: any) => {
			if (preNum != item.num) {
				ElMessage.warning(`[${item.materialCode}]报工数量不一致，请重新输入`);
				throw 'aaaa';
			}
		});
		console.log('materialNums', materialNums);
	}

	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			await finishWork({
				produceWorkOrderNo: props.produceWorkOrderNo,
				packCode: ruleForm.value.packCode,
				packName: ruleForm.value.packName,
				batchNo: ruleForm.value.batchNo,
				preBatchNo: props.preBatchNo,
				num: ruleForm.value.num,
				hours: ruleForm.value.hours,
				remark: ruleForm.value.remark,
				// startDate: onLinePersonList.value?.[0]?.onlineDate,
				processCode: props.processCode,
				equipmentCode: props.equipmentCode,
				productionLineCode: props.productionLineCode,
				workPersonAccount: workUser.value.account, // onLinePersonList.value?.map((item) => item?.account).join(','),
				workPersonName: workUser.value.realName, //onLinePersonList.value?.map((item) => item?.name).join(','),
				useList: useList,
				workDeviceParam: {
					deviceTm: ruleForm.value.deviceTm,
					deviceSpeed: ruleForm.value.deviceSpeed,
					deviceDyz: ruleForm.value.deviceDyz,
					deviceWd: ruleForm.value.deviceWd,
					deviceGl: ruleForm.value.deviceGl,
					deviceYl: ruleForm.value.deviceYl,
				},
				// isPrintPanel:props.isPrintPanel,
				// printPanelDate:props.printPanelDate
			});
			ElMessage.success('操作成功');
			closeDialog();
			emit('reflashWorkOrderInfo', { workUser: workUser.value });
		}
	});
};

const onScanAccount = async () => {
	var res = await getPersonByAccount({ account: ruleForm.value.workAccount });
	workUser.value = res.data.result;
	ElMessage.success('扫描成功');
};

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