<template>
	<view class="container">
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">Mes工位库库存变更</block>
		</cu-custom>
		<view class="example">
			<uni-forms ref="form" :model="formData" labelWidth="80px">
				<uni-forms-item label="托盘编号" name="palletCode">
					<uni-easyinput v-model="formData.palletCode" placeholder="请扫描托盘号" @blur="trimPalletInput"/>
				</uni-forms-item>
				<uni-forms-item label="物料编号" name="skuCode">
					<uni-easyinput v-model="this.skuCode" disabled/>
				</uni-forms-item>
				<uni-forms-item label="物料描述" name="skuName">
					<textarea class="full-width-textarea"  v-model="this.skuName" disabled/>
				</uni-forms-item>
				<uni-forms-item label="工位" name="locCode">
					<uni-easyinput v-model="this.locCode" disabled/>
				</uni-forms-item>
				<uni-forms-item label="MES工位" name="mesStationCode">
					<uni-easyinput v-model="this.mesStationCode" disabled/>
				</uni-forms-item>
				<uni-forms-item label="变更类型" required>
					<uni-data-checkbox v-model="formData.orderType" :localdata="orderType" />
				</uni-forms-item>
				<uni-forms-item label="变更数量" name="amount">
					<uni-easyinput v-model="formData.amount" type="number" placeholder="请输入变更数量"/>
				</uni-forms-item>
			</uni-forms>
		  <view class="button-group">
		    <button :disabled="isButtonDisabled" style="width: 100px;" @click="callAgv">确认变更</button>
		  </view>

		</view>
		<view class="cu-modal" :class="msgModalName=='Modal'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">{{msgTitleName}}</view>
					<view class="action" @tap="hideMsgModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl">
					{{msg}}
				</view>
			</view>
		</view>
	</view>

</template>

<script>
	import { getStation, setStation } from '@/utils/station'
	import{queryLinePalletInfo} from "@/api/wms/palletDetailUnBind.js"
	import {
		getSkuDictionary,getSkuTypes
	} from "@/api/wms/sku.js"
	import {
		createPalletBySku, callAgvIn,surplusReturn
	} from "@/api/wms/bill.js"
	import {
		getDictionary
	} from "@/api/wms/dictData.js"
	import {
		formatDate
	} from 'tough-cookie';
	export default {
		data() {
			return {
				whCode: this.$store.state.user.warehouse[0]?.warehouseCode,
				userCode:this.$store.state.user.name,
				isButtonDisabled:false,
				autoCall:true,
				callStatus:"已开启自动呼叫空容器",
				//表单中的数据信息	
				formData: {
					palletCode: "",
					locCode: "",
					amount: "",
					orderType: 2
				},
				rules: {
					skuCode: {
						rules: [{
							required: true,
							errorMessage: '请选择物料'
						}]
					},
					palletCode: {
						rules: [{
							required: true,
							errorMessage: '请扫码托盘号'
						}]
					},
					locCode: {
						rules: [{
							required: true,
							errorMessage: '请扫码货位号'
						}]
					},
					skuQty: {
						rules: [{
							required: true,
							errorMessage: '请输入物料数量'
						}]
					}
				},
				// 单选数据源
				orderType: [{
					text: '扣减',
					value: 2
				}, {
					text: '增加',
					value: 1
				}],
				
				//查询获取的单据信息
				billInfo: {
					totalPlanQty: 0,
					totalSurplusQty: 0,
					wmsInBillSkuInfos: []
				},
				//table 相关
				searchVal: '',
				tableData: [],
				// 每页数据量
				pageSize: 10,
				// 当前页
				pageCurrent: 1,
				// 数据总量
				total: 0,
				loading: false,
				//tabe选中的数据对象
				selectedIndexs: [],
				// 列配置
				tableClumns: [{
						dataIndex: "itemCode",
						key: "itemCode",
						title: "明细单号"
					},
					{
						dataIndex: "batch",
						key: "batch",
						title: "批次"
					},
					{
						dataIndex: "skuCode",
						key: "skuCode",
						title: "物料编号"
					},
					{
						dataIndex: "skuName",
						key: "skuName",
						title: "物料名称"
					},
					{
						dataIndex: "planQty",
						key: "planQty",
						title: "计划数量"
					},
					{
						dataIndex: "lockQty",
						key: "lockQty",
						title: "锁定数量"
					},
					{
						dataIndex: "qty",
						key: "qty",
						title: "组盘数量"
					},
				],
				
				warehouseList: [],
				skuList: [],
                skuType:'',
                skuTypeList: [],
				skuArray: [],
				skushow: false,
				invoiceCode: null,
				palletCode: null,
				houseCode: null,
				skuCode: null,
				skuName: null,
				locCode: null,
				mesStationCode: null,
				skuQty: null,
				stations: [],

				totalPlanQty: null,
				totalSurplusQty: null,

				msgModalName: null,
				msgTitleName: null,
				msg: null
			};
		},
		onLoad() {
			//加载物料下拉值列表
			this.getSkuTypes()
			//加载入库单据类型下拉值列表
			// this.getWarehouses()
			//this.getInvoicesByBusinessType()
			
			const saved = getStation();
			this.stations = saved ? JSON.parse(saved) : [];
			console.log(this.stations);
			if(this.stations.length === 0) {
			    this.$modal.msgError("请先在空工装回库页面配置工位！")
			}
			var stas = [];
			for (var i = 0; i < this.stations.length; i++) {
				stas[i] = {value:this.stations[i],text:this.stations[i]}
			}
			this.stations = stas;
		
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},

		watch: {
			async  skuType(newVal) {
				var param={categoryCode:this.skuType}
				this.skuList = await getSkuDictionary(param);
			 
			}
		},
		methods: {
			//去除空格并查询托盘信息
			trimPalletInput(event) {
			    this.formData.palletCode = event.target.value.trim();
				
				this.queryPalletInfo();
			},
			queryPalletInfo: async function(e) {
				console.log('进入托盘查询方法');
				var palletCode = this.formData.palletCode;
				if (palletCode == null) {
					this.$modal.msgError("托盘编号不能为空")
					return;
				}
				if (palletCode.length < 1) {
					this.$modal.msgError("托盘编号不能为空")
					return;
				}
				//查询托盘信息
				var palletInfo = await queryLinePalletInfo({
					'palletCode': palletCode
				});
				console.log("palletInfo", palletInfo)
				if (palletInfo) {
					var palletDetails = palletInfo.data;
					this.skuCode = palletDetails.skuCode;
					this.skuName = palletDetails.skuName;
					this.locCode = palletDetails.locCode;
					this.mesStationCode = palletDetails.mesStationCode;
				};
			},
			
			//去除空格
			trimLocInput(event) {
			    this.formData.locCode = event.target.value.trim();
			},
			/// 数据来源 [模拟]
			async fetch(param) {
				var response = await queryInBillSkuInfo(param);
				return {
					total: response.data.total,
					data: response.data.record,
				};
			},
			switchChange(e){
				this.autoCall = e.detail.value;
				if(this.autoCall){
					this.callStatus="已开启自动呼叫空容器"
				}else{
					this.callStatus="已停止自动呼叫空容器"
				}
			},
			//获取物料类型列表
			async getSkuTypes() {
				this.skuTypeList = await getSkuTypes();
				console.log("this.skutypeList",this.skuTypeList)
			},
			//获取物料列表
			// async getSkus() { 
			// 	console.log("this.skuType",this.skuType)
            //     if(this.skuType){
            //         this.skuList = await getSkuDictionary(this.skuType);
            //     }
			// },
			//获取仓库列表
			async getWarehouses() {
				this.warehouseList = await getDictionary('warehouseList');
				console.log("this.warehouseList",this.warehouseList)
			},
			// 多选处理
			selectedItems() {
				return this.selectedIndexs.map(i => this.tableData[i])
			},
			// 多选
			selectionChange(e) {
				console.log(e.detail.index)
				this.selectedIndexs = e.detail.index
				//选中内容改变时获取选中数据

			},
			//批量删除
			delTable() {
				console.log(this.selectedItems())
			},
			// 分页触发
			change(e) {
				this.$refs.table.clearSelection()
				this.selectedIndexs.length = 0
				this.getData(e.current)
			},
			// 搜索
			search() {
				this.getData(1, this.searchVal)
			},
			// 获取数据
			getData(pageCurrent, value = '') {
				this.loading = true
				this.pageCurrent = pageCurrent
				this.request({
					pageSize: this.pageSize,
					pageCurrent: pageCurrent,
					value: value,
					success: res => {
						// console.log('data', res);
						this.tableData = res.data
						this.total = res.total
						this.loading = false
					}
				})
			},
			//获取选中的数据
			getSelectDetail() {
				if (this.selectedIndexs.length == 0) {
					//提示 
					this.$modal.msgError("请先选择需要组盘的单据明细")
					return;
				}
				//筛选出需要拣选的单据明细
				let arr = [];
				let len = this.billInfo.wmsInBillSkuInfos.length;
				for (let i = 0; i < len; i++) {
					if (this.selectedIndexs.indexOf(i) >= 0) {
						arr.push(this.billInfo.wmsInBillSkuInfos[i]);
					} else {
						// console.log(this.selectArr.indexOf(i))
						//this.selectArr.indexOf(i);
					}
				}
				console.log("选中的单据明细数据为", arr.length)
				return arr;
			},

			// 伪request请求
			request(options) {
				const {
					pageSize,
					pageCurrent,
					success,
					value
				} = options
				let total = tableData.length
				let data = tableData.filter((item, index) => {
					const idx = index - (pageCurrent - 1) * pageSize
					return idx < pageSize && idx >= 0
				})
				if (value) {
					data = []
					tableData.forEach(item => {
						if (item.name.indexOf(value) !== -1) {
							data.push(item)
						}
					})
					total = data.length
				}

				setTimeout(() => {
					typeof success === 'function' &&
						success({
							data: data,
							total: total
						})
				}, 500)
			},
			// submit(ref) {
			// 	this.$refs.form.validate().then(res => {
			// 		updateUserProfile(this.user).then(response => {
			// 			this.$modal.msgSuccess("修改成功")
			// 		})
			// 	})
			// }
			//组盘
			submitPallet: function(ref) {
				this.isButtonDisabled = true; 
				this.$modal.loading("请等待...")
				this.$refs.form.validate().then(res => {
					
					let requestData={
						...this.formData,
						userCode:this.userCode,
						warehouseCode:this.whCode
					}
					createPalletBySku(this.formData).then(response => {
						console.log("response", response)
						this.$modal.msgSuccess("组盘成功")
					}).finally(() => {
                    this.isButtonDisabled = false; // 恢复按钮可用
				    this.$modal.closeLoading()
					});
				}).catch(()=>{
                    this.isButtonDisabled = false; // 恢复按钮可用
				    this.$modal.closeLoading()
				})
			},
			generateUUID: function() {
			  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			    const r = (Math.random() * 16) | 0;
			    const v = c === 'x' ? r : (r & 0x3) | 0x8;
			    return v.toString(16);
			  });
			},
			
			//Mes工位库库存变更
			callAgv: function() {
				this.isButtonDisabled = true; 
                this.$modal.loading("请等待...")
                if(!this.formData.locCode){
                    this.$modal.closeLoading()
                }
                if(!this.formData.palletCode){
                    this.$modal.closeLoading()
                }
                var data={
					list:[{
						amount:this.formData.amount,
						materialCode:this.skuCode,
						orderId:this.generateUUID(),
						orderType:this.formData.orderType,
						stationGroupCode:this.mesStationCode
					}],
					siteCode:"1021"
                }
				
				uni.request({
				    url: 'https://gw-qd-aliyun.haier.net/hdshmls/raw-wms-remoting-service/api/seqPull/updateSeq',
					method: 'POST',
				    data: data,
				    header: {
				        'Authorization': 'tx7rruWpIRhU2v7Ofuls3nKsrAyHWN5o'
				    },
				    success: (res) => {
				        console.log(res.data);
						if(res.data.code == '1') {
							this.$modal.msgSuccess("MES工位库库存变更成功")
						} else {
							this.$modal.msgError(res.data.msg)
						}
				    },
				});
				this.isButtonDisabled = false; // 恢复按钮可用
				this.$modal.closeLoading()
			},
			hideMsgModal(e) {
				//关闭信息模态框
				this.msgModalName = null;
			},
			textareaAInput(e) {
				this.textareaAValue = e.detail.value
			},
			textareaBInput(e) {
				this.textareaBValue = e.detail.value
			},
			//根据单据号查询入库单
			queryRkOrder: async function(e) {
				console.log('进入查询方法', e);
				console.log('this.formData', this.formData);
				console.log('this.formData.invoiceCode', this.formData.invoiceCode);
				var invoiceCode = this.formData.invoiceCode;
				if (invoiceCode == null) {
					this.$modal.msgError("单据号不能为空")
					return;
				}
				if (invoiceCode.length < 1) {
					this.$modal.msgError("单据号不能为空")
					return;
				}
				//查询单据信息
				var billInfo = await queryInBillSkuInfo({
					'invoiceCode': invoiceCode
				});
				console.log("billInfo", billInfo)
				if (billInfo) {
					this.billInfo = billInfo.data;
				};
			}
		}
	}
</script>

<style lang="scss">
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}

	page {
		background-color: #ffffff;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}
 .switch-item {
   display: flex;
   align-items: center;
   justify-content: space-between;
   padding: 10px;
   border-bottom: 1px solid #eee;
 }
 /* 输入框样式 */
 .full-width-textarea {
     width: calc(100vw - 260rpx); /* 直接扣除边距 */
 
   padding: 20rpx;
   box-sizing: border-box;
   border: 2rpx solid #e5e5e5;
   border-radius: 8rpx;
   min-height: 200rpx;
   font-size: 28rpx;
   line-height: 1.5;
 }
</style>