<template>
	<view>
		<uni-collapse>
			<uni-forms ref="form" :modelValue="formData" :rules="rules">
				<uni-collapse-item title="不良记录单新增" :open="true">
					<uni-forms-item label="记录单编码" :labelWidth='90' name="pwoRecordCode">
						<uni-easyinput v-model="formData.pwoRecordCode" type="text" disabled />
					</uni-forms-item>
					<uni-forms-item label="记录单名称" :labelWidth='90' name="pwoRecordName">
						<uni-easyinput v-model="formData.pwoRecordName"></uni-easyinput>
					</uni-forms-item>
				</uni-collapse-item>
				<uni-collapse-item title="不良原因" :open="true">
					<uni-swipe-action>
						<uni-swipe-action-item v-for="(item, index) in dataList" :key="index"
							:rightOptions="rightOptions" @click="(data) => clickDetail(index,data)">
							<uni-badge :text="index+1" type="primary"></uni-badge>
							<uni-forms-item label="作业编码" :labelWidth='90'>
								<uni-easyinput suffixIcon="scan" @iconClick="scanBarPwoJobCode(index)"
									@confirm="confirmPwoJobCode(index)" type="text" v-model="item.pwoJobCode" />
							</uni-forms-item>
							<uni-forms-item label="维修工单" :labelWidth='90'>
								{{item.pwoCode}}
							</uni-forms-item>
							<uni-forms-item label="制程" :labelWidth='90'>
								{{item.opCode?(item.opCode+':'+item.opTitle):''}}
							</uni-forms-item>
							<uni-forms-item label="维修产品编码" :labelWidth='90'>
								{{item.ptNoTar}}
							</uni-forms-item>
							<uni-forms-item label="维修产品名称" :labelWidth='90'>
								{{item.ptTitleTar}}
							</uni-forms-item>
							<uni-forms-item label="物料规格" :labelWidth='90'>
								{{item.specification1}}
							</uni-forms-item>
							<uni-forms-item label="记录人员" :labelWidth='90'>
								<uni-easyinput type="text" suffixIcon="scan" @iconClick="scanBarEmpCode(index)"
									v-model="item.empCode" @confirm="(data) => isEmp(index,data)" />
								<uni-data-picker popup-title="请选择记录人员" :localdata="dataTree"
									@change="(e) => onchange(e, index)" @nodeclick="(e) => onnodeclick(e, index)"
									@popupopened="onpopupopened" @popupclosed="onpopupclosed" style="margin-top: 5px;"
									:preload="true">
								</uni-data-picker>
								<!-- <uni-data-select style="margin-top: 10px;" v-model="item.empCode"
									@change="(data) => selectEmp(index,data)" :localdata="empList"></uni-data-select> -->
							</uni-forms-item>
							<uni-forms-item label="不良原因" :labelWidth='90' name="defectReason">
								<uni-data-select style="margin-top: 10px;" v-model="item.defectReason"
									:localdata="reasonOptions"></uni-data-select>
							</uni-forms-item>
							<uni-forms-item label="维修数量" :labelWidth='90' name="number">
								<u-number-box button-size="36" inputWidth="120" v-model="item.number"
									min="0"></u-number-box>
							</uni-forms-item>
							<uni-forms-item label="用时" :labelWidth='90'>
								<uni-easyinput type="number" v-model="item.timeTake" />
							</uni-forms-item>
							<uni-forms-item label="维修时间" :labelWidth='90'>
								<view class="example-body">
									<uni-datetime-picker type="datetime" v-model="item.dateTime" />
								</view>
							</uni-forms-item>
							<uni-forms-item label="设备" :labelWidth='90'>
								<uni-easyinput suffixIcon="scan" @iconClick="scanBarEqpCode(index)"
									@confirm="(data) => isEqp(index,data)" type="text" v-model="item.eqpCode" />
							</uni-forms-item>
							<uni-forms-item label="备注" :labelWidth='90'>
								<uni-easyinput autoHeight type="textarea" v-model="item.remark"></uni-easyinput>
							</uni-forms-item>
						</uni-swipe-action-item>
					</uni-swipe-action>
					<button @click="handleAddDataList" size="mini" type="primary" plain="true"
						style="text-align: center;font-size: 18px;width: 50%;margin-bottom: 10px;display: block;margin-top: 10px;"
						v-if="formData.pwoRecordId">添加</button>
				</uni-collapse-item>
			</uni-forms>
		</uni-collapse>
		<uni-row :gutter="10">
			<uni-col :span="12">
				<u-button type="success" @click="savesubmit" :disabled="formData.pwoRecordId">保存</u-button>
			</uni-col>
			<uni-col :span="12">
				<u-button type="primary" :disabled="!formData.pwoRecordId" @click="submit">提交</u-button>
			</uni-col>
		</uni-row>
	</view>
</template>

<script>
	import {
		listMesPwoRecordrecord,
		getMesPwoRecordrecord,
		delMesPwoRecordrecord,
		addMesPwoRecordrecord,
		updateMesPwoRecordrecord
	} from "@/api/mes/mesPwoRecordrecord";
	import {
		listMesPwoRecordDetail,
		getMesPwoRecordDetail,
		delMesPwoRecordDetail,
		addMesPwoRecordDetail,
		updateMesPwoRecordDetail,
	} from "@/api/mes/mesPwoRecordDetail";
	import {
		listPwoJob,
		addReport,
		getEquipment,
		addReportEnterPiece,
		listEquipment
	} from "@/api/mes/jobReport.js";
	import {
		getDicts
	} from "@/api/system/dict/dictData.js";
	import {
		listEmployee
	} from "@/api/mes/jobIn.js";
	import {
		listDepartment
	} from "@/api/basic/department";
	export default {
		onLoad: function(option) {
			getDicts("mes_pwo_record_defect_reason").then(res => {
				this.reasonOptions = res.data.map(dict => {
					return {
						text: dict.dictLabel,
						value: dict.dictLabel,
						diasble: false
					}
				});
			})
			listEmployee().then((res) => {
				this.empList = res.rows
			})
			listDepartment().then((res) => {
				this.dptList = res.rows
			})
		},

		mounted() {},
		data() {
			return {
				reasonOptions: [],
				item: '',
				dataTree: [],
				pickerData: '',
				dptList: [],
				empList: [],
				formData: {
					pwoRecordCode: null,
					pwoRecordName: '不良记录单',
				},
				dataList: [],
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				rules: {
					formData: {
						rules: [{
							required: true,
							errorMessage: '请输入记录单名称!'
						}]
					},
					// rulesName:{
					// 	rules:[{
					// 		required:true,
					// 		errorMessage: '请输入记录人员!'
					// 	}]
					// },
					// defectReason:{
					// 	rules:[{
					// 		required:true,
					// 		errorMessage: '请输入记录不良原因!'
					// 	}]
					// },
					// number:{
					// 	rules:[{
					// 		required:true,
					// 		errorMessage: '请输入数量!'
					// 	}]
					// },
				}
			}
		},
		methods: {
			// 防抖函数
			debounce(fn, delay) {
				let timer = null; // 声明一个定时器
				return function(...args) { // 返回一个函数，它接收函数的参数
					if (timer) {
						clearTimeout(timer); // 如果定时器存在，清除它
					}
					timer = setTimeout(() => { // 设置一个新的定时器
						fn.apply(this, args); // 执行原函数
					}, delay);
				}
			},

			selectEmp(i, e) {
				this.dataList[i].empName = this.empList.find(item => item.value == e).text
			},
			deleteDetail(index) {
				this.dataList.splice(index, 1);
			},
			clickDetail(itemIndex, {
				position,
				index
			}) {
				if (index == 0) {
					this.deleteDetail(itemIndex);
				}
			},
			onnodeclick(e, index) {
				console.log(e);
				this.item = e;
				this.onchange(this.item, index); // 传递 e 和 index 给 onchange 方法
			},

			onpopupopened(e) {
				this.dataTree = []

				this.empList.filter(item => item.deptId).forEach(item => {
					item.departmentTitle = this.dptList.find(item2 => item2.id == item.deptId).departmentTitle
					// 检查dataTree中是否已存在相同部门
					let existingDept = this.dataTree.find(dept => dept.value === item.deptId);
					if (existingDept) {
						// 如果已存在相同部门，则将员工信息push进该部门的children数组
						existingDept.children.push({
							text: item.name,
							value: item.empCode
						});
					} else {
						// 如果不存在相同部门，则创建一个新部门对象，包括children数组，并将员工信息push进去
						let newDept = {
							text: item.departmentTitle,
							value: item.deptId,
							children: [{
								text: item.name,
								value: item.empCode
							}]
						};
						this.dataTree.push(newDept);
					}
				})

			},
			onpopupclosed() {
				//处理不同步
				// this.$nextTick(() => {
				// this.pickerData = this.item.value;
				// this.formData.pickerData = this.item.value;
				// if (!this.item) return
				// this.onchange(this.item)
				// });
			},
			onchange(e, index) {
				console.log(e)
				this.dataList[index].empCode = null
				this.$set(this.dataList[index], 'empCode', e.value.split('/')[0]);
			},
			scanBarPwoJobCode(i) {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						// _this.$set(_this.dataList[i], "pwoJobCode", res
						// 	.result);
						_this.dataList[i].pwoJobCode = res.result;
						_this.confirmPwoJobCode(i);
					}
				});
			},
			confirmPwoJobCode(i) {
				listPwoJob({
					code: this.dataList[i].pwoJobCode
				}).then(res => {
					if (res.rows.length > 0) {
						this.dataList[i].pwoCode = res.rows[0].pwoCode;
						this.dataList[i].opCode = res.rows[0].opCode;
						this.dataList[i].opTitle = res.rows[0].opTitle;
						this.dataList[i].ptNoTar = res.rows[0].ptNoTar.split("@")[0];
						this.dataList[i].ptTitleTar = res.rows[0].ptTitleTar.split("@")[0];
						this.dataList[i].specification1 = res.rows[0].specification1;
						if (res.rows[0].eqpId) {
							getEquipment(res.rows[0].eqpId).then(resp => {
								if (resp.data) {
									this.dataList[i].eqpCode = resp.data.equipmentCode;
								}
							})
						}
					}
				})
			},
			scanBarEmpCode(i) {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.dataList[i].empCode = res
							.result;
						_this.isEmp(i, res
							.result);
					}
				});
			},
			//验证是否为员工
			isEmp(i, code) {
				listEmployee({
					empCode: code
				}).then(res => {
					if (res.total == 0) {
						this.$modal.msg("未查询到该员工！");
						this.dataList[i].empCode = null;
					}
				})
			},
			scanBarEqpCode(i) {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.dataList[i].eqpCode = res
							.result;
						_this.isEqp(i, res
							.result);
					}
				});
			},
			//验证是否为设备
			isEqp(i, code) {
				listEquipment({
					equipmentCode: code
				}).then(res => {
					if (res.total == 0) {
						this.$modal.msg("未查询到该设备！");
						this.dataList[i].eqpCode = null;
					}
				})
			},
			handleAddDataList() {
				let obj = {}
				obj.pwoJobCode = null;
				//目前仅支持合格品
				obj.pwoCode = null;
				obj.opCode = null;
				obj.opTitle = null;
				obj.ptNoTar = null;
				obj.ptTitleTar = null;
				obj.specification1 = null;
				obj.empCode = null;
				obj.empName = null;
				obj.number = null;
				obj.timeTake = null;
				obj.dateTime = null;
				obj.eqpCode = null;
				this.dataList.push(obj);
			},
			savesubmit() {
				const _this = this;
				_this.$refs.form.validate().then(res => {
					uni.showModal({
						title: '提示',
						content: '您确定新增该维修单吗？',
						success: function(res) {
							if (res.confirm) {
								addMesPwoRecordrecord(_this.formData).then(res => {
									_this.$modal.msgSuccess("新增成功!");
									console.log(res.data)
									_this.formData.pwoRecordCode = res.data.pwoRecordCode;
									_this.formData.pwoRecordId = res.data.id
								}).catch(() => {});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				});
			},
			submit() {
				const _this = this;
				console.log(_this.dataList, this.dataTree, "dataListdataList");
				_this.dataList.forEach(item => {
					_this.dataTree.forEach(department => {
						if (department.children) {
							department.children.forEach(employee => {
								if (employee.value === item.empCode) {
									item.empName = employee.text;
								}
							});
						}
					});
				});

				_this.$refs.form.validate().then(res => {
					uni.showModal({
						title: '提示',
						content: '您确定新增该维修单明细吗？',
						success: function(res) {
							if (res.confirm) {
								let promises = [];

								for (var i in _this.dataList) {
									if (!_this.dataList[i].pwoCode) {
										_this.$modal.msg("作业必填！");
										return;
									}
									if (!_this.dataList[i].defectReason) {
										_this.$modal.msg("不良原因必填！");
										return;
									}
									if (!_this.dataList[i].empCode) {
										_this.$modal.msg("记录人员必填！");
										return;
									}
									if (!_this.dataList[i].number) {
										_this.$modal.msg("数量必填！");
										return;
									}
									_this.formData.dataInfo = _this.dataList[i];
									_this.formData.dataInfo = JSON.stringify(_this.formData.dataInfo);
									console.log(_this.formData);

									// 将addMesPwoRecordDetail的Promise加入数组
									promises.push(addMesPwoRecordDetail(_this.formData)
										.then(() => {
											_this.$modal.msgSuccess("新增成功!");
										})
										.catch(() => {}));
								}

								// 等所有Promise完成后执行
								Promise.all(promises).then(() => {
									setTimeout(() => {
										_this.$tab.switchTab("/pages/work/index");
									}, 500);
								});

							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				});
			},
			debouncedFunction() {
				return debounce(this.submit, 1500);
			},
			debouncedFunction() {
				return debounce(this.savesubmit, 1500);
			},
		}
	}
</script>

<style>
</style>