<template>
	<view style="background-color: #fff;">
		<uni-forms ref="form" :modelValue="formData" :rules="rules">
			<uni-row>
				<uni-col :span="24">
					<uni-forms-item label="班产任务编码" :label-width='120' name="taskCode">
						<uni-easyinput suffixIcon="scan" @iconClick="scanTaskCode" type="text" v-model="formData.taskCode"
							@blur="scanBarTaskCode" :key="input.boolean" :focus='true' />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="工单编码" :labelWidth='120' name="pwoCode">
						<uni-easyinput type="text" v-model="formData.pwoCode" disabled />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="班产作业编码" :labelWidth='120' name="shiftJobCode">
						<uni-data-select :localdata="formData.shiftJobs" v-model="formData.shiftJobCode"
							@change="getShiftJobInfo"></uni-data-select>
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="工单作业编码" :labelWidth='120' name="pwoJobCode">
						<uni-easyinput v-model="formData.pwoJobCode" disabled />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="产品编码" :labelWidth='120' 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='120' name="ptTitleTar">
						<uni-easyinput disabled type="text" v-model="formData.ptTitleTar" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="12">
					<uni-forms-item label="规格" :labelWidth='50' name="specification1">
						<uni-easyinput disabled type="text" v-model="formData.specification1" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="12">
					<uni-forms-item label="材质" :labelWidth='50' name="texture">
						<uni-easyinput disabled type="text" v-model="formData.texture" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="设备编号" :labelWidth='120' name="machineId">
						<uni-easyinput disabled type="text" v-model="formData.machineId" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="批号" :labelWidth='120' 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='120' 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='120' name="opTitle">
						<uni-easyinput disabled type="text" v-model="formData.opTitle" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="用时(h)" :labelWidth='120' name="timeTake">
						<uni-easyinput type="number" v-model="formData.timeTake" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="生产员工编码" :labelWidth='120' name="createByCode">
						<uni-easyinput type="text" suffixIcon="scan" @iconClick="scanBar1" @blur="scanBarCreateBy"
							v-model="formData.createByCode" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="生产员工" :labelWidth='120' 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='100' name="pass">
						<u-number-box button-size="36" inputWidth="120"
							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='100' name="defect">
						<u-number-box button-size="36" inputWidth="120"
							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='100' 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='100' name="scrap">
						<u-number-box button-size="36" inputWidth="120"
							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='100' 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='100' name="loss">
						<u-number-box button-size="36" inputWidth="120"
							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='100' 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='100'>
						<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='100' name="endTime">
						<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='100' name="remark">
						<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,
	addReportOnce
} from "@/api/mes/jobReport.js";
import {
	getEquipment
} from "@/api/mes/jobIn.js";
import {
	listPwoJobLike
} from "@/api/mes/pwoIn.js";
import {
	listShiftTask
} from "@/api/mes/shiftTask.js";
import {
	listShiftJobWithAssociatedData,
	getShiftJobByShiftJobCode
} from "@/api/mes/shiftJob.js";
import {
	listMaterial
} from "@/api/mes/material.js";
import {
	listEmpEqpHistory,
	listEmployee,
	listConversion
} from "@/api/mes/jobIn.js";
import {
	getDicts
} from "@/api/system/dict/dictData.js";
import {
	login
} from "../../../api/login";
// const serialPort = uni.requireNativePlugin('Fvv-UniSerialPort')
export default {
	data() {
		return {
			input: {
				boolean: 0,
				inputValue: '',
			},
			//判断是否从工单状态页面查询过来
			isSearchRoute: false,
			lossReasonOptions: [],
			scrapReasonOptions: [],
			defectReasonOptions: [],
			formData: {
				taskCode: null,
				shiftJobCode: null,
				pwoJobCode: null,
				shiftJobs: [],
				pwoCode: null,
				ptNoTar: null,
				ptTitleTar: null,
				eqpId: 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,
				specification1: null,
				jobType: 1,
				texture: null,
				opCode: null,
				opTitle: null
			},
			reportableNum: 0,
			rules: {
				taskCode: {
					rules: [{
						required: true,
						errorMessage: '请输入班产任务编码!'
					}]
				},
				pwoCode: {
					rules: [{
						required: true,
						errorMessage: '请输入工单编码!'
					}]
				},
				shiftJobCode: {
					rules: [{
						required: true,
						errorMessage: '请选择班产作业编码!'
					}]
				},
				createByCode: {
					rules: [{
						required: true,
						errorMessage: '请输入生产员工编码!'
					}]
				},
				endTime: {
					rules: [{
						required: true,
						errorMessage: '请输入完工时间!'
					}]
				}
			}
		}
	},
	methods: {
		getOptions() {
			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
					}
				});
			})
		},
		submit() {
			if (this.sumReportNum() <= 0 || this.sumReportNum() > this.reportableNum) {
				this.$modal.showToast("请重新检查报工数量")
				return
			}
			this.$refs.form.validate().then(res => {
				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);
					}
				})
			})
		},
		sumReportNum() {
			const sum = ['pass', 'defect', 'scrap', 'loss'].reduce((total, key) => {
				const value = Number(this.formData.mesJobReportOnceRequestDTO[key].reportNumber)
				this.formData.mesJobReportOnceRequestDTO[key].reportNumber = value
				return total + value
			}, 0)

			return sum
		},
		scanBarPwoCode() {
			this.formData.shiftJobs = []
			if (this.formData.pwoCode) {
				listShiftJobWithAssociatedData({
					pwoCode: this.formData.pwoCode
				}).then((res) => {
					if (res.rows.length > 0) {
						this.$set(this.formData, "shiftJobs", res.rows.map(item => ({
							text: item.shiftJobCode + ":" + item.opTitle,
							value: item.shiftJobCode,
							disabled: false
						})))
						console.log(this.formData.shiftJobs)
					} else {
						this.$modal.showToast("未查询到该工单编码")
					}
				})
			}
		},
		clearJobInfo() {
			this.reportableNum = 0
			const resetFields = [
				"ptNoTar", "ptTitleTar", "eqpId", "batchNo",
				"createByName", "createByCode", "createById", "remark", "startTime",
				"texture", "specification1", "machineId", "pwoJobCode",
				"opCode", "opTitle"
			]
			// 重置表单信息
			resetFields.forEach(field => {
				this.$set(this.formData, field, null)
			})
			// 重置报工数量
			Object.keys(this.formData.mesJobReportOnceRequestDTO).forEach(key => {
				const item = this.formData.mesJobReportOnceRequestDTO[key];
				this.$set(item, 'reportNumber', 0);
				this.$set(item, 'reason', null);
			});
		},
		async getShiftJobInfo(e) {
			this.formData.shiftJobCode = e
			if (this.formData.shiftJobCode) {
				this.clearJobInfo()

				await getShiftJobByShiftJobCode(this.formData.shiftJobCode).then(async res => {
					this.formData.pwoJobCode = res.data.code
					this.formData.ptNoTar = res.data.ptNoTar
					this.formData.ptTitleTar = res.data.ptTitleTar
					this.formData.opCode = res.data.opCode
					this.formData.opTitle = res.data.opTitle
					this.formData.batchNo = res.data.batchNo
					this.reportableNum = res.data.targetNum - res.data.finishQty

					await listPwoJobLike({
						code: this.formData.pwoJobCode
					}).then(resp => {
						this.formData.eqpId = resp.rows[0].eqpId
					})
					if (this.formData.eqpId) {
						getEquipment(this.formData.eqpId).then(res => {
							this.formData.machineId = res.data.equipmentCode
						}).catch(() => {
							this.$modal.showToast("获取设备编号失败")
						})
					}
					if (res.data.ptNoTar) {
						listMaterial({
							materialCode: res.data.ptNoTar
						}).then(resp => {
							if (resp.rows.length > 0) {
								if (resp.rows[0].specification1) this.formData.specification1 =
									resp.rows[0].specification1

								if (resp.rows[0].texture) this.formData.texture = resp.rows[0]
								.texture
								// this.formData.specification1 = resp.rows[0].specification1 ?
								// 	resp.rows[0].specification1 : ''
								// this.formData.texture = resp.rows[0].texture ? res.rows[0]
								// 	.texture : ''
							}
						}).catch(() => {
							this.$modal.showToast("查询产品规格/材质信息失败！")
						})
					}
				}).catch(() => {
					this.$modal.showToast("获取作业信息失败！")
				})
			}
		},
		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.pwoCode = res.result;
					_this.scanBarCode();
				}
			});
		},
		scanBar1() {
			const _this = this;
			uni.scanCode({
				scanType: ['barCode', 'qrCode'],
				success: function(res) {
					_this.formData.createByCode = res.result;
					_this.scanBarCreateBy();
				}
			});
		},
		scanTaskCode() {
			const _this = this;
			uni.scanCode({
				scanType: ['barCode', 'qrCode'],
				success: function(res) {
					_this.formData.taskCode = res.result
					_this.scanBarTaskCode()
				}
			});
		},
		scanBarTaskCode() {
			console.log(this.formData.taskCode)
			if (this.formData.taskCode) {
				this.formData.pwoCode = null
				this.formData.shiftJobCode = null
				this.formData.shiftJobs = []
				this.clearJobInfo()
				listShiftTask({
					// taskCode: "ST000003017"
					taskCode: this.formData.taskCode
				}).then((res) => {
					this.formData.pwoCode = res.rows[0].pwoCode
					this.scanBarPwoCode()
				}).catch(() => {
					this.$modal.showToast("获取工单编码失败")
				})
			}
		},

		/**
		 * 隐藏软键盘
		 */
		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

		}*/
	},
	onLoad: function(option) {
		if (option.taskCode) {
			this.isSearchRoute = true;
			this.formData.taskCode = option.taskCode;
			this.scanTaskCode();
		}
		// 获取当前时间
		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.getOptions();
		// this.formData.type = '报废品';
		// this.formData.createByName = this.$store.state.user.name;
	}
}
</script>