<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>
						<!-- <utils-input prefixIcon="scan" @iconClick="scanBar" type="text" v-model="formData.pwoJobCode"
							@confirm="scanBarCode" @input="handleInput" :key="input.boolean" :focus='true'
							@focus="focus" @click="focus" /> -->
						<uni-easyinput suffixIcon="scan" @iconClick="scanBar" type="text" v-model="formData.pwoJobCode"
							@confirm="scanBarCode" @input="handleInput" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<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="18">
					<uni-forms-item label="设备编号" :labelWidth="90" name="machineId">
						<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">
					<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-forms-item label="用时(s)" :labelWidth="90" name="timeTake">
						<uni-easyinput type="number" v-model="formData.timeTake" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="生产员工编码" :labelWidth="90" name="createByCode" required>
						<uni-easyinput type="text" suffixIcon="scan" @iconClick="scanBar1" @confirm="scanBarCreateBy"
							v-model="formData.createByCode" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="生产员工" :labelWidth="90" name="createByName">
						<uni-easyinput disabled type="text" v-model="formData.createByName" />
					</uni-forms-item>
					<u-divider :text="'可报工数量:' + reportableNum"></u-divider>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="合格数量" :labelWidth="90" name="pass">
						<u-number-box button-size="36" inputWidth="auto"
							v-model="formData.mesJobReportOnceRequestDTO.pass.reportNumber" min="0"></u-number-box>
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="不良数量" :labelWidth="90" name="defect">
						<u-number-box button-size="36" inputWidth="auto"
							v-model="formData.mesJobReportOnceRequestDTO.defect.reportNumber" min="0"></u-number-box>
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="不良原因" :labelWidth="90" name="defectReason">
						<uni-data-select v-model="formData.mesJobReportOnceRequestDTO['defect'].reason"
							:localdata="defectReasonOptions"></uni-data-select>
					</uni-forms-item>
				</uni-col>

				<uni-col :span="24">
					<uni-forms-item label="报废数量" :labelWidth="90" name="scrap">
						<u-number-box button-size="36" inputWidth="auto"
							v-model="formData.mesJobReportOnceRequestDTO.scrap.reportNumber" min="0"></u-number-box>
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="报废原因" :labelWidth="90" name="scrapReason">
						<uni-data-select v-model="formData.mesJobReportOnceRequestDTO['scrap'].reason"
							:localdata="scrapReasonOptions"></uni-data-select>
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="损耗数量" :labelWidth="90" name="loss">
						<u-number-box button-size="36" inputWidth="auto"
							v-model="formData.mesJobReportOnceRequestDTO.loss.reportNumber" min="0"></u-number-box>
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="损耗原因" :labelWidth="90" name="lossReason">
						<uni-data-select v-model="formData.mesJobReportOnceRequestDTO['loss'].reason"
							:localdata="lossReasonOptions"></uni-data-select>
					</uni-forms-item>
				</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" />
						</view>
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="完工时间" :labelWidth="90" name="endTime" required>
						<view class="example-body">
							<uni-datetime-picker type="datetime" v-model="formData.endTime" />
						</view>
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="备注" :labelWidth="90" name="remark" :required="requireRemark">
						<uni-easyinput autoHeight type="textarea" v-model="formData.remark"></uni-easyinput>
					</uni-forms-item>
				</uni-col>
			</uni-row>
		</uni-forms>
		<u-button type="primary" @click="submit">提交</u-button>
		<!-- <u-button type="primary" @click="end">关闭</u-button> -->
	</view>
</template>

<script>
import {
	listPwoJob,
	addReport,
	updatePwoJob,
	getEquipment,
	addReportOnce,
	listEquipment
} from '@/api/mes/jobReport.js';
import {
	listEmpEqpHistory,
	listEmployee,
	listConversion
} from '@/api/mes/jobIn.js';
import { getDicts } from '@/api/system/dict/dictData.js';
// const serialPort = uni.requireNativePlugin('Fvv-UniSerialPort')
import utilsInput from '@/utils/uniapp/utilsInput.vue';
import { getConfigKey } from '@/api/system/config.js';
import { listAllBadCauseByOpCode } from '@/api/basic/badCause';

export default {
	components: {
		utilsInput
	},
	onLoad: async function(option) {
		if (option.code) {
			this.isSearchRoute = true;
			this.formData.pwoJobCode = option.code;
			this.scanBarCode();
		}
		// 获取当前时间
		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.endTime
		this.formData.endTime = formattedDate;
		this.formData.way = '人工报工';
		// this.formData.type = '报废品';
		// this.formData.createByName = this.$store.state.user.name;

		await getConfigKey('basic:operation:badCause').then((res) => {
			if (!res.msg) return;
			this.reasonFrom = +res.msg;
			this.formData.reasonFrom = +res.msg || 0;
		});
		await getConfigKey('mes.job.report.requireRemark').then(res => {
			if (res.msg == null) return;
			this.requireRemark = Boolean(+res.msg);
		});
		this.getOptions();
	},
	data() {
		return {
			input: {
				boolean: 0,
				inputValue: ''
			},
			//判断是否从工单状态页面查询过来
			isSearchRoute: false,
			lossReasonOptions: [],
			scrapReasonOptions: [],
			defectReasonOptions: [],
			formData: {
				pwoJobCode: null,
				pwoJobId: null,
				pwoCode: null,
				ptNoTar: null,
				ptTitleTar: null,
				machineId: null,
				batchNo: null,
				createByName: null,
				createByCode: null,
				createById: null,
				remark: null,
				mesJobReportOnceRequestDTO: {
					pass: {
						reportNumber: 0,
						reason: null
					},
					defect: {
						reportNumber: 0,
						reason: null
					},
					scrap: {
						reportNumber: 0,
						reason: null
					},
					loss: {
						reportNumber: 0,
						reason: null
					}
				},
				startTime: null,
				endTime: null
			},
			reasonFrom: null,
			reportableNum: 0,
			requireRemark: false,
			rules: {
				pwoJobCode: {
					rules: [{
						required: true,
						errorMessage: '请输入作业编码!'
					}]
				},
				createByCode: {
					rules: [{
						required: true,
						errorMessage: '请输入生产员工编码!'
					}]
				},
				endTime: {
					rules: [{
						required: true,
						errorMessage: '请输入完工时间!'
					}]
				}
			}
		};
	},
	created: function(option) {
		// const self = this
		// serialPort.getAllDeviceList(res => {
		// 	console.log('//设备列表', res)
		// })
		// serialPort.getAllDevicePath(res => {
		// 		console.log('//路径列表', res)
		// 	}),
		// 	setTimeout(() => {
		// 		serialPort.setPath('/dev/ttyUSB0')
		// 		serialPort.setBaudRate(9600)
		// 		serialPort.open(res => {
		// 			if (!res.status) {
		// 				uni.showToast({
		// 					title: res.msg,
		// 					duration: 2000,
		// 					icon: "none"
		// 				});
		// 				return
		// 			}
		// 			serialPort.onMessage(rec => {
		// 				this.onMessage(rec);
		// 			}, send => {
		// 				console.log(send)
		// 			})
		// 		})
		// 	}, 10000)
	},
	methods: {
		test() {
			serialPort.sendHex('A00102A3');
		},
		end() {
			serialPort.sendHex('A00100A1');
		},
		getOptions() {
			this.defectReasonOptions = [];
			this.scrapReasonOptions = [];
			this.lossReasonOptions = [];
			if (this.formData.opCode && this.reasonFrom === 1) {
				listAllBadCauseByOpCode(this.formData.opCode).then((res) => {
					res.rows.forEach((item) => {
						switch (item.causeType) {
							case '0':
								this.defectReasonOptions.push({
									text: item.name,
									value: item.id,
									disable: false
								});
								break;
							case '1':
								this.scrapReasonOptions.push({
									text: item.name,
									value: item.id,
									disable: false
								});
								break;
							case '2':
								this.lossReasonOptions.push({
									text: item.name,
									value: item.id,
									disable: false
								});
								break;
						}
					});
				});
			} else {
				getDicts('mes_job_report_defect').then((res) => {
					this.defectReasonOptions = res.data.map((dict) => {
						return {
							text: dict.dictLabel,
							value: dict.dictValue,
							diasble: false
						};
					});
				});
				getDicts('mes_job_report_scrap').then((res) => {
					this.scrapReasonOptions = res.data.map((dict) => {
						return {
							text: dict.dictLabel,
							value: dict.dictValue,
							diasble: false
						};
					});
				});
				getDicts('mes_job_report_loss').then((res) => {
					this.lossReasonOptions = res.data.map((dict) => {
						return {
							text: dict.dictLabel,
							value: dict.dictValue,
							diasble: false
						};
					});
				});
			}
		},
		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((res) => {
				if(this.requireRemark && !this.formData.remark) {
					this.$modal.msg('请输入备注！');
					return;
				}
				this.formData.mesJobReportOnceRequestDTO.pass.reportNumber = Number(this.formData.mesJobReportOnceRequestDTO
				.pass.reportNumber);
				this.formData.mesJobReportOnceRequestDTO.defect.reportNumber = Number(this.formData
				.mesJobReportOnceRequestDTO.defect.reportNumber);
				this.formData.mesJobReportOnceRequestDTO.scrap.reportNumber = Number(this.formData
				.mesJobReportOnceRequestDTO.scrap.reportNumber);
				this.$modal.loading('提交中');
				addReportOnce(this.formData).then((res) => {
					this.$modal.closeLoading();
					this.$modal.msgSuccess('报工成功！');
					if ((this.isSearchRoute = true)) {
						setTimeout(() => {
							this.$tab.navigateBack();
						}, 500);
					} else {
						setTimeout(() => {
							this.$tab.switchTab('/pages/work/index');
						}, 500);
					}
				});
			});
		},
		scanBarCode() {
			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;
				this.reportableNum = job.targetNum - job.finishQty;

				this.getOptions();

				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;
					});
				});
			});
		},
		scanBarCreateBy() {
			if (this.formData.createByCode) {
				let obj = {
					empCode: this.formData.createByCode
				};
				listEmployee(obj).then(async (res) => {
					if (res.rows.length != 0) {
						this.formData.createByName = res.rows[0].name;
						this.formData.createById = res.rows[0].id;
					} else {
						this.$modal.msg('未查询到该人员信息！');
					}
				});
			}
		},
		scanBar() {
			const _this = this;
			uni.scanCode({
				scanType: ['barCode', 'qrCode'],
				success: function(res) {
					_this.formData.pwoJobCode = res.result;
					_this.scanBarCode(_this.formData.pwoJobCode);
				}
			});
		},
		scanBar1() {
			const _this = this;
			uni.scanCode({
				scanType: ['barCode', 'qrCode'],
				success: function(res) {
					_this.formData.createByCode = res.result;
					_this.scanBarCreateBy();
				}
			});
		},

		/**
		 * 隐藏软键盘
		 */
		focus() {
			uni.hideKeyboard();
		},
		/**
		 * 不让手动输入
		 * @param {Object} value
		 */
		handleInput(value) {
			const { inputValue } = this.input;
			if (value.length - inputValue.length == 1 || inputValue.length - value.length == 1) {
				this.$modal.msg('请扫描');
				this.formData.pwoJobCode = null;
				this.input.inputValue = value;
				this.input.boolean = this.input.boolean == 0 ? 10 : 0;
				return;
			}
			this.input.inputValue = value;
		}
	}
};
</script>