<template>
	<view class="app-container">
		<uni-nav-bar dark :fixed="true" shadow background-color="#007AFF" status-bar :title="formData.billTypeName"
							left-icon="left" left-text="返回" @clickLeft="handleBack"
							right-icon="refreshempty" @clickRight="SendNumEmpty"/>
		<view class="scan-header">
			<uni-forms-item  name="remark" label="条码" :label-width="lableWidth" labelAlign="right" 
					style="margin-bottom: 0px; padding: 0px 15px 0px 15px;" >
				<uni-easyinput type="text" :inputBorder="true" v-model="barCode"
					:clearable="false" @confirm="scanSearch" ></uni-easyinput>
				<view class="icon" @click="handleScanClick">
					<uni-icons type="scan" size="20"></uni-icons>
				</view>
			</uni-forms-item>
		</view>
		<view class="cpck-content">
			<scroll-view :scroll-top="scrollTop" :show-scrollbar="true" scroll-y="true" class="scroll-Y">
				<view class="form-container">
					<uni-forms 
						:rules="rules" 
						:value="formData" 
						ref="form" 
						validate-trigger="submit" 
						err-show-type="toast"
					>
						<uni-forms-item  name="billTypeCode" label="单据类型" :label-width="lableWidth"  labelAlign="right">
							<uni-data-select
								v-model="formData.billTypeCode"
								:localdata="billTypeOption"
								@change="ywlxChange"
							></uni-data-select>
						</uni-forms-item>
						<uni-forms-item  name="warehouseCode" :required="rulesStar('warehouseCode')" v-if="fieldHidden('warehouseCode')" label="仓库" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="text" v-model="formData.warehouseCode"  v-show="false"></uni-easyinput>
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true"
								v-model="formData.warehouseName" suffixIcon="compose" @iconClick="setScan('WH')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="backTaskOutsCode" :required="rulesStar('backTaskOutsCode')" v-if="fieldHidden('backTaskOutsCode')" label="任务编码" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true" 
								v-model="formData.backTaskOutsCode" suffixIcon="search" @iconClick="searchIconClick('task')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="deptCode" :required="rulesStar('deptCode')" v-if="fieldHidden('deptCode')" label="部门" :label-width="lableWidth" labelAlign="right">
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true" v-show="false"
								v-model="formData.deptCode" ></uni-easyinput>
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true"
									v-model="formData.deptName" suffixIcon="search" @iconClick="searchIconClick('dept')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="employeeCode" :required="rulesStar('employeeCode')" v-if="fieldHidden('employeeCode')" label="职员" :label-width="lableWidth" labelAlign="right">
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true" 
								v-model="formData.employeeCode" v-show="false" ></uni-easyinput>
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true"
								v-model="formData.employeeName" suffixIcon="search" @iconClick="searchIconClick('empl')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="customerCode" :required="rulesStar('customerCode')" v-if="fieldHidden('customerCode')" label="客户" :label-width="lableWidth" labelAlign="right">
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true" v-show="false"
								v-model="formData.customerCode" ></uni-easyinput>
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true"
									v-model="formData.customerName" suffixIcon="search" @iconClick="searchIconClick('cust')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="supplierCode" :required="rulesStar('supplierCode')" v-if="fieldHidden('supplierCode')" label="供应商" :label-width="lableWidth" labelAlign="right">
							<uni-easyinput type="text" :inputBorder="true" v-model="formData.supplierCode" v-show="false" :disabled="true"></uni-easyinput>
							<uni-easyinput type="text" :inputBorder="true" 
								v-model="formData.supplierName" :disabled="true" :styles="styleInput" 
								:suffixIcon="formData.backTaskOutsCode!=''? '' : 'search'"  @iconClick="searchIconClick('supp')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="extendCode01" :required="rulesStar('extendCode01')" v-if="fieldHidden('extendCode01')" label="收发类别" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="text" :disabled="true" :inputBorder="true"  v-show="false"
								v-model="formData.extendCode01" ></uni-easyinput>
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true"
								v-model="formData.extendName01" suffixIcon="search" @iconClick="searchIconClick('ext01')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="locationCode" :required="rulesStar('locationCode')" v-if="fieldHidden('locationCode')" label="货位" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="text" v-model="formData.locationCode" v-show="false"></uni-easyinput>
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true"
								v-model="formData.locationName" suffixIcon="compose" @iconClick="setScan('PT')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="palletCode" :required="rulesStar('palletCode')" v-if="fieldHidden('palletCode')" label="托盘" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true"
								v-model="formData.palletCode" suffixIcon="search" @iconClick="searchIconClick('pall')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="packageCode" :required="rulesStar('packageCode')" v-if="fieldHidden('packageCode')" label="包装" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true"
								v-model="formData.packageCode" suffixIcon="search" @iconClick="searchIconClick('pack')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="labelCode" :required="rulesStar('labelCode')" v-if="fieldHidden('labelCode')" label="标签编码" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true" 
								v-model="formData.labelCode" suffixIcon="compose" @iconClick="setScan('L')"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="materialCode" :required="rulesStar('materialCode')" v-if="fieldHidden('materialCode')" label="物料" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="text"  v-model="formData.materialCode" v-show="false" ></uni-easyinput>
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true" 
								v-model="formData.materialName"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="batch" :required="rulesStar('batch')" v-if="fieldHidden('batch')" label="批号" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true" v-model="formData.batch"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="unitCode" :required="rulesStar('unitCode')" v-if="fieldHidden('unitCode')" label="单位" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="text"  v-model="formData.unitCode" v-show="false"></uni-easyinput>
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true" v-model="formData.unitName"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="stockQty" :required="rulesStar('stockQty')" v-if="fieldHidden('stockQty')" label="标签数量" :label-width="lableWidth"  labelAlign="right">
							<uni-easyinput type="number" :inputBorder="true"
								v-model="formData.stockQty" @input="bqslInputHandle"  ></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item  name="rwQty" :required="rulesStar('rwQty')" v-if="fieldHidden('rwQty')" label="任务数量" :label-width="lableWidth" labelAlign="right">
							<uni-easyinput type="text" :disabled="true" :styles="styleInput" :inputBorder="true" v-model="formData.rwQty"></uni-easyinput>
						</uni-forms-item>
					</uni-forms>
				</view>
			</scroll-view>
		</view>
		
		<view class="page-bottom">
			<view class="p-b-btn">
				<uni-badge class="uni-badge-left-margin" :text="mxNum" :max-num="999" absolute="rightTop" :offset="[-3, -3]" size="small">
					<view class="box"><text class="box-text" @click="handleMx">明细</text></view>
				</uni-badge>
			</view>
			<view class="p-b-btn" @click="$noMultipleClicks(handleSave)">
				<text class="box-text" v-show="isShowSaveButton">暂存</text>
			</view>
			<view class="p-b-btn" @click="handleAuto">
				<text class="box-text">{{autoButtonTitle}}</text>
			</view>
			<view class="p-b-btn" @click="handleBack">
				<text class="box-text">返回</text> 
			</view> 
		</view>
		
		<scan-code />
		<!-- 明细弹窗 -->
		<MxPopup ref="mxPopup" @sendNum="getSendNum" :formData="formData" @sendData="getSendData"/>
		<!-- 任务清单弹窗 -->
		<RwbmPopup  ref="rwbmPopup" :title="rwbmTitle" :idxFlag="rwbmFlag" :formData="formData"  @sendData="getSendData" />
		<!-- 部门弹窗 -->
		<BmPopup ref="bmPopup" :title="bmTitle" :idxFlag="bmFlag" :formData="formData"  @sendData="getSendData"/> 
		<!-- 职员 -->
		<ZyPopup ref="zyPopup" :title="zyTitle" :idxFlag="zyFlag" :formData="formData" @sendData="getSendData"/> 
		<!-- 客户 -->
		<KhPopup ref="khPopup" :title="khTitle" :idxFlag="khFlag" :formData="formData" @sendData="getSendData"/> 
		<!-- 收发类别 -->
		<SflbPopup ref="sflbPopup" :title="sflbTitle" :idxFlag="sflbFlag" :formData="formData" @sendData="getSendData"/> 
		<!-- 供应商 -->
		<GysPopup ref="gysPopup" :title="gysTitle" :idxFlag="gysFlag" :formData="formData" @sendData="getSendData"/> 
		<!-- 托盘 -->
		<TpPopup ref="tpPopup" :title="tpTitle" :idxFlag="tpFlag" :formData="formData" @sendData="getSendData"/> 
		<!-- 包装 -->
		<BzPopup ref="bzPopup" :title="bzTitle" :idxFlag="bzFlag" :formData="formData" @sendData="getSendData"/> 
		
	</view>
</template>
 	
<script>
	import scanCode from "@/components/scan/scan.vue";
    import { getDicts } from "@/api/system/dict/data"; // 字典
	import RwbmPopup from './popup/commonpopup.vue' // 任务编码
	import BmPopup from './popup/commonpopup.vue' // 部门
	import ZyPopup from './popup/commonpopup.vue' // 职员
	import KhPopup from './popup/commonpopup.vue' // 客户
	import SflbPopup from './popup/commonpopup.vue' // 收发类别
	import GysPopup from './popup/commonpopup.vue' // 供应商
	import TpPopup from './popup/commonpopup.vue' // 托盘
	import BzPopup from './popup/commonpopup.vue' // 包装
	
	import MxPopup from './popup/mxPopup.vue'
	import {addStockOut, listWarehouse, listLocation, listBackStockTaskOut, listBackStockOut, listPallet, listPackage,listExtend, getListFieldSetting, queryBillTypeCache } from '@/api/wms/backStockOut.js'
	import { listFieldDefault } from '@/api/wms/report.js'
	import storage from '@/utils/storage'
	import { nanoid } from 'nanoid'; //唯一值 nanoid
	
	export default {
		components: {
			scanCode, 
			RwbmPopup,
			BmPopup,
			MxPopup,
			ZyPopup,
			KhPopup,
			SflbPopup,
			GysPopup,
			TpPopup,
			BzPopup
		},
		props: {},
		async onLoad(option) {
			//下面请求如果失败改为false
			let isRequest = true;
			
			//字段设置
			try {
				const res = await this.retryRequest(getListFieldSetting, { billCode: "backStockOut" });
				// 处理响应数据
				this.fieldSetting = res.rows;
			} catch (error) {
				isRequest = false;
			}
			
			//单据类型
			try {
				const res = await this.retryRequest(queryBillTypeCache, {billCode: "backStockOut"});
				// 处理响应数据
				let tmpData = res.rows;
				this.billTypeOption = tmpData.filter(item => item.isEnableApp == 0 && item.status == 0)
				                .map(item => ({
				                  billTypeCode: item.billTypeCode,
				                  billTypeName: item.billTypeName,
								  value: item.billTypeCode,
								  text: item.billTypeName,
								  taskValue: item.taskBillTypeCode ? "'" + item.taskBillTypeCode.replace(/,/g, "','") + "'" : '',
								  isControlTask: item.backTaskBillTypeCode ? item.isControlTask : 0,
				                }));
				//触发单据类型变更
				this.ywlxChange(option.ywlx);
			} catch (error) {
				isRequest = false;
			}
			
			if(isRequest==false){
				uni.showModal({
					title: '获取单据信息失败',
					content: '请返回菜单重新进入',
					showCancel: false ,//不显示取消按钮
					success: function (res) {
					    if (res.confirm) {
					        uni.navigateBack();
					    }
					}
				})
			}else{
				this.isRequest=true
			}
		},
		onUnload(){
			uni.removeStorageSync('stock_key');
		},
		onBackPress(options) {
			if (options.from === 'navigateBack') {
				// 来自于导航条返回按钮或者系统返回按钮的事件
				return false;
			}
			// 双击返回的逻辑
			const now = Date.now();
			if (this.lastBackPress && now - this.lastBackPress < 1000) {
				// 如果两次点击的间隔小于1000毫秒，则可以认为是双击
				//这时退出
				return false;
			} else {
				this.lastBackPress = now;
				uni.showToast({
					title: '再按一次退出',
					icon: 'none'
				});
				setTimeout(() => {
					this.lastBackPress = null;
				}, 1000);
				return true;
			}
		},
		data() {
			return {
				isRequest: false, //onLoad请求成功时改为true，否则不允许保存
				remarkFocus: false,
				mxNum: 0, //明细按钮数量
				suppShow: true, // 是否显示供应商
				isShowSaveButton: false, //是否显示保存按钮
				currentSelectBillTypeCode: '', // 当前单据类型
				// 必填项
				ext1Star: false, //收发类别是否是必填项
				emplStar: false, //职员是否是必填项
				autoButtonTitle: '自动',
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				billTypeOption: [],  // 业务类型字典选择框数据
				barCode: '', //条码
				formData: {
					// 单据类型
					billTypeCode: "", // 单据类型
					billTypeName: "",// 单据类型的名称（显示使用）
					taskBillTypeCode: "", //单据类型对应的任务类型
					isControlTask: null, //任务用，是否可超量
					// 任务编码
					backTaskOutsCode: "",// 出库任务退编码|行号
					taskOutsId: "",// 出库任务子表id
					backTaskOutsId: "",// 出库任务退子表id
					// 部门
					deptCode: "", //部门
					deptName: "", //部门名称
					// 职员
					employeeCode: "", // 职员
					employeeName: "", // 职员名称
					//客户
					customerCode: "", //客户编码
					customerName: "", //客户名称
					// 供应商
					supplierCode : "", //供应商
					supplierName: "", //供应商名称
					// 收发类别
					extendName01: "", // 收发类别
					extendCode01: "", // 收发类别编码
					// 仓库
					warehouseCode: "", // 仓库
					warehouseName: "", // 仓库名称
					isSupplement: "", //是否补料
					//预留
					extendCode02: "",
					extendCode03: "",
					extendCode04: "",
					extendCode05: "",
					// 组id
					appGroupId: "",
					// ===== 以下 保存时转化为 wmsBackStockOutsList=====
					//任务子表id
					taskOutsId: "",
					// 货位
					locationCode: "", // 货位编码
					locationName: "", // 货位名称 
					// 标签
					labelCode: "", // 标签编码
					// 物料
					materialCode: "", // 物料编码
					materialName: "", //物料名称
					isSupplement: 1, //是否补料
					// 批号
					batch: "", //批号
					// 托盘
					palletCode: "", // 托盘编码
					palletName: "", // 托盘名称
					// 包装
					packageCode: "", // 包装编码
					packageName: "", // 包装名称
					//单位
					unitCode: "", //单位编码
					unitName: "", //单位名称
					
					stockQty: "", // 标签数量 
					rwQty: "",// 任务数量
					batch1: "", //批号1
					batch2: "", //批号2
					materialSpecification: "", //物料规格
					isLocation:"",
					isPackage:"",
					isPallet:"",
				},
				
				show: false,
				lableWidth: '80px',
				styleInput: {
					color: '#333',
					backgroundColor: '#fff',
					disableColor: '#fff',
					borderColor: '#e5e5e5',
				},
				fieldSetting: [], //单据字段设置
				// 任务编码
				rwbmTitle: "任务",
				rwbmFlag: "rwbm",
				// 职员
				zyTitle: "职员",
				zyFlag: "zy",
				// 客户
				khTitle: "客户",
				khFlag: "kh",
				// 部门
				bmTitle: "部门",
				bmFlag: "bm",
				// 收发类别
				sflbTitle: "收发类别",
				sflbFlag: "sflb",
				// 供应商
				gysTitle: "供应商",
				gysFlag: "gys",
				// 托盘
				tpTitle: "托盘",
				tpFlag: "tp",
				// 包装
				bzTitle: "包装",
				bzFlag: "bz",
				//配合$noMultipleClicks防止重复点击
				noClick:true,
			}
		},
		methods: {
			upper: function(e) {

			},
			lower: function(e) {

			},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			async retryRequest(requestFunction, requestParams, maxRetries = 1) { 
				let retriesLeft = maxRetries;
				while (retriesLeft > 0) {
					try {
						// 调用请求函数并传入参数
						const response = await requestFunction(requestParams);
						if (response && response.code === 200) {
							return response; // 请求成功，返回响应
						} else {
							// 请求失败，但还有重试机会
							//console.warn(`请求失败，正在尝试第 ${maxRetries - retriesLeft + 1} 次重试...`);
							retriesLeft--;
						}
					} catch (error) {
						// 请求发生异常，但还有重试机会
						//console.error('请求发生异常，正在尝试重试...', error);
						retriesLeft--;
					}
				}
				// 所有重试都失败了，抛出错误
				throw new Error('获取信息失败');
			},
			onShow() {
				let that = this;
				uni.$off("scancode"); // 每次进来先 移除全局自定义事件监听器
				uni.$on("scancode", (data) => {
					// 扫描PCS码
					if(data && data !== ''){
						that.barCode = data;
						this.getDataByRemark(that.barCode);
					}else{
						uni.showToast({
						title: '扫码失败!',
						icon:'none',
						duration: 2000
						});
					}
				});
			},
			// 条码右侧扫码按钮事件
			handleScanClick:function(){
				let that = this;
				uni.scanCode({
					success: function(res) {
						// 播放音效
						// this.playMusic();
						
						// {"scanType":"QR_CODE","path":"","charSet":"ISO8859_1","result":"PT|04-A-1-1","errMsg":"scanCode:ok"}
						if(res.errMsg == "scanCode:ok"){
							that.barCode = res.result;
							this.getDataByRemark(that.barCode);
						}else{
							 uni.showToast({
							 title: '扫码失败!',
							 icon:'none',
							 duration: 2000
							 });
						}
					
					},
					fail: (err) => {

					},
					complete: () => {

					}
				});
			},
			// 根据扫码数据查询其他formItem数据
			getDataByRemark(remark){
				let that = this;
				remark = remark.replace(/^\s+|\s+$/g, '');
				var splitPre = remark.split("|")[0];
				var splitLast = remark.slice(splitPre.length+1);
				// 条码空 不执行
				if(splitLast == ""){
					return true;
				}
				// 扫码
				switch (splitPre){
					case "PT": // 货位 PT|04-A-1-1
						this.getScanHwList(splitLast);
						break;
					case "WH": // 仓库 WH|01
						this.getScanCkList(splitLast);
						break;
					case "RW": //  任务扫码 RW|
						this.getScanRwList(splitLast);
						break;
					case "L": // 标签 L|L2311060002 
						this.getScanBqList(splitLast);
						break;
					case "P": // 托盘 P|0002
						this.getScanTpList(splitLast);
						break;
					case "PA": // 包装 PA|0002
						this.getScanBzList(splitLast);
						break;
					default:
						uni.showToast({
							title: "条码不合法",
							icon: "none"
						})
						break;
				}
			},
			// 条码框 回车
			scanSearch(remark){
				this.getDataByRemark(remark);
			},
			async ywlxChange(value) {
				if(value === ''){
					this.formData.billTypeCode = "";
					this.formData.billTypeName = "";
					this.formData.taskBillTypeCode = "";
					this.formData.isControlTask = "";
				}else {
					let status = this.billTypeOption.find(item => item.value == value);
					if(status){
						this.formData.billTypeCode = status.value;
						this.formData.billTypeName = status.text;
						this.formData.taskBillTypeCode = status.taskValue;
						this.formData.isControlTask = status.isControlTask
					}
				}
				
				// 监听业务类型变更，变更后。清空任务、供应商、收发类别、清空明细查询出的数据、清空入库单号和单号数组
				//清空任务
				this.formData.taskOutsId = ""; 
				this.formData.backTaskOutsCode = "";
				this.formData.backTaskOutsId = "";
				//清空供应商
				this.formData.supplierCode = "";
				this.formData.supplierName = "";
				//清空收发类别
				this.formData.extendCode01 = "";
				this.formData.extendName01 = "";
				// 清空明细数据
				if (this.$refs.mxPopup) {
					this.$refs.mxPopup.listData = [];
				}
				// 清空入库单号和单号数组
				uni.removeStorageSync('stock_key');
				//更新唯一值
				this.formData.appGroupId = nanoid(19);
				
				if(value!='' && value!=null){
					//默认值
					const res = await this.retryRequest(listFieldDefault, { "billTypeCode":value, "billCode": 'backStockOut' });
					if(res.code === 200){
						let fieldDefault = res.rows; //字段默认值
						let fieldSetting = this.fieldSetting.filter(item => item.defaults == '1'); //字段信息
						let form = this.formData; //新增的信息
						/*
						* 遍历字段信息，如果字段默认值和头信息中存在，则用字段中的keyCode、keyName和默认值中的settingCode、settingName赋值给from
						*/
						for (let i = 0; i < fieldSetting.length; i++) {
							let fieldD = fieldDefault.filter(item => item.settingFlag == fieldSetting[i].field);
							//如果字段默认值和头信息中存在
							if (fieldD.length>0 && fieldSetting[i].field in form) {
								//仓库触发一次扫码
								if(fieldD[0].settingFlag=="warehouseCode" && fieldD[0].settingCode){
									this.getScanCkList(fieldD[0].settingCode)
									continue
								}
								
								//赋值code(实际值)
								if(fieldSetting[i]["keyCode"]){
									form[ fieldSetting[i]["keyCode"] ] = fieldD[0].settingCode;
								}
								//赋值name(显示值)
								if(fieldSetting[i]["keyName"]){
									form[ fieldSetting[i]["keyName"] ] = fieldD[0].settingName;
								}
							}
						}
					}
				}
			},
			getSendData(res){ //基础资料
				let cFlag = res.currentFlag; 
				switch (cFlag){
					case "rwbm": // 任务编码
						//任务
						this.formData.taskOutsId = res.selectData.wmsTaskOuts.taskOutsId;
						this.formData.backTaskOutsCode = res.selectData.wmsTaskOuts.subTaskCode;
						this.formData.backTaskOutsId = res.selectData.wmsTaskOuts.id;
						// 赋值部门
						this.formData.deptCode = res.selectData.deptCode;
						this.formData.deptName = res.selectData.deptName;
						// 赋值职员
						this.formData.employeeCode = res.selectData.employeeCode;
						this.formData.employeeName = res.selectData.employeeName;
						// 赋值供应商
						this.formData.supplierCode = res.selectData.supplierCode;
						this.formData.supplierName = res.selectData.supplierName;
						// 赋值物料、任务数量
						this.formData.materialCode = res.selectData.wmsTaskOuts.materialCode;
						this.formData.rwQty = (res.selectData.wmsTaskOuts.taskQty || 0) - (res.selectData.wmsTaskOuts.stockQty || 0);
						break;
					case "bm": // 部门
						this.formData.deptCode = res.selectData.deptCode;
						this.formData.deptName = res.selectData.deptName;
						
						// 职员清空
						this.formData.employeeCode = "";
						this.formData.employeeName = "";
						break;
					case "zy": // 职员
						this.formData.employeeCode = res.selectData.employeeCode;
						this.formData.employeeName = res.selectData.employeeName;
						break;
					case "kh": // 客户
						this.formData.customerCode = res.selectData.customerCode;
						this.formData.customerName = res.selectData.customerName;
						break;
					case "sflb": // 收发类别
						this.formData.extendName01 = res.selectData.extendName;
						this.formData.extendCode01 = res.selectData.extendCode;
						break;
					case "gys": // 供应商
						this.formData.supplierCode = res.selectData.supplierCode;
						this.formData.supplierName = res.selectData.supplierName;
						break;
					case "bz": // 包装
						this.formData.packageCode = res.selectData.packageCode;
						this.formData.packageName = res.selectData.packageName;
						if(res.selectData.warehouseCode){
							this.formData.warehouseCode = res.selectData.warehouseCode;
							this.formData.warehouseName = res.selectData.warehouseName;
						}
						if(res.selectData.locationCode){
							this.formData.locationCode = res.selectData.locationCode;
							this.formData.locationName = res.selectData.locationName;
						}
						if(res.selectData.palletCode){
							this.formData.palletCode = res.selectData.palletCode;
							this.formData.palletName = res.selectData.palletName;
						}
						break;
					case "tp": // 托盘
						this.formData.palletCode = res.selectData.palletCode;
						this.formData.palletName = res.selectData.palletName;
						if(res.selectData.warehouseCode){
							this.formData.warehouseCode = res.selectData.warehouseCode;
							this.formData.warehouseName = res.selectData.warehouseName;
						}
						if(res.selectData.locationCode){
							this.formData.locationCode = res.selectData.locationCode;
							this.formData.locationName = res.selectData.locationName;
						}
						this.formData.packageCode = '';
						this.formData.packageName = '';
						break;
					default:
						break;
				}
			},
			// easyinput后面放大镜点击
			searchIconClick(type){
				switch (type){
					case "task":  // 任务编码
						this.$refs.rwbmPopup.showPopup();
						break;
					case "dept": // 部门
						this.$refs.bmPopup.showPopup();
						break;
					case "empl": // 职员
						this.$refs.zyPopup.showPopup();
						break;
					case "cust": // 客户
						this.$refs.khPopup.showPopup();
						break;
					case "supp": // 供应商
						this.$refs.gysPopup.showPopup();
						break;
					case "ext01": // 收发类别
						this.$refs.sflbPopup.showPopup();
						break;
					case "pall": // 托盘
						this.$refs.tpPopup.showPopup();
						break;
					case "pack": // 包装
						this.$refs.bzPopup.showPopup();
						break;
					default:
						break;
				}
			},
			remarkGetFocus(){
				this.remarkFocus = false;
				this.$nextTick(() => {
					this.remarkFocus = true
				})
			},
			setScan(str){//赋值条码框 光标聚焦
				this.barCode = str + "|";
				this.remarkGetFocus();
			},
			bqslInputHandle(value){
				let rwsl = this.formData.rwQty; //任务数量
				if(rwsl != ""){
					if(value > parseFloat(rwsl)){
						uni.showToast({
							title: "数量大于任务数量",
							icon: "none"
						})
						return;
					}
				}
			},
			// 下面工具栏 明细点击 事件
			handleMx(){
				this.$refs.mxPopup.showDrawer();
			},
			handleSave() {
				//获取信息失败时不可以保存
				if(this.isRequest==false){
					uni.showToast({
						title: '获取单据信息失败,请返回菜单重新进入',
						icon: "none"
					})
					return true;
				}
				if (this.isShowSaveButton) {
					uni.showToast({
						title: '保存中，请稍等',
						icon: 'none',
						duration:2000
					})
				}
				//如果唯一值空，生成唯一值
				if(this.formData.appGroupId=='' || this.formData.appGroupId==null){
					this.formData.appGroupId = nanoid(19)
				}
				
				let that = this;
				that.$refs.form.validate().then(res => {
					let wmsStockOutsArr = [];
					let tmpWms = {
						taskOutsId: that.formData.taskOutsId,// 任务
						backTaskOutsId: that.formData.backTaskOutsId,
						locationCode: that.formData.locationCode, // 货位编码
						labelCode:that.formData.labelCode,  // 标签编码
						materialCode: that.formData.materialCode, // 物料编码
						batch: that.formData.batch, //批号
						palletCode: that.formData.palletCode, // 托盘编码
						unitCode: that.formData.unitCode, //单位编码
						stockQty: that.formData.stockQty,  // 标签数量 
						batch1: that.formData.batch1, //批号1
						batch2: that.formData.batch2, //批号2
						palletCode: that.formData.palletCode, // 托盘编码
						packageCode: that.formData.packageCode, // 包装编码
						isPackage: that.formData.isPackage,
						isPallet: that.formData.isPallet,
					};
					wmsStockOutsArr.push(tmpWms);
					
					let params = {
						guid: that.getHashId,
						appGroupId: that.formData.appGroupId,
						status: "1",
						stockType: "1",
						billTypeCode: that.formData.billTypeCode, // 单据类型
						deptCode: that.formData.deptCode, //部门
						employeeCode: that.formData.employeeCode, // 职员
						supplierCode : that.formData.supplierCode, //供应商
						customerCode : that.formData.customerCode, //客户
						extendCode01: that.formData.extendCode01, // 收发类别编码
						warehouseCode: that.formData.warehouseCode, // 仓库
						wmsBackStockOutsList: wmsStockOutsArr,
						isLocation: that.formData.isLocation
					}

					addStockOut(params).then(res => {
						if(res.code === 200){
							that.mxNum ++;
							// 保存单号
							if(res.msg !== ""){
								let storageData = uni.getStorageSync('stock_key');
								if(storageData){
									let stockIdList = storageData.stockIdList;
									stockIdList.push(res.msg);
									let data = {
										"stockId":  res.msg,
										"stockIdList": stockIdList
									}
									uni.setStorageSync('stock_key', data);
								}else{
									let tmpList = [];
									tmpList.push(res.msg);
									let data = {
										"stockId":  res.msg,
										"stockIdList": tmpList
									}
									uni.setStorageSync('stock_key', data);
								}
							}
							// 扫码后任务数量 - 标签数量
							let rwQty = that.formData.rwQty;
							if(rwQty!=0 && rwQty!="" && !isNaN(parseFloat(rwQty)) && isFinite(rwQty)){
								that.formData.rwQty = rwQty - that.formData.stockQty;
							}
							// 清空子表信息
							that.EmptyEntry();
								
							if (that.isShowSaveButton) {
								uni.showToast({
									title: '保存成功',
									icon: 'none',
									duration:2000
								})
							}
						}else{
							uni.vibrateLong({});
							uni.showToast({
							 	title: "保存失败!",
								icon: "none"
							}) 
						}
					}).catch((err) => {
						uni.vibrateLong({});
					});
				}).catch((err) => {
					uni.vibrateLong({});
				});
			},
			// 任务扫码请求
			getScanRwList(barCode){
				let that = this;
				let params = {
					supplierCode: that.formData.supplierCode,  //供应商 (为空时不传)
					customerCode: that.formData.customerCode, //客户
					taskType: 1,
					billTypeCode:that.formData.taskBillTypeCode,
					params: {
						"barCode":barCode,
						"limit":1,
						"isControlTask": that.formData.isControlTask,
					},
				}
				listBackStockTaskOut(params).then(res => {
					if(res.code === 200){
						let data = res.rows ? res.rows[0] : {};
						if(data && Object.keys(data).length !== 0){
							// 赋值任务编号
							that.formData.taskOutsId = data.wmsTaskOuts.taskOutsId;
							that.formData.backTaskOutsCode = data.wmsTaskOuts.subTaskCode;
							that.formData.backTaskOutsId = data.wmsTaskOuts.id;
							// 赋值部门
							that.formData.deptCode = data.deptCode;
							that.formData.deptName = data.deptName;
							// 赋值职员
							that.formData.employeeCode = data.employeeCode;
							that.formData.employeeName = data.employeeName;
							// 赋值供应商
							that.formData.supplierCode = data.supplierCode;
							that.formData.supplierName = data.supplierName;
							// 赋值客户
							that.formData.customerCode = data.customerCode;
							that.formData.customerName = data.customerName;
							// 赋值物料、任务数量
							that.formData.materialCode = data.wmsTaskOuts.materialCode;
							that.formData.materialName = data.wmsTaskOuts.materialName;
							that.formData.materialSpecification = data.wmsTaskOuts.materialSpecification;
							that.formData.rwQty = (data.wmsTaskOuts.taskQty || 0) - (data.wmsTaskOuts.stockQty || 0);
						}else{
							uni.showToast({
								title: "无数据",
								icon: 'none',
							})
							that.formData.taskOutsId = "";
							that.formData.backTaskOutsCode = "";
							that.formData.backTaskOutsId = "";
							that.formData.deptCode = "";
							that.formData.deptName = "";
							that.formData.employeeCode = "";
							that.formData.employeeName = "";
							that.formData.supplierCode = "";
							that.formData.supplierName = "";
							that.formData.materialCode = "";
						}
					}
				});
			},
			//仓库扫码请求
			getScanCkList(barCode){
				let that = this;
				let params = {
					status: "0", // (固定)
					params: {
						"barCode":barCode,
						"limit":1
					},
				}
				// 仓库网络请求
				listWarehouse(params).then(res => {
					if(res.code === 200){
						let data = res.rows ? res.rows[0] : {};
						if(data && Object.keys(data).length !== 0){
							// 带出仓库编码、仓库名称、是否包含货位(is_location)，如果is_location=1，隐藏货位
							
							// 赋值仓库、货位
							that.formData.warehouseCode = data.warehouseCode;
							that.formData.warehouseName = data.warehouseName;
							that.formData.locationCode = "";
							that.formData.locationName = "";
							// 是否显示货位
							let obj = {"field": "locationCode","fieldName": "货位","required": null,"requiredCondition": null,"hidden": null,"hiddenCondition": null}
							obj.required = data.isLocation == "1" ? null : 1;
							obj.hidden = data.isLocation == "1" ? 1 : null;
							that.formData.isLocation = data.isLocation;
							that.setFieldSetting(obj);
							// 清空包装托盘
							that.formData.palletCode = '';
							that.formData.palletName = '';
							that.formData.packageCode = '';
							that.formData.packageName = '';

							// 清空信息
							that.EmptyTest();
							that.EmptyEntry();
							that.formData.rwQty = "";
						}else if(this.barCode){
							uni.showToast({
								title: "无数据",
								icon: 'none',
							})
						}
					}
				});
			},
			//收发类别扫码请求(但不是给扫码用的，在加载时调用)
			getScanSflbList(barCode){
				let that = this;
				let params = {
					extendClassCode: "01.02",
					params: {
						"keyWord":barCode,
						"limit":1
					},
				}
				// 收发类别网络请求
				listExtend(params).then(res => {
					if(res.code === 200){
						let data = res.rows ? res.rows[0] : {};
						if(data && Object.keys(data).length !== 0){
							// 收发类别
							that.formData.extendCode01 = data.extendCode;
							that.formData.extendName01 = data.extendName;
						}else if(this.barCode){
							uni.showToast({
								title: "无数据",
								icon: "none"
							})
						}
					}
				});
			},
			//货位扫码请求
			getScanHwList(barCode){
				let that = this;
				
				let params = {
					status: "0", // (固定)
					params: {
						"barCode":barCode,
						"limit":1
					},
				}
				// 货位网络请求
				listLocation(params).then(res => {
					if(res.code === 200){
						let data = res.rows ? res.rows[0] : {};
						if(data && Object.keys(data).length !== 0){
							if(data.warehouseCode === that.formData.warehouseCode || '' == that.formData.warehouseCode ){ // 货位能对上仓库
								// 赋值货位、仓库
								that.formData.locationCode = data.locationCode;
								that.formData.locationName = data.locationName;
								that.formData.warehouseCode = data.warehouseCode;
								that.formData.warehouseName = data.warehouseName;
								// 显示货位
								let obj = {"field": "locationCode","fieldName": "货位","required": null,"requiredCondition": null,"hidden": null,"hiddenCondition": null}
								obj.required = 1;
								that.setFieldSetting(obj);
								that.formData.isLocation = 0
								// 清空包装托盘
								that.formData.palletCode = '';
								that.formData.palletName = '';
								that.formData.packageCode = '';
								that.formData.packageName = '';
								// 清空信息
								that.EmptyEntry();
							}else{ // 货位对不上仓库
								uni.showToast({
									title: "货位不属于当前仓库",
									icon: "none",
									duration: 3000
								})
							}
						}else{
							uni.showToast({
								title: "无数据",
								icon: 'none',
							})
						}
						
					}
				});
			},
			// 标签扫码请求
			getScanBqList(barCode){
				let that = this;
				let params = {
					params: {
						"barCode":barCode,
						"limit":1
					},
					BackTaskCode: that.formData.BackTaskCode, //任务
				}
				//有任务时传物料编码
				if(that.formData.BackTaskCode!=null && that.formData.BackTaskCode!='' && that.formData.BackTaskCode!=undefined){
					params.materialCode = that.formData.materialCode;
				}
				// 标签网络请求
				listBackStockOut(params).then(res => {
					if(res.code === 200){
						let data = res.rows ? res.rows[0] : {};
						if(data && Object.keys(data).length !== 0){
							
							// 赋值标签数量
							that.formData.stockQty = data.labelQty;
							if(that.formData.backTaskOutsCode == '' || that.formData.backTaskOutsCode == null){
								that.formData.rwQty = data.labelQty;
							}
							
							// 赋值标签
							that.formData.labelCode = data.labelCode;
							// 赋值物料编码，物料名称 ， 规格
							that.formData.materialName = data.materialName;
							that.formData.materialCode = data.materialCode;
							that.formData.materialSpecification = data.materialSpecification; //规格
							// 赋值批号
							that.formData.batch = data.batch;
							that.formData.batch1 = data.batch1;
							that.formData.batch2 = data.batch2;
							// 赋值单位
							that.formData.unitCode = data.unitCode;
							that.formData.unitName = data.unitName;
							//赋值是否托、是否包装
							that.formData.isPackage = data.isPackage
							that.formData.isPallet = data.isPallet
							
							//如果不显示保存按钮则自动保存
							if (!that.isShowSaveButton) { 
								setTimeout(() => {
									that.handleSave();
								},10)
							}
							  
						}else{
							uni.vibrateLong({});
							uni.showToast({
								title: "标签无效或已扫描",
								icon: "none"
							})
						}
					}
				}).catch((err) => {
					uni.vibrateLong({});
				});
			},
			//托盘扫码请求
			getScanTpList(barCode){
				let that = this;
				let params = {
					status: "0", // (固定)
					locationCode: this.formData.locationCode,
					warehouseCode: this.formData.warehouseCode,
					params: {
						"barCode":barCode,
						"limit":1
					},
				}
				// 托盘网络请求
				listPallet(params).then(res => {
					if(res.code === 200){
						let data = res.rows ? res.rows[0] : {};
						if(data && Object.keys(data).length !== 0){
							that.formData.palletCode = data.palletCode;
							that.formData.palletName = data.palletName;
							if(data.warehouseCode){
								that.formData.warehouseCode = data.warehouseCode;
								that.formData.warehouseName = data.warehouseName;
							}
							if(data.locationCode){
								that.formData.locationCode = data.locationCode;
								that.formData.locationName = data.locationName;
							}
							that.formData.packageCode = '';
							that.formData.packageName = '';
						}else{
							uni.showToast({
								title: "无数据",
								icon: "none"
							})
						}
					}
				});
			},
			//包装扫码请求
			getScanBzList(barCode){
				let that = this;
				let params = {
					status: "0", // (固定)
					locationCode: this.formData.locationCode,
					warehouseCode: this.formData.warehouseCode,
					palletCode: this.formData.palletCode,
					params: {
						"barCode":barCode,
						"limit":1
					},
				}
				// 包装网络请求
				listPackage(params).then(res => {
					if(res.code === 200){
						let data = res.rows ? res.rows[0] : {};
						if(data && Object.keys(data).length !== 0){
							that.formData.packageCode = data.packageCode;
							that.formData.packageName = data.packageName;
							if(data.warehouseCode){
								that.formData.warehouseCode = data.warehouseCode;
								that.formData.warehouseName = data.warehouseName;
							}
							if(data.locationCode){
								that.formData.locationCode = data.locationCode;
								that.formData.locationName = data.locationName;
							}
							if(data.palletCode){
								that.formData.palletCode = data.palletCode;
								that.formData.palletName = data.palletName;
							}
						}else{
							uni.showToast({
								title: "无数据",
								icon: "none"
							})
						}
					}
				});
			},
			handleAuto(){
				if(this.autoButtonTitle === "自动"){ //手动
					this.autoButtonTitle = "手动";
					this.isShowSaveButton = true;
				}else{  //自动
					this.autoButtonTitle = "自动";
					this.isShowSaveButton = false;
				}
				
			},
			handleBack(){
				uni.showModal({
					title: '提示',
					content: '确认返回?',
					success: function (res) {
						if (res.confirm) {
							uni.navigateBack();
						} else if (res.cancel) {
						
						}
					}
				});
			},
			getSendNum(num){
				this.mxNum = num;
				if(num == 0){
					this.formData.appGroupId=''
				}
			},
			SendNumEmpty(){
				let that = this;
				if(this.mxNum>0){
					uni.showModal({
						title: '新单',
						content: '是否要明细归零，录入新单？',
						success: function (res) {
							if (res.confirm) {
								that.mxNum = 0;
								let data = {
									"stockId":  "",
									"stockIdList": []
								}
								uni.setStorageSync('stock_key', data);
								//清空唯一值
								that.formData.appGroupId = '';
							}
						}
					});
				}
			},
			EmptyTest(){ //清空任务信息
				this.formData.taskOutsId = "";
				this.formData.BackTaskCode = "";
				this.formData.backTaskOutsId = "";
				this.formData.materialCode = "";
				this.formData.materialName = "";
				this.formData.materialSpecification = "";
			},	
			EmptyEntry(){ //清空子表信息
				this.formData.labelCode = "";
				this.formData.batch = "";
				this.formData.unitCode = "";
				this.formData.unitName = "";
				this.formData.stockQty = "";
				// this.formData.rwQty = "";
				this.formData.batch1 = "";
				this.formData.batch2 = "";
				this.formData.palletCode = "";
				this.formData.palletName = "";
				this.formData.packageCode = "";
				this.formData.packageName = "";
			},
			rulesStar(str){
				let rules=this.rules;
				if(rules[str] && rules[str].rules[0] && rules[str].rules[0].required){
					return true;
				}else{
					return false;
				}
			},
			fieldHidden(str){
				let rules=this.rules;
				if(rules[str] && rules[str].rules[0] && rules[str].rules[0].hidden){
					return !true;
				}else{
					return !false;
				}
			},
			setFieldSetting(obj){ //修改字段设置
				let index = this.fieldSetting.findIndex(item => item.field == obj.field);
				if (index !== -1) {
					// 如果找到匹配项，则使用 obj 的属性覆盖 fieldSetting 中的相应属性
					Object.assign(this.fieldSetting[index], obj);
				} else {
					// 如果没有找到匹配项，则将 obj 添加到 fieldSetting 中
					this.fieldSetting.push(obj);
				}
			},
		},
		computed: {
			rules() {
				let form = this.formData;
				let rules = {};
				if(!Array.isArray(this.fieldSetting) && this.fieldSetting.length>0){
					return rules;
				}
				//转数组
				for(let i=0;i<this.fieldSetting.length;i++){
					let field = this.fieldSetting[i];
					rules[field.field] = {
						rules: [{ required: false, errorMessage: field.fieldName + '不能为空', hidden: false }],
					}
					if(field.required==1 && field.field){ //判断是否必录
						//判断是否必录
						if(!field.requiredCondition){ //条件为空
							rules[field.field].rules[0].required = true;
						}else{ //有条件；form中对应属性满足正则
							//先赋值true；正则不满足再赋值false
							rules[field.field].rules[0].required = true;
							//判断必录用正则数组
							let regArr = [];
							try {
								if(field.requiredCondition){
									let arr = JSON.parse(field.requiredCondition);
									if(arr!=null){
										regArr = arr.map(([key, value]) => [key, new RegExp(value)]);
									}
								}
							}catch(err) {
								console.error("err",err)
							}
							for(let j=0;j<regArr.length;j++){
								if(regArr[j].length==2 && regArr[j][1].test( form[regArr[j][0]] )){
									rules[field.field].rules[0].required = true;
								}else{
									rules[field.field].rules[0].required = false;
									break;
								}
							}
						}
					}
					if(field.hidden==1 && field.field){ //判断是否隐藏
						//判断是否必录
						if(!field.hiddenCondition){ //条件为空
							rules[field.field].rules[0].hidden = true;
						}else{ //有条件；form中对应属性满足正则
							//先赋值true；正则不满足再赋值false
							rules[field.field].rules[0].hidden = true;
							//判断必录用正则数组
							let regArr = [];
							try {
								if(field.hiddenCondition){
									let arr = JSON.parse(field.hiddenCondition);
									if(arr!=null){
										regArr = arr.map(([key, value]) => [key, new RegExp(value)]);
									}
								}
							}catch(err) {
								console.error("err",err)
							}
							for(let j=0;j<regArr.length;j++){
								if(regArr[j].length==2 && regArr[j][1].test( form[regArr[j][0]] )){
									rules[field.field].rules[0].hidden = true;
								}else{
									rules[field.field].rules[0].hidden = false;
									break;
								}
							}
						}
					}
				}
				return rules;
			},
			getHashId(){
				//生成哈希值
				const crypto = require('crypto');
				function hashString(str) {
					const hash = crypto.createHash('sha256');
					hash.update(str);
					return hash.digest('hex');
				}
				//null和undefined返回空
				function IFNULL(str){
					return (str==null || str==undefined) ? "" : str + "";
				}
				//使用头信息和nanoid来生成唯一值
				let groupJson = {
					appGroupId : this.formData.appGroupId,
					billTypeCode : IFNULL(this.formData.billTypeCode),
					backTaskOutId : '',
					deptCode : IFNULL(this.formData.deptCode),
					employeeCode : IFNULL(this.formData.employeeCode),
					supplierCode : IFNULL(this.formData.supplierCode),
					warehouseCode : IFNULL(this.formData.warehouseCode),
					customerCode : IFNULL(this.formData.customerCode),
					extendCode01 : IFNULL(this.formData.extendCode01),
					extendCode02 : IFNULL(this.formData.extendCode02),
					extendCode03 : IFNULL(this.formData.extendCode03),
					extendCode04 : IFNULL(this.formData.extendCode04),
					extendCode05 : IFNULL(this.formData.extendCode05),
				}
				let groupStr = JSON.stringify(groupJson)
				const hash = hashString(groupStr)
				return hash
			},
		},
	}
</script>
 
<style>
	@import "@/static/scss/stock.css";
</style>
