<template>
	<view class="container">
		<uni-easyinput class="scanInput" placeholder="请扫描销售单号" v-model="saleCode"
			@confirm="fetchDetail" @blur="isFocusSaleCode = false" :focus="isFocusSaleCode" clearable />
		<uni-table border stripe emptyText="暂无更多数据" class="saleInfo">
		  <uni-tr v-for="(field, index) in saleInfoFields" :key="index">
		    <uni-td align="center" width="120">{{ field.label }}</uni-td>
		    <uni-td align="center">{{ getNestedValue(saleInfo, field.key) }}</uni-td>
		  </uni-tr>
		</uni-table>
		<uni-easyinput class="scanInput" placeholder="请扫描工业条码" v-if="!allowSubmission"
			v-model="pieceBarcode" @confirm="submitPiece" @blur="isFocusPieceBarcode = false" :focus="isFocusPieceBarcode" clearable />
		<uni-table border stripe emptyText="暂无更多数据" class="boxInfo">
			<uni-tr>
				<uni-th align="center" width="30">物料名称</uni-th>
				<uni-th align="center" width="30">规格</uni-th>
				<uni-th align="center" width="20">发货数</uni-th>
				<uni-th align="center" width="20">校验数</uni-th>
			</uni-tr>
			<uni-tr v-for="(item, index) in saleInfo.wmsSaleOutTaskDetailList" :key="index">
				<uni-td align="center">{{ item.materialName }}</uni-td>
				<uni-td align="center">{{ item.specification }}</uni-td>
				<uni-td align="center">{{ item.number }}</uni-td>
				<uni-td align="center">{{ item.validationNumber }}</uni-td>
			</uni-tr>
		</uni-table>
		<u-button class="submitBtn" type="primary" @click="submit" :disabled="!allowSubmission">提交</u-button>
		<u-modal :show="showModal" :title="title" :content="content" @confirm="handleConfirm" />
	</view>
</template>

<script>
import { addOut } from '@/api/wms/sale.js';
import {
	listTask,
	getTask,
	fetchTask
} from '@/api/wms/sale.js';
import { autioError, autioSuccess } from '@/utils/audio';
import { addWmsPieceOutRecord } from '@/api/mes/wmsPieceOutRecord.js';

export default {
	computed: {
		allowSubmission() {
			const { scanNumber, allNumber } = this.saleInfo;
			return scanNumber && allNumber && scanNumber === allNumber;
		}
	},
	data() {
		return {
			isFocusSaleCode: true,
			isFocusPieceBarcode: false,
			// 销售单号
			saleCode: null,
			// 销售单 id
			saleId: null,
			// 箱码
			pieceBarcode: null,
			saleInfoFields: [
			  { label: '销售单号', key: 'saleOutTaskCode' },
			  { label: '客户', key: 'customerName' },
			  { label: '下级客户', key: 'dynamicField1.nextLevelCus' },
			  { label: '扫描数量', key: 'scanNumber' },
			  { label: '订单总数', key: 'allNumber' },
			],
			// 扫描销售单号获取的数据
			saleInfo: {
				// 销售单号
				saleOutTaskCode: null,
				// 扫描数量
				scanNumber: 0,
				// 订单总数
				allNumber: 0,
				// 动态字段
				dynamicField1: {
					// 下级客户
					nextLevelCus: null
				},
				//获取的物料详情
				wmsSaleOutTaskDetailList: []
			},
			showModal: false,
			modalType: '',
			title: '',
			content: ''
		};
	},
	methods: {
		getNestedValue(obj, path) {
		  return path.split('.').reduce((o, k) => o?.[k], obj) ?? '';
		},
		focusSaleCode() {
			this.$nextTick(() => {
				this.isFocusSaleCode = true;
			});
		},
		focusPieceBarcode() {
			this.$nextTick(() => {
				this.isFocusPieceBarcode = true;
			});
		},
		showConfirm(title, content, type) {
		  this.title = title;
		  this.content = content;
		  this.modalType = type;
		  this.showModal = true;
		},
		handleConfirm() {
		  const type = this.modalType;
		  this.showModal = false;
		  this.title = this.content = this.modalType = '';
		
			if (type === 'saleCode') this.focusSaleCode();
			else if (type === 'pieceBarCode') this.focusPieceBarcode();
		},
		// 校验工业条码规范性
		validatePieceBarcode() {
			//判断工业条码里面是否有逗号，逗号后面大于九位
			if (!this.pieceBarcode) return false;
			const [prefix, suffix] = this.pieceBarcode.replace('，', ',').split(',');
			return !!(prefix && suffix?.length >= 9);
		},
		// 提交工业条码
		async submitPiece() {
		  if (!this.pieceBarcode) return;
		  if (!this.saleCode) return this.showConfirm('错误', '请先输入销售单号', 'saleCode');
		  if (!this.validatePieceBarcode()) return this.showConfirm('错误', '请输入正确的工业条码', 'pieceBarCode');
		
		  try {
		    await addWmsPieceOutRecord({
					// 销售订单号
		      saleOrderCode: this.saleCode,
					// 工业条码
		      pieceBarcode: this.pieceBarcode,
					// 客户编码
		      customerCode: this.saleInfo.customerCode,
		      delStatus: '0'
		    });
		
		    autioSuccess();
		    this.updateValidateNum(this.pieceBarcode);
		    this.$modal.msgSuccess('提交成功');
		    this.focusPieceBarcode();
		  } catch (err) {
		    autioError();
		    this.showConfirm('提交失败', err.msg || err.message || String(err), 'pieceBarCode');
		  } finally {
		    this.pieceBarcode = '';
		  }
		},
		// 增加物料校验数（数量可能与后端对不齐）
		updateValidateNum(pieceBarcode) {
			// 获取物料 id 或商品码
		  const [code] = pieceBarcode.replace('，', ',').split(',');
		  const mat = this.saleInfo.wmsSaleOutTaskDetailList.find(
		    i => i.materialId == code || i.commodityCode == code
		  );
		  if (!mat) return console.warn('未找到对应物料');
		
		  if (typeof mat.validationNumber === 'number') {
		    this.$set(mat, 'validationNumber', mat.validationNumber + 1);
		    this.$set(this.saleInfo, 'scanNumber', this.saleInfo.scanNumber + 1);
		  }
		},
		// 通过销售单号获取任务单明细
		async fetchDetail() {
			//当输入值明显不合法时不执行后续操作
			if (!this.saleCode) return;

			if (this.saleCode.length < 9) {
				this.showConfirm('错误', `销售单号 ${this.saleCode} 错误，请扫描正确的销售单号`, 'saleCode');
				this.saleCode = '';
				return autioError();
			}

			try {
				this.$modal.loading('获取明细中...');
				// 从任务单信息中获取任务单 id
				const res = await listTask({ saleOutTaskCode: this.saleCode });
				this.saleId = res.rows[0]?.id || null;
				if (!this.saleId) {
					this.$modal.closeLoading();
					this.showConfirm('获取明细失败', `请检查销售单号 ${this.saleCode}`, 'saleCode');
					return;
				}

				// 用任务单 id 获取明细详情
				const res_task = await getTask(this.saleId);
				const data = res_task.data;
				
				data.dynamicField1 = data.dynamicField1
					? JSON.parse(data.dynamicField1)
					: { nextLevelCus: null };
				delete data.id;
				
				this.saleInfo = data;
				this.focusPieceBarcode();
			} catch (err) {
				autioError();
				this.showConfirm('获取明细失败', err.message || err, 'saleCode');
			} finally {
				this.$modal.closeLoading();
			}
		},
		// 提交
		async submit() {
		  try {
		    this.$modal.loading('提交中...');
		    const { data } = await fetchTask(this.saleId);
		    const detail = {
		      ...data,
		      wmsSaleOutTaskDetailList: data.wmsSaleOutTaskDetailList.map(i => {
		        const { id, ...rest } = i;
		        return rest;
		      }),
		      dynamicField1: JSON.stringify(this.saleInfo.dynamicField1),
		      wmsSaleOutDetailList: data.wmsSaleOutTaskDetailList,
		      billType: 2
		    };
		    delete detail.id;
		    await addOut(detail);
		    autioSuccess();
		    this.$modal.msgSuccess('出库成功');
		  } catch (err) {
		    autioError();
		    this.$modal.alert(err.msg || err.message || err);
		  } finally {
		    this.$modal.closeLoading();
		  }
		}
	}
};
</script>

<style scoped lang="scss">
.container {
	background-color: #ffffff;
	// #ifdef H5
	height: calc(100vh - 44px);
	// #endif
	// #ifdef APP-PLUS
	height: 100vh;
	// #endif
	padding: 10px;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.scanInput,
.saleInfo,
.boxInfo,
.submitBtn {
	flex: 0 0 auto;
	margin: 0.5vh 0;
}

.boxInfo {
	flex: 1;
}

.uni-table-th,
.uni-table-td {
	padding: 4px;
}

.uni-table-th {
	position: sticky;
	top: 0;
	z-index: 2;
	background-color: #ffffff;
}

.submitBtn {
	width: 100%;
}

::v-deep .u-popup {
	flex: unset;
}
</style>