<template>
	<view class="form-container">
		<uni-forms ref="form" :modelValue="formData" :rules="rules" label-width="80" label-align="right">
			<uni-forms-item label="作业编码" name="pwoJobCode">
				<uni-easyinput @confirm="searchData" suffixIcon="scan" @iconClick="scanBar" type="text"
					v-model="formData.pwoJobCode" />
			</uni-forms-item>
			<uni-forms-item label="工单编码" name="pwoCode">
				<uni-easyinput type="text" v-model="formData.pwoCode" />
			</uni-forms-item>
			<uni-forms-item label="产品编码" name="ptNoTar">
				<uni-easyinput type="text" v-model="formData.ptNoTar" />
			</uni-forms-item>
			<uni-forms-item label="产品名称" name="ptTitleTar">
				<uni-easyinput type="text" v-model="formData.ptTitleTar" />
			</uni-forms-item>
			<uni-forms-item label="制程编码" name="opCode">
				<uni-easyinput type="text" v-model="formData.opCode" />
			</uni-forms-item>
			<uni-forms-item label="制程名称" name="opTitle">
				<uni-easyinput type="text" v-model="formData.opTitle" />
			</uni-forms-item>
			<uni-forms-item label="开始时间" name="startTime">
				<uni-datetime-picker type="datetime" v-model="formData.startTime" />
			</uni-forms-item>
			<uni-forms-item label="结束时间" name="endTime">
				<uni-datetime-picker type="datetime" v-model="formData.endTime" />
			</uni-forms-item>
			<uni-forms-item label="操作人员" name="staff">
				<uni-easyinput type="text" v-model="formData.staff" @confirm="searchStaff" />
			</uni-forms-item>
			<uni-forms-item label="调试单价" name="programmingDebuggingUnitPrice">
				<uni-easyinput type="text" v-model="formData.programmingDebuggingUnitPrice" />
			</uni-forms-item>
			<uni-row>
				<uni-col :span="12">
					<uni-forms-item label="调机时长" name="timeTake" class="form-col">
						<uni-easyinput type="text" v-model="timeTake" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="12">
					<uni-forms-item label="时间单位" name="timeUnit" class="form-col">
						<uni-data-select v-model="timeUnit" :localdata="unitOptions" placeholder="选择时间单位" />
					</uni-forms-item>
				</uni-col>
			</uni-row>
		</uni-forms>
		<u-button type="primary" @click="submit">提交</u-button>
	</view>
</template>

<script>
import { addRecord } from "@/api/mes/mesMachineSetUpRecord.js";
import { listPwoJob } from "@/api/mes/jobReport.js";
import { getUserInfo } from "@/api/system/user.js";
import { getEmployeeByCode } from "@/api/basic/employee.js";

export default {
	data() {
		return {
			formData: {
				machineAdjustmentDuration: null,
			},
			timeTake: null,
			timeUnit: 'h',
			rules: {
				pwoJobCode: {
					rules: [{
						required: true,
						errorMessage: '请扫描作业编码!'
					}]
				}
			},
			unitOptions: [
				{ value: 'h', text: '小时' },
				{ value: 'm', text: '分钟' },
				{ value: 's', text: '秒' }
			],
		}
	},
	created() {
		this.$set(this.formData, "staff", this.$store.state.employee.empName);
	},
	methods: {
		scanBar() {
			const _this = this;
			uni.scanCode({
				scanType: ['barCode', 'qrCode'],
				success: function(res) {
					_this.$set(_this.formData, "pwoJobCode", res.result);
					_this.scanBarCode(_this.formData.pwoJobCode);
				}
			});
		},
		searchStaff() {
			const _this = this;
			getEmployeeByCode(_this.formData.staff).then(async res => {
				if(res.data != null){
					_this.$set(_this.formData, "staff", res.data.name);
				}else{
					_this.$modal.msg("未查询到该员工！");
				}
			})
		},
		searchData() {
			const _this = this;
			if (_this.formData.pwoJobCode) {
				let obj = {
					code: _this.formData.pwoJobCode
				}
				listPwoJob(obj).then(async res => {
					let jobs = res.rows;
					if (jobs.length == 0) {
						_this.$modal.msg("未检索到该作业编码相关的信息！");
					} else {
						let job = jobs[0];
						_this.$set(_this.formData, "pwoCode", job.pwoCode);
						_this.$set(_this.formData, "ptNoTar", job.ptNoTar);
						_this.$set(_this.formData, "ptTitleTar", job.ptTitleTar);
						_this.$set(_this.formData, "opCode", job.opCode);
						_this.$set(_this.formData, "opTitle", job.opTitle);
					}
				})
			}
		},
		scanBarCode() {
			const _this = this;
			if (_this.formData.pwoJobCode) {
				let obj = {
					code: _this.formData.pwoJobCode
				}
				listPwoJob(obj).then(async res => {
					let jobs = res.rows;
					if (jobs.length == 0) {
						_this.$modal.msg("未检索到该作业编码相关的信息！");
					} else {
						let job = jobs[0];
						this.$set(this.formData, "pwoCode", job.pwoCode);
						this.$set(this.formData, "ptNoTar", job.ptNoTar);
						this.$set(this.formData, "ptTitleTar", job.ptTitleTar);
						this.$set(this.formData, "opCode", job.opCode);
						this.$set(this.formData, "opTitle", job.opTitle);
					}
				})
			}
		},
		submit() {
			const _this = this;
			this.$refs.form.validate().then(res => {
				if (_this.timeTake && _this.timeUnit && _this.formData.endTime) {
					_this.changeTime();
					if (!_this.formData.startTime) {
						_this.formData.startTime = _this.getCurrentDatetime();
					}
					const isLegal = new Date(_this.formData.startTime).getTime() < new Date(_this.formData.endTime).getTime();
					if (!isLegal) {
						_this.$modal.msg("结束时间不能早于开始时间");
						return;
					}
					_this.$modal.loading('提交中')
					addRecord(_this.formData).then(res => {
						_this.$modal.closeLoading();
						_this.$modal.msgSuccess("提交成功！");
						// _this.reset();
						setTimeout(() => {
							this.$tab.switchTab("/pages/work/index");
						}, 500);
					})
				} else {
					_this.$modal.msg("请将信息补充完整");
				}
			})
		},
		changeTime() {
			const _this = this;
			if (_this.timeUnit === 'h') {
				_this.formData.machineAdjustmentDuration = _this.timeTake * 60 * 60;
			} else if (_this.timeUnit === 'm') {
				_this.formData.machineAdjustmentDuration = _this.timeTake * 60;
			} else {
				_this.formData.machineAdjustmentDuration = _this.timeTake;
			}
		},
		getCurrentDatetime() {
			const now = new Date();
			// 年（4位）
			const year = now.getFullYear();
			// 月（补零，2位）
			const month = String(now.getMonth() + 1).padStart(2, '0');
			// 日（补零，2位）
			const day = String(now.getDate()).padStart(2, '0');
			// 时（补零，2位）
			const hour = String(now.getHours()).padStart(2, '0');
			// 分（补零，2位）
			const minute = String(now.getMinutes()).padStart(2, '0');
			// 秒（补零，2位）
			const second = String(now.getSeconds()).padStart(2, '0');

			// 拼接为 "YYYY-MM-DD HH:mm" 格式
			return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
		},
	}
}
</script>

<style scoped>
.form-container {
	padding: 15px;
	display: flex;
	flex-direction: column;
	gap: 10px;
}

.uni-forms-item {
	margin-bottom: 1rem;
}
</style>