<template>
	<div class="mescontrol-container">
		<div class="mescontrol-total">
			<div style="height: 30px; padding: 10px 10px 0px 10px; color: #ffffff; display: flex; flex-direction: column; justify-content: space-between">
				<div style="height: 70%; display: flex; justify-content: space-between; align-items: center">
					<div>生产日期：{{ titleform.scheduleTime }}</div>
					<div style="font-size: 25px">MES生产数据采集</div>
					<div>作业人员：{{ workUser.account }}</div>
				</div>
				
			</div>
			<div style="height: calc(100% - 50px); margin: 10px; background: #ffffff">
				<div class="elbutton" style="display: flex; justify-content: space-between; padding: 12px; height: 10%">
					<div style="width: 42%; display: flex; justify-content: space-between">
						<el-button type="primary" size="large" @click="peopleShow">上岗人员</el-button>
						<!-- <el-button type="primary" size="large" @click="equipmentShow">设备点检</el-button> -->
						<el-button type="primary" size="large" @click="productionShow">生产工单</el-button>
						<el-button type="primary" size="large" @click="scanShow" :disabled="processform && processform.isCharge == 0">扫码上料</el-button>
						<el-button type="primary" size="large" @click="mouldShow" :disabled="processform && processform.isRelMold == 0">关联模具</el-button>
					</div>
					<div style="width: 45%; display: flex; justify-content: space-between">
						<el-dropdown size="big" trigger="click">
							<el-button type="primary" size="large" :disabled="processform && processform.isFQI == 0">首检</el-button>

							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item @click="firstShow(1)">按报工送检</el-dropdown-item>
									<el-dropdown-item @click="firstShow(2)">此工单送检</el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
						<el-button size="large" :type="titleform.isFTrue|| 'primary'" icon="ele-Refresh" style="margin-left: -15px;" @click="onRefreshFLQI('f',true)" />

						<el-button type="primary" size="large" @click="workingShow">开工</el-button>
						<el-button type="primary" size="large" @click="reportShow">报工</el-button>
						<el-button type="primary" size="large" @click="jobShow">作业指导</el-button>
						<el-button type="primary" size="large" @click="xjShow" :disabled="processform && processform.isZJ == 0">巡检</el-button>
						
						<el-dropdown size="big" trigger="click">
							<el-button type="primary" size="large" :disabled="processform && processform.isLQI == 0">末检</el-button>
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item @click="endShow(1)">按报工送检</el-dropdown-item>
									<el-dropdown-item @click="endShow(2)">此工单送检</el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
						<el-button size="large" :type="titleform.isLTrue|| 'primary'" icon="ele-Refresh" style="margin-left: -15px;" @click="onRefreshFLQI('l',true)" />
					</div>
				</div>
				<div style="padding: 12px; height: 50%; color: var(--el-color-primary)">
					<el-row style="height: 100%">
						<el-col :span="6" class="elcol">
							<div style="display: flex; height: 10%">
								<span style="font-size: 15px; font-weight: bold">生产工序：</span
								><span style="width: 50%">
									<el-select filterable="" v-model="titleform.processCode" placeholder="请选择工序" clearable disabled>
										<el-option v-for="(item, index) in mesProcessProcessCodeDropdownList" :key="index" :value="item.value" :label="item.label" />
									</el-select>
								</span>
							</div>
							<div style="display: flex; height: 10%">
								<span style="font-size: 15px; font-weight: bold">生产设备：</span>
								<div style="width: 50%">
									<el-select style="width: 100%" filterable="" v-model="titleform.equipmentCode" placeholder="请选择设备" clearable @change="getProductionLineCode">
										<el-option v-for="(item, index) in mesEquipmentDropdownList" :key="index" :value="item.value" :label="`[${item.value}]${item.label}`" />
									</el-select>
								</div>
							</div>
							<div class="processform">
								<el-form :model="processform" label-width="120px">
									<el-form-item label="当前工序：">{{ processform.processName }}[{{ processform.processCode }}]</el-form-item>
									<el-form-item label="产品：">{{ processform.productName }}</el-form-item>
									<el-form-item label="零件：">{{ processform.partName }}[{{ processform.partCode }}]</el-form-item>
									<!-- <el-form-item label="客户：">{{ processform.customerName }}</el-form-item> -->
									<el-form-item label="生产订单：">{{ processform.produceOrderNo }}</el-form-item>
									<el-form-item label="批次号：">{{ processform.batchNo }}</el-form-item>
									<el-form-item label="批次报废数：">{{ processform.producePlanInfo?.num2 || 0 }}</el-form-item>
								</el-form>
							</div>
						</el-col>
						<el-col :span="6" class="elcol">
							<div style="display: flex; height: 10%">
								<span style="font-size: 15px; font-weight: bold">开工时间：</span>
								<div style="width: 50%">
									{{ processform.startWorkDate }}
								</div>
							</div>
							<div style="display: flex; height: 10%">
								<span style="font-size: 15px; font-weight: bold">开工时长：</span>
								<div style="width: 50%">
									{{ processform.startTimeStr }}
								</div>
							</div>
							<div class="processform" style="display: flex; position: relative">
								<div style="width: 53%; height: 100%">
									<el-form :model="processform" label-width="110px">
										<el-form-item label="工单号：">{{ processform.produceWorkOrderNo }}</el-form-item>
										<el-form-item label="工单数量：">{{ processform.planNum || 0 }}</el-form-item>
										<el-form-item label="已完工数量：">{{ processform.finishNum || 0 }}</el-form-item>
										<el-form-item label="未完工数量：">{{ (processform.planNum || 0) - (processform.finishNum || 0) }}</el-form-item>
										<el-form-item label="报工批次数：">{{ processform.workRecordList?.length || 0 }}</el-form-item>
										<el-form-item label="生产状态：">{{
											processform.produceWorkOrderStatus == 0
												? '未开立'
												: processform.produceWorkOrderStatus == 1
													? '已开立'
													: processform.produceWorkOrderStatus == 2
														? '已完成'
														: processform.produceWorkOrderStatus
										}}</el-form-item>
										<el-form-item label="工单报废数：">{{ processform.num2|| 0 }}</el-form-item>
									</el-form>
								</div>
								<div style="width: 50%; height: 50%; position: absolute; right: 0; bottom: 0">
									<instrument :dataArr="(processform.finishNum || 0) / (processform.planNum || 0) || 0"></instrument>
								</div>
							</div>
						</el-col>
						<el-col :span="12" class="elcol">
							<div style="height: 50%">
								<div style="height: 20%; font-size: 15px; font-weight: bold">上料记录</div>
								<div style="height: 80%">
									<el-table :data="materialTableData" height="100%" style="width: 100%" border="">
										<el-table-column type="index" label="序号" width="55" align="center" />
										<el-table-column v-if="processform.isCharge == 0 && processform.chargeType == 1" prop="packCode" label="载具编码" show-overflow-tooltip="" />
										<el-table-column v-if="processform.isCharge == 0 && processform.chargeType == 1" 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="specs" label="规格型号" show-overflow-tooltip="" />
										<el-table-column prop="batchNo" label="批次号" show-overflow-tooltip="" />
										<el-table-column v-if="processform.isCharge == 0" prop="packNum" label="装载数量" show-overflow-tooltip="" />
										<el-table-column v-if="processform.isCharge == 0" prop="packProcessCode" label="来源工序" show-overflow-tooltip="" />
										<el-table-column v-if="processform.isCharge == 0" prop="packProduceWorkOrderNo" label="生产工单" show-overflow-tooltip="" />
									</el-table>
								</div>
							</div>
							<div style="height: 50%">
								<div style="height: 20%; font-size: 15px; font-weight: bold">工装模具</div>
								<div style="height: 80%">
									<el-table :data="moldTableData" height="100%" style="width: 100%" border="">
										<el-table-column type="index" label="序号" width="55" align="center" />
										<el-table-column prop="moldCode" label="模具编号" show-overflow-tooltip="" />
										<el-table-column prop="moldName" label="模具名称" show-overflow-tooltip="" />
									</el-table>
								</div>
							</div>
						</el-col>
					</el-row>
				</div>
				<div style="height: 40%; padding: 12px; color: var(--el-color-primary)">
					<div style="height: 22px; font-size: 15px; font-weight: bold; padding-left: 10px">载具信息</div>
					<el-row style="border: 1px solid #cccccc; padding: 10px; height: calc(100% - 22px)" :gutter="10">
						<el-col :span="12" style="height: 100%" class="packlist">
							<div style="margin-bottom: 10px; height: 25px">
								<el-button type="primary" icon="ele-Plus" @click="packShow(1)">添加载具</el-button>
								<el-button type="primary" icon="ele-Minus" @click="onUnRelPack">删除载具</el-button>
								<el-button type="warning" icon="ele-Plus" @click="packShow(2)">添加消耗载具</el-button>
							</div>
							<el-table ref="packTableRef" :data="packTableData || []" style="width: 100%" border="" @select="handleSelectionChange">
								<el-table-column type="selection" width="30" />
								<el-table-column type="index" label="序号" width="50" align="center" />
								<el-table-column prop="packStatus" label="状态">
									<template #default="scope">
										<el-tag :type="dv('MesPackStatusEnum', scope.row.packStatus)?.tagType"> {{ dv('MesPackStatusEnum', scope.row.packStatus)?.name }}</el-tag>
									</template>
								</el-table-column>
								<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="num" label="实际载数量" show-overflow-tooltip="" />
								<el-table-column label="操作" width="140">
									<template #default="scope">
										<el-button type="warning" link @click="onShowAttaInfo(scope.row)">消耗信息</el-button>
										<el-button type="danger" link @click="onFinishPack(scope.row)">装载完成</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-col>
						<el-col :span="12" style="height: 100%">
							<div style="margin-bottom: 10px; height: 25px">载具报工记录</div>
							<el-table :data="packRecordData || []" style="width: 100%" border="">
								<el-table-column type="selection" width="30" />
								<el-table-column type="index" label="序号" width="50" align="center" />
								<el-table-column prop="packStatus" label="状态" width="90">
									<template #default="scope">
										<el-tag type="success">装载完成</el-tag>
									</template>
								</el-table-column>
								<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="" width="90" />
								<el-table-column prop="num" label="实际装载数量" show-overflow-tooltip="" width="90" />
								<el-table-column prop="finishDate" label="装载完成时间" show-overflow-tooltip="" width="90" />
								<el-table-column prop="processCode" label="生产工序" show-overflow-tooltip="" />
								<el-table-column prop="produceWorkOrderNo" label="生产工单" show-overflow-tooltip="" />
								<!-- <el-table-column prop="fmBatchNo" label="生产订单" show-overflow-tooltip="" /> -->
							</el-table>
						</el-col>
					</el-row>
				</div>
			</div>
		</div>
		<chooseEquipment title=" 选择设备" ref="chooseEquipmentRef" @finish="onChooseFinish"></chooseEquipment>
		<peopleDialog
			ref="peopleDialogRef"
			:title="'人员上工'"
			:productionLineCode="titleform.productionLineCode"
			:produceWorkOrderNo="processform.produceWorkOrderNo"
			@reloadTable="
				() => {
					handleQuery();
					getonlineList();
				}
			"
		/>
		<equipmentDialog ref="equipmentDialogRef" :title="'设备点检'" :equipmentCode="titleform.equipmentCode" :equipmentName="titleform.equipmentName" @reloadTable="handleQuery" />
		<productionDialog ref="productionDialogRef" :title="'生产工单'" @reloadTable="handleQuery" :getProduceWorkOrderNo="getWorkOrderInfo" :processCode="''" />
		<scanDialog ref="scanDialogRef" :title="'扫码上料'" @reloadTable="getMaterial" :produceWorkOrderNo="processform?.produceWorkOrderNo" />
		<scanPackDialog ref="scanPackDialogRef" :title="'其他工序上料'" @reloadTable="getMaterial" :produceWorkOrderNo="processform?.produceWorkOrderNo" />
		<mouldDialog ref="mouldDialogRef" :title="'关联模具'" @reloadTable="getMoldList" :produceWorkOrderNo="processform?.produceWorkOrderNo" />
		<packDialog ref="packDialogRef" :title="'添加载具'" @reloadTable="getPackList" :produceWorkOrderNo="processform?.produceWorkOrderNo" :processform="processform"></packDialog>
		<workingDialog ref="workingDialogRef" :title="'开工'" @reloadTable="handleQuery" :getBatchInfo="getBatchInfo" @startWork="startWorkNosure" />
		<attaInfoDialog ref="attaInfoDialogRef" :title="'消耗信息'"></attaInfoDialog>
		<reportDialog
			ref="reportDialogRef"
			:title="'报工'"
			@reloadTable="handleQuery"
			:produceWorkOrderNo="processform?.produceWorkOrderNo"
			:preBatchNo="batchForm?.workBatchNo"
			:processCode="titleform.processCode"
			:equipmentCode="titleform.equipmentCode"
			:productionLineCode="titleform.productionLineCode"
			@reflashWorkOrderInfo="reflashWorkOrderInfo"
		/>
		<jobDialog ref="jobDialogRef" :title="'作业指导'" @reloadTable="handleQuery" />
		<seftestDialog
			ref="seftestDialogRef"
			:title="'巡检'"
			@reloadTable="handleQuery"
			:produceWorkOrderNo="processform?.produceWorkOrderNo"
			:processCode="titleform.processCode"
			:equipmentCode="titleform.equipmentCode"
			:factoryCode="titleform.factoryCode"
			:productCode="processform.productCode"
		/>
		<firstDialog
			ref="firstDialogRef"
			:title="'首件送检'"
			@reloadTable="handleQuery"
			:produceWorkOrderNo="processform?.produceWorkOrderNo"
			:processCode="titleform.processCode"
			:equipmentCode="titleform.equipmentCode"
			:factoryCode="titleform.factoryCode"
		/>
		<endDialog
			ref="endDialogRef"
			:title="'末件送检'"
			@reloadTable="handleQuery"
			:produceWorkOrderNo="processform?.produceWorkOrderNo"
			:processCode="titleform.processCode"
			:equipmentCode="titleform.equipmentCode"
			:factoryCode="titleform.factoryCode"
		/>
		<xjDialog
			ref="xjDialogRef"
			:title="'巡检任务'"
			@reloadTable="handleQuery"
			:produceWorkOrderNo="processform?.produceWorkOrderNo"
			:processCode="titleform.processCode"
			:equipmentCode="titleform.equipmentCode"
			:factoryCode="titleform.factoryCode"
		/>
	</div>
</template>
<script lang="ts" setup="" name="mescontrol">
import { onUnmounted,onMounted, ref, watchEffect } from 'vue';
import * as echarts from 'echarts';
import 'echarts-wordcloud';
import { Calendar, Search } from '@element-plus/icons-vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { auth } from '/@/utils/authFunction';
import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
import { formatDate } from '/@/utils/formatTime';
import { getDictLabelByVal as dv } from '/@/utils/dict-utils';
import { getMesProcessProcessCodeDropdown } from '/@/api/mes/mesRuleProductCapacity';
import chooseEquipment from '/@/businessComponents/chooseEquipment.vue';
import instrument from './instrument.vue';
import peopleDialog from './peopleDialog.vue';
import equipmentDialog from './equipmentDialog.vue';
import productionDialog from './productionDialog.vue';
import scanDialog from './scanDialog.vue';
import scanPackDialog from './scanPackDialog.vue';
import mouldDialog from './mouldDialog.vue';
import packDialog from './packDialog.vue';
import workingDialog from './workingDialog.vue';
import reportDialog from './reportDialog.vue';
import jobDialog from './jobDialog.vue';
import seftestDialog from './seftestDialog.vue';
import firstDialog from './firstDialog.vue';
import attaInfoDialog from './attaInfoDialog.vue';
import xjDialog from './xjDialog.vue';
import endDialog from './endDialog.vue';
import {
	getOnlineRecord,
	getPreData,
	getWorkOrderMaterial,
	getWorkOrderMold,
	getWorkOrderPack,
	getWorkOrderPackRecord,
	finishPack,
	unRelPack,
	getWorkOrderPage,
	startWork,
	getEquipmentByWorkOrder,
	saveFLInsp,
	validFirstQi,
	validLastQi,
} from '/@/api/mes/mesControlBoard';

const chooseEquipmentRef = ref();
const titleform = ref<any>({});
const processform = ref<any>({});
const batchForm = ref<any>({});
const materialTableData = ref<any>([]);
const moldTableData = ref<any>([]);
const packTableData = ref<any>([]);

onMounted(()=>{
	RefreshFLQiTimer.value = setInterval(() => {
		onRefreshFLQI('f',false);
		onRefreshFLQI('l',false);
	}, 10000);
})
onUnmounted(() => {
	if (timer.value) {
		clearInterval(timer.value);
	}
	if(RefreshFLQiTimer.value){
		clearInterval(RefreshFLQiTimer.value)
	}
});

// 工序不从全部工序拿，从前置数据接口
const mesProcessProcessCodeDropdownList = ref<any>([]);
// const getMesProcessProcessCodeDropdownList = async () => {
// 	let list = await getMesProcessProcessCodeDropdown();
// 	mesProcessProcessCodeDropdownList.value = list.data.result ?? [];
// };
// getMesProcessProcessCodeDropdownList();
const mesEquipmentDropdownList = ref([]);
const getPreDataInfo = async () => {
	let res = (await getPreData()).data?.result;
	mesProcessProcessCodeDropdownList.value = (res.processList || []).map((item) => ({
		...item,
		value: item.processCode,
		label: item.processName,
	}));
	titleform.value.scheduleTime = res.currentDate || new Date();
	titleform.value.factoryCode = res.factoryCode;
	// mesEquipmentDropdownList.value = (res.equipmentList || []).map((item) => ({
	// 	...item,
	// 	value: item.equipmentCode,
	// 	label: item.equipmentName,
	// }));
	// [
	// {value:1,label:1},
	//     {value:2,label:2},
	// ]
};
getPreDataInfo();

// 根据设备获取线体编码
const getProductionLineCode = (value) => {
	console.log(value);
	let current = mesEquipmentDropdownList.value.find((item) => item.value == value);
	titleform.value.equipmentName = current?.equipmentName || '';
	titleform.value.productionLineCode = current?.productionLineCode || '';
	titleform.value.productionLineName = current?.productionLineName || '';
};

const onChooseFinish = (data: any) => {
	titleform.value.teamManageId = data.id;
	titleform.value.teamManageName = `[${data.id}]${data.nickName}`;
};

const handleQuery = () => {};

// 打开人员上岗
const peopleDialogRef = ref();
const peopleShow = () => {
	// if(!processform.value.produceWorkOrderNo) return ElMessage.warning('请选择生产工单后操作');
	// if(!titleform.value.processCode || !titleform.value.equipmentCode) {
	//   return ElMessage.warning('请选择生产工序与生产设备后操作');
	// }
	peopleDialogRef.value.openDialog({});
};
// 打开设备点检
const equipmentDialogRef = ref();
const equipmentShow = () => {
	if (!titleform.value.equipmentCode) return ElMessage.warning('请选择生产设备后操作');
	equipmentDialogRef.value.openDialog({});
};
// 打开设备点检
const productionDialogRef = ref();
const productionShow = () => {
	productionDialogRef.value.openDialog({});
};
// 打开扫码上料
const scanDialogRef = ref();
const scanPackDialogRef = ref();
const scanShow = () => {
	// scanDialogRef.value.openDialog({});
	console.log(processform.value);
	if (!processform.value.produceWorkOrderNo) return ElMessage.warning('请选择生产工单后操作');
	if (processform.value.chargeType == 0) {
		scanDialogRef.value.openDialog({ processform });
	} else if (processform.value.chargeType == 1) {
		scanPackDialogRef.value.openDialog({ processform });
	}
};
// 打开关联模具
const mouldDialogRef = ref();
const mouldShow = () => {
	// mouldDialogRef.value.openDialog({});
	if (!processform.value.produceWorkOrderNo) return ElMessage.warning('请选择生产工单后操作');
	mouldDialogRef.value.openDialog({});
};

const packDialogRef = ref();
const packShow = (sign: number) => {
	var data = {};
	if (sign == 2) {
		var rows = packTableRef.value.getSelectionRows();
		if (rows.length == 0) {
			ElMessage.error('请选择载具');
			return;
		}
		data = rows[0];
	}
	packDialogRef.value.openDialog({ sign: sign, ...data });
};

const packTableRef = ref();
const onUnRelPack = () => {
	var rows = packTableRef.value.getSelectionRows();
	if (rows.length == 0) {
		ElMessage.error('请选择要解绑的载具');
		return;
	}
	var packCodes = rows.map((item: any) => item.packCode);

	ElMessageBox.confirm('确定要解绑此载具?')
		.then(async () => {
			await unRelPack({
				produceWorkOrderNo: processform.value.produceWorkOrderNo,
				PackCodeList: packCodes,
			});
			ElMessage.success('操作成功');
			getPackList();
		})
		.catch(() => {
			// catch error
		});
};

// 打开开工
const workingDialogRef = ref();
const workingShow = async () => {
	// workingDialogRef.value.openDialog({});
	if (!processform.value.produceWorkOrderNo) return ElMessage.warning('请选择生产工单后操作');
	if (processform.value.isScanBoard == 1) {
		workingDialogRef.value.openDialog({});
	} else {
		ElMessageBox.confirm('确认要开工吗?')
			.then(async () => {
				await startWork({
					produceWorkOrderNo: processform.value.produceWorkOrderNo,
					PreBatchNo: '',
					ProcessCode: titleform.value.processCode,
					EquipmentCode: titleform.value.equipmentCode,
					ProductionLineCode: titleform.value.productionLineCode,
					WorkPersonAccount: presenttableData.value
						.map((item) => item?.account)
						.filter((item) => item)
						.join(','),
					WorkPersonName: presenttableData.value
						.map((item) => item?.name)
						.filter((item) => item)
						.join(','),
				});
				ElMessage.success('操作成功');
				reflashWorkOrderInfo({ workUser: JSON.parse(JSON.stringify(workUser.value)) });
			})
			.catch(() => {
				// catch error
			});
	}
};
const startWorkNosure = (res: any) => {
	if (!processform.value.produceWorkOrderNo) return ElMessage.warning('请选择生产工单后操作');
	startWork({
		produceWorkOrderNo: processform.value.produceWorkOrderNo,
		PreBatchNo: res.preBatchNo,
		ProcessCode: titleform.value.processCode,
		EquipmentCode: titleform.value.equipmentCode,
		ProductionLineCode: titleform.value.productionLineCode,
		WorkPersonAccount: presenttableData.value
			.map((item) => item?.account)
			.filter((item) => item)
			.join(','),
		WorkPersonName: presenttableData.value
			.map((item) => item?.name)
			.filter((item) => item)
			.join(','),
	});
	// ElMessage.success('操作成功');
};
// 打开报工
const reportDialogRef = ref();
const reportShow = () => {
	var row = packTableRef.value.getSelectionRows();
	if (row.length == 0) {
		return ElMessage.error('请选择报工载具');
	}
	if (processform.value.isFirstProcess == 1 && processform.value.isAssemble == 0) {
		//上料工序报工
		reportDialogRef.value.openDialog({ packCode: row[0].packCode, packName: row[0].packName, sign: 1, processform: processform.value });
	} else if (processform.value.isAssemble == 1) {
		//装配
		reportDialogRef.value.openDialog({ packCode: row[0].packCode, packName: row[0].packName, sign: 3, processform: processform.value });
	} else {
		//后工序
		reportDialogRef.value.openDialog({ packCode: row[0].packCode, packName: row[0].packName, sign: 2, processform: processform.value });
	}
};
// 打开作业指导
const jobDialogRef = ref();
const jobShow = () => {
	if (!processform.value.produceWorkOrderNo) return ElMessage.warning('请选择生产工单后操作');
	if (!processform.value.craftFiles || processform.value.craftFiles == '[]') return ElMessage.warning('该工单无作业指导');
	jobDialogRef.value.openDialog({ url: JSON.parse(processform.value?.craftFiles).url });
};
// 打开自检
const seftestDialogRef = ref();
const seftestShow = () => {
	if (!processform.value.produceWorkOrderNo) {
		return ElMessage.warning('请选择生产工单后操作');
	}
	seftestDialogRef.value.openDialog({});
};
// 打开首件送检
const firstDialogRef = ref();
const firstShow = async (idx) => {
	if (idx == 1) {
		firstDialogRef.value.openDialog({ inspType: 1 });
	} else {
		if (!processform.value.produceWorkOrderNo) {
			return ElMessage.warning('请选择生产工单后操作');
		}
		await saveFLInsp({
			ProduceWorkOrderNo: processform.value.produceWorkOrderNo,
			equipmentCode: titleform.value.equipmentCode,
			inspType: 1,
			isFirstInsp: true,
		})
			.then((res) => {
				ElMessage.success('提交成功');
			})
			.catch(() => {});
	}
};
// 打开末件送检
const endDialogRef = ref();
const endShow = async (idx) => {
	
	if (idx == 1) {
		endDialogRef.value.openDialog({ inspType: 2 });
	} else {
		if (!processform.value.produceWorkOrderNo) {
			return ElMessage.warning('请选择生产工单后操作');
		}
		await saveFLInsp({
			ProduceWorkOrderNo: processform.value.produceWorkOrderNo,
			equipmentCode: titleform.value.equipmentCode,
			inspType: 2,
			isFirstInsp: false,
		})
			.then((res) => {
				ElMessage.success('提交成功');
			})
			.catch(() => {});
	}
};
const xjDialogRef = ref();
const xjShow = () => {
	xjDialogRef.value.openDialog({ inspType: 5 });
};

// 选择工单数据后赋值
const getWorkOrderInfo = async (value: any) => {
	// (value)=> produceWorkOrderNo=value
	console.log(value);
	processform.value = {
		...value,
	};
	processform.value.startTimeStr = computerStartTime(processform.value?.startWorkDate);
	showTime();
	titleform.value = {};
	titleform.value.processCode = value.processCode;
	titleform.value.equipmentCode = '';
	var res = await getEquipmentByWorkOrder({ workOrderNo: value.produceWorkOrderNo });
	mesEquipmentDropdownList.value = res.data.result;
	getPackList();
	getPackRecordList();
};
const workUser = ref({});
// 重新获取最新的工单信息
const reflashWorkOrderInfo = async (e: any) => {
	workUser.value = e.workUser;

	if (!processform.value?.produceWorkOrderNo) return;
	var res = await getWorkOrderPage({ produceWorkOrderNo: processform.value?.produceWorkOrderNo });
	processform.value = (res.data.result?.items ?? [])?.[0] || {};
	processform.value.startTimeStr = computerStartTime(processform.value?.startWorkDate);
	showTime();

	getPackList();
	getPackRecordList();
};
const timer = ref();
const showTime = () => {
	if (timer.value) {
		clearInterval(timer.value);
	}
	if (processform.value?.startWorkDate && processform.value?.produceWorkOrderStatus != 2) {
		timer.value = setInterval(() => {
			processform.value.startTimeStr = computerStartTime(processform.value?.startWorkDate);
		}, 1000);
	}
};

const computerStartTime = (date1: any) => {
	if (!date1) return '';
	var date2 = new Date(); //结束时间
	var date3 = date2.getTime() - new Date(date1).getTime(); //时间差的毫秒数

	//计算出相差天数
	var days = Math.floor(date3 / (24 * 3600 * 1000));

	//计算出小时数

	var leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000));
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000));
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);

	return days + '天 ' + hours + '小时 ' + minutes + ' 分钟' + seconds + ' 秒';
};

const handleSelectionChange = (selection: any, row: any) => {
	if (selection.length > 1) {
		let del_row = selection.shift();
		packTableRef.value.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
	}
};

// 获取批次信息
const getBatchInfo = (value) => {
	batchForm.value = value;
};

// 获取模具列表信息
const getMoldList = async () => {
	if (!processform.value.produceWorkOrderNo) return;
	let res =
		(
			await getWorkOrderMold({
				workOrderNo: processform.value.produceWorkOrderNo,
			})
		)?.data?.result || [];
	moldTableData.value = res;
};

// 获取载具列表信息
const getPackList = async () => {
	if (!processform.value.produceWorkOrderNo) return;
	let res =
		(
			await getWorkOrderPack({
				workOrderNo: processform.value.produceWorkOrderNo,
				isFinish: false,
			})
		)?.data?.result || [];
	packTableData.value = res;
};
const packRecordData = ref<any>([]);
// 获取载具列表信息
const getPackRecordList = async () => {
	if (!processform.value.produceWorkOrderNo) return;
	let res =
		(
			await getWorkOrderPackRecord({
				workOrderNo: processform.value.produceWorkOrderNo,
			})
		)?.data?.result || [];
	packRecordData.value = res;
};
//装载完成
const onFinishPack = async (item: any) => {
	if (item.num <= 0) {
		return ElMessage.warning('当前装载数量为0，不能装载完成');
	}
	ElMessageBox.confirm('确定装载完成?')
		.then(async () => {
			await finishPack({ ProduceWorkOrderNo: processform.value.produceWorkOrderNo, PackCode: item.packCode });
			getPackList();
			getPackRecordList();
			ElMessage.success('操作成功');
		})
		.catch(() => {
			// catch error
		});
};
const attaInfoDialogRef = ref();
const onShowAttaInfo = async (item: any) => {
	attaInfoDialogRef.value.openDialog({ produceWorkOrderNo: item.produceWorkOrderNo, packCode: item.packCode });
};
const getMaterial = async () => {
	if (!processform.value.produceWorkOrderNo) return;
	let res =
		(
			await getWorkOrderMaterial({
				workOrderNo: processform.value.produceWorkOrderNo,
			})
		)?.data?.result || [];
	materialTableData.value = res;
};

// 获取当前在岗记录
const presenttableData = ref([]);
const getonlineList = async () => {
	let res =
		(
			await getOnlineRecord({
				workOrderNo: processform.value.produceWorkOrderNo,
			})
		)?.data?.result || [];
	presenttableData.value = res;
};

const RefreshFLQiTimer = ref('');
const onRefreshFLQI = async(type,showTip)=>{
	
	if(!processform.value.produceWorkOrderNo){
		if(showTip) return ElMessage.warning('请先选择工单');
		else return;
	}
	if(!titleform.value.equipmentCode){
		if(showTip) return ElMessage.warning('请先选择设备');
		else return;
	}
	var res = null;
	if(type=='f'){
		res = await validFirstQi({workOrderNo:processform.value.produceWorkOrderNo,equipmentCode:titleform.value.equipmentCode})
	}else if(type=='l'){
		res = await validLastQi({workOrderNo:processform.value.produceWorkOrderNo,equipmentCode:titleform.value.equipmentCode})
	}
	if(res.data.result==0){
		if(type=='f') titleform.value.isFTrue = 'primary';
		if(type=='l') titleform.value.isLTrue = 'primary';
		if(showTip) ElMessage.warning('无需检验');
	}
	if(res.data.result==1){
		if(type=='f') titleform.value.isFTrue = 'success';
		if(type=='l') titleform.value.isLTrue = 'success';
		if(showTip) ElMessage.success('检验合格');
	}
	if(res.data.result==2){
		if(type=='f') titleform.value.isFTrue = 'danger';
		if(type=='l') titleform.value.isLTrue = 'danger';
		if(showTip) ElMessage.error('不合格');
	}
	if(res.data.result==3){
		if(type=='f') titleform.value.isFTrue = 'warning';
		if(type=='l') titleform.value.isLTrue = 'warning';
		if(showTip) ElMessage.error('待检验');
	}
	if(res.data.result==4){
		if(type=='f') titleform.value.isFTrue = 'info';
		if(type=='l') titleform.value.isLTrue = 'info';
		if(showTip) ElMessage.error('未发起');
	}
}

// 工单号变化自动更新相关数据
watchEffect(() => {
	if (processform.value.produceWorkOrderNo) {
		getMoldList();
		getMaterial();
		getonlineList();
	}
});
</script>
<style scoped>
:deep(.el-ipnut),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
:deep(.title-total .el-input__wrapper) {
	background: none;
}
:deep(.title-total .el-form-item--small .el-form-item__label) {
	font-size: 15px;
	font-weight: bold;
	color: #ffffff;
}
:deep(.title-total .el-input--small .el-input__inner) {
	font-size: 15px;
	color: #ffffff;
}
:deep(.el-input__prefix-inner) {
	font-size: 15px;
	color: #ffffff;
}
:deep(.title-total .el-button--small) {
	font-size: 15px;
	font-weight: bold;
	background: var(--el-color-primary);
}
:deep(.title-total .el-input.is-disabled .el-input__wrapper) {
	background: none;
}
:deep(.title-total .el-input.is-disabled .el-input__inner) {
	font-size: 15px;
	-webkit-text-fill-color: #ffffff;
	color: #ffffff;
}
:deep(.elbutton .el-button > span) {
	font-size: 16px;
	font-weight: bold;
}
:deep(.title-total .el-input__wrapper.is-focus) {
	box-shadow: 0 0 0 1px #cccdcd;
}
:deep(.processform .el-form-item--small .el-form-item__label) {
	font-size: 15px;
	font-weight: bold;
	color: var(--el-color-primary);
}
:deep(.processform .el-form-item--small .el-form-item__content) {
	color: var(--el-color-primary);
	font-size: 15px;
}
:deep(.el-table__header-wrapper .el-table th.el-table__cell) {
	background-color: var(--el-color-primary);
}
.mescontrol-total {
	width: 100%;
	height: 100%;
	background: var(--el-color-primary);
}
.elcol {
	padding: 0px 10px;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}
.processform {
	border: 1px solid #cfd1d1;
	padding: 10px 0px;
	height: 89%;
}

:deep(.packlist .el-table__header-wrapper .el-checkbox) {
	display: none;
}
</style>
