<template>
	<view style="background-color: #fff">
		<uni-forms ref="form" :modelValue="formData" :rules="rules" label-align="right">
			<uni-row>
				<uni-col :span="24">
					<uni-forms-item label="作业编码" :labelWidth="90" name="pwoJobCode" required>
						<uni-easyinput suffixIcon="scan" @iconClick="scanJob" type="text" v-model="formData.pwoJobCode"
							@confirm="getJobInfo" focus />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="18">
					<uni-forms-item label="员工编码" :labelWidth="90" name="createByCode" required>
						<uni-easyinput type="text" @confirm="getEmpInfo" v-model="formData.createByCode" />
<!-- 						<uni-easyinput type="text" suffixIcon="scan" @iconClick="scanEmp" @confirm="getEmpInfo"
							v-model="formData.createByCode" /> -->
					</uni-forms-item>
				</uni-col>
				<uni-col :span="6">
					<uni-easyinput disabled type="text" v-model="formData.createByName || '/'" />
				</uni-col>
				<uni-col :span="18">
					<uni-forms-item label="设备编码" :labelWidth="90" name="machineId" required>
						<uni-easyinput type="text" v-model="formData.machineId" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="6">
					<u-button style="height: 37px;" @click="handleBindEqp" text="绑定设备"
						:disabled="!formData.pwoJobCode || !formData.machineId" />
				</uni-col>
				<uni-col :span="24">
					<u-divider />
					<uni-forms-item label="工单编码" :labelWidth="90" name="pwoCode">
						<uni-easyinput disabled type="text" v-model="formData.pwoCode" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="产品编码" :labelWidth="90" name="ptNoTar">
						<uni-easyinput disabled type="text" v-model="formData.ptNoTar" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="产品名称" :labelWidth="90" name="ptTitleTar">
						<uni-easyinput disabled type="text" v-model="formData.ptTitleTar" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="批号" :labelWidth="90" name="batchNo">
						<uni-easyinput disabled type="text" v-model="formData.batchNo" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="制程编码" :labelWidth="90" name="opCode">
						<uni-easyinput disabled type="text" v-model="formData.opCode" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="制程名称" :labelWidth="90" name="opTitle">
						<uni-easyinput disabled type="text" v-model="formData.opTitle" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="开工时间" :labelWidth="90">
						<view class="example-body">
							<uni-datetime-picker type="datetime" v-model="formData.startTime" :disabled="!checkPermi(['mes:jobStartRecord:edit'])" />
						</view>
					</uni-forms-item>
				</uni-col>
			</uni-row>
		</uni-forms>
		<u-button type="primary" @click="submit">开工</u-button>
	</view>
</template>

<script>
import {
	addStart,
	listPwoJob,
	updatePwoJob,
	getEquipment,
	listEquipment
} from '@/api/mes/jobReport.js';
import {
	listEmpEqpHistory,
	listEmployee,
	listConversion
} from '@/api/mes/jobIn.js';
import { getConfigKey } from '@/api/system/config.js';
import { checkPermi	} from "@/utils/permission";

export default {
	data() {
		return {
			timer: null,
			formData: {
				pwoJobCode: null,
				pwoJobId: null,
				pwoCode: null,
				ptNoTar: null,
				ptTitleTar: null,
				machineId: null,
				batchNo: null,
				createByName: null,
				createByCode: null,
				createById: null,
				startTime: null,
			},
			rules: {
				pwoJobCode: {
					rules: [{
						required: true,
						errorMessage: '请输入作业编码!'
					}]
				},
				machineId: {
					rules: [{
						required: true,
						errorMessage: '请输入设备编码!'
					}]
				},
				createByCode: {
					rules: [{
						required: true,
						errorMessage: '请输入生产员工编码!'
					}]
				},
				startTime: {
					rules: [{
						required: true,
						errorMessage: '请输入开工时间!'
					}]
				}
			}
		};
	},
	created() {
		this.timer = setInterval(() => {
			this.renderStartTime();
		}, 1000);
	},
	methods: {
		checkPermi,
		renderStartTime() {
			// 获取当前时间
			var currentDate = new Date();
			// 格式化为字符串（YYYY-MM-DD HH:mm:ss）
			var year = currentDate.getFullYear();
			var month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
			var day = ('0' + currentDate.getDate()).slice(-2);
			var hours = ('0' + currentDate.getHours()).slice(-2);
			var minutes = ('0' + currentDate.getMinutes()).slice(-2);
			var seconds = ('0' + currentDate.getSeconds()).slice(-2);
			var formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
			// 将当前时间赋值给 formData.startTime
			this.formData.startTime = formattedDate;
		},
		async handleRenderEmp() {
			if(!this.formData.machineId) return;
			const { rows, total } = await listEmpEqpHistory({ equipmentCode: this.formData.machineId });
			const emp = rows.filter(item => !item.endTime)?.[0];
			if(!emp || !total > 0) return this.$modal.msg('该设备下没有绑定人员');
			this.formData.createByCode = rows[0].empCode || '';
			this.formData.createByName = rows[0].empName || '';
			this.formData.createById = rows[0].empId || '';
		},
		// 绑定设备
		async handleBindEqp() {
			let eqpId = '';
			this.$modal.loading('绑定中');
			try {
				const { rows, total } = await listEquipment({ equipmentCode: this.formData.machineId });
				if(total == 1) {
					eqpId = rows[0].id;
				} else {
					this.$modal.msg('未检索到该设备编码相关的信息！');
					return;
				}
				
				await updatePwoJob({
				  id: this.formData.pwoJobId,
				  eqpId
				});
				this.$modal.msgSuccess("绑定成功！");
				this.handleRenderEmp();
			} catch (err) {
				console.log(err);
				this.$modal.msgError('绑定失败！');
			} finally {
				this.$modal.closeLoading();
			}
		},
		submit() {
			this.$refs.form.validate().then(() => {
				this.$modal.loading('提交中');
				addStart({
					jobCode: this.formData.pwoJobCode,
					equipmentCode: this.formData.machineId,
					employeeCode: this.formData.createByCode,
					startTime: this.formData.startTime
				}).then(() => {
					this.$modal.closeLoading();
					this.$modal.msgSuccess('操作成功！');
					setTimeout(() => {
						this.$tab.switchTab('/pages/work/index');
					}, 500);
				});
			});
		},
		getJobInfo() {
			if (!this.formData.pwoJobCode) return;
			listPwoJob({
				code: this.formData.pwoJobCode
			}).then(async (res) => {
				if (!res.total > 0) return this.$modal.msg('未检索到该作业编码相关的信息！');
				const job = res.rows[0];
				this.formData.pwoCode = job.pwoCode;
				this.formData.pwoJobId = job.id;
				this.formData.ptNoTar = job.ptNoTar;
				this.formData.ptTitleTar = job.ptTitleTar;
				this.formData.opCode = job.opCode;
				this.formData.opTitle = job.opTitle;
				this.formData.batchNo = job.batchNo;

				if (job.eqpId) {
					await getEquipment(job.eqpId).then((res) => {
						this.formData.machineId = res.data.equipmentCode;
					});
					// 查找该设备下上机人员
					await this.handleRenderEmp();
				}
				if(this.formData.createById) return;
				// 若没有人员，则调取最后一条转入记录的操作人
				listConversion({
					powJobCode: this.formData.pwoJobCode
				}).then(async (res) => {
					if(!res.total > 0) return;
					
					this.formData.createByName = res.rows[0].operateBy;
					if(!this.formData.createByName) return;
					listEmployee({
						name: this.formData.createByName
					}).then(async (res) => {
						this.formData.createByCode = res.rows[0].empCode;
						this.formData.createById = res.rows[0].id;
					});
				});
			});
		},
		getEmpInfo() {
			if (!this.formData.createByCode) {
				this.formData.createByName = null;
				this.formData.createById = null;
				return;
			}
			listEmployee({
				empCode: this.formData.createByCode
			}).then(res => {
				if (res.rows.length == 0) {
					this.$modal.msg('未查询到该人员信息！');
					return;
				}
				this.formData.createByName = res.rows[0].name;
				this.formData.createById = res.rows[0].id;
			});
		},
		scanJob() {
			const _this = this;
			uni.scanCode({
				scanType: ['barCode', 'qrCode'],
				success: function(res) {
					_this.formData.pwoJobCode = res.result;
					_this.scanBarCode(_this.formData.pwoJobCode);
				}
			});
		},
		scanEmp() {
			const _this = this;
			uni.scanCode({
				scanType: ['barCode', 'qrCode'],
				success: function(res) {
					_this.formData.createByCode = res.result;
					_this.getEmpInfo();
				}
			});
		},
	},
	beforeDestroy() {
		clearInterval(this.timer);
	},
};
</script>