<template>
	<view>
		<!-- 销售预备货 -->
		<!-- <u-navbar back-text="返回" title="销售预备货" :background="background"></u-navbar> -->
		<navVar
		  :mysNavConfig="navConfig"
		  @onLeftClick="onLeftClick"
		></navVar>
		<!-- 备货框 -->
		<view style="margin-top: 50rpx;">
			<u-row>
				<u-col span="2"><label style="text-align: right;">备货：</label> </u-col>
				<u-col span="6">
					<!-- <input type="text" :border="true"  v-model="shiprequestName"> -->
					<u-input type="text"  v-model="shiprequestName" border> </u-input>
				</u-col>
				&nbsp;&nbsp;&nbsp;&nbsp;
				<u-col span="2">
					<u-button @click="selectShipRequestName" type="primary" size="mini">新增</u-button>
				</u-col>
				<u-col span="2">
					<u-button @click="serachMaterialList" type="primary" size="mini">查询</u-button>
				</u-col>
			</u-row>
		</view>


		<!-- 备货条件折叠 -->
		<view>
<!-- 			<view>
				<uni-section type="line">
					<uni-collapse>
						<uni-collapse-item title="备货条件" :show-animation="true">
							<view class="content">
								<text>
									物料编码 : {{materialSpecName}} &nbsp;&nbsp; 
									规格 : {{sdkSpec}} &nbsp;&nbsp;
									阶段 :{{phase}} &nbsp;&nbsp;
									业助: {{userId}}
								</text>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</uni-section>
			</view> -->
			<view style="margin: 20rpx;">
				<checkbox-group @change="bh" >
					<label>
						<checkbox value="cb" style="padding-right: 25rpx;"/> <text>备货条件</text>
					</label>
				</checkbox-group>
			</view>
			
			<u-card style="border: 1rpx solid #0081ff" :show-head="false" :full="true"
				:body-style="{ height: '180rpx' }" v-if = "bhShow">
				<view slot="body">
					<u-row>
						<u-col span="6">
							<view>物料编码：{{materialSpecName}}</view>
						</u-col>
						<u-col span="6">
							<view>规格：{{ specName }}</view>
						</u-col>
					</u-row>
					<br/>
					<u-row>
						<u-col span="6">
							<view>阶段：{{phase}}</view>
						</u-col>
						<u-col span="6">
							<view>业助：{{ CAREER_ASSISTANCE }}</view>
						</u-col>
					</u-row>
				</view>
			</u-card>
			<u-card style="border: 1rpx solid #0081ff" :show-head="false" :full="true"
				:body-style="{ height: '100rpx' }">
				<view slot="body">
					<u-row>
					<!-- 	<u-col span="5">
							<view>报工：{{RECEIVEREQUESTNAME}}</view>
						</u-col> -->
						<u-col span="6">
							<view>数量：{{ MATERIALQUANTITY || '0' }}</view>
						</u-col>
						<u-col span="6">
							<view>标签数：{{ JS || '0' }}</view>
						</u-col>
					</u-row>
				</view>
			</u-card>

			<view style="margin: 25rpx;">
				<u-form ref="testForm">
					<u-form-item :border-bottom="false">
						<p>条码:</p>
						<u-input :border="true" v-model="barCode" placeholder="请扫描条码" :focus="focusBarCode"
							@confirm="confirmBarcode" />
					</u-form-item>
				</u-form>
			</view>
		</view>
		<view>
			<zb-table sref="zbTable" :show-header="true" :columns="column" :stripe="true"
				:fit="true" show-summary :highlight="true" :border="true" :data="BoxInfoList" :cell-style="cellStyleFn"
				@edit="buttonEdit"
				@dele="dele"
				@lkbh="lkbh"></zb-table>
		</view>
		<!-- <uni-load-more class="font-more" iconType="auto" :status="moreStatus"
			v-show="BoxInfoList.length && totalAll < pageSize" /> -->
		<u-form>
			<!-- <u-form-item>
				<u-button @click="ConfirmButton" type="primary" size="mini" :disabled="disableButton"
					style="background-color: green;width: 80%;">备货确认</u-button>
			</u-form-item> -->
		</u-form>

		<!-- 备货内容 -->
		<view style="margin-top: 150rpx;">
			<uni-drawer ref="showUp" mode="Up" :width="260" :mask-click="true" >
				<scroll-view style="height: 68%; margin-top: 150rpx; margin-right: 10rpx;" scroll-y="true">
					<h3 style = "width: auto;color: #007AFF;">备货选项</h3>
					<br />
					<hr/>
					<br/>
					<br/>
					<view style="margin: 5rpx;">
						<u-row>
							<u-col span="3"><label style="text-align: right;">扫描标签：</label> </u-col>
							<u-col span="8">
								<u-input v-model="bhBarCode" @confirm ="getBhCondition"  :border="true"/>
							</u-col>
						</u-row>
						<br />
						<!-- 物料 -->
						<u-row>
							<u-col span="3"><label style="text-align: right;">物料编码：</label> </u-col>
							<u-col span="8">
								<!-- <zxzUniDataSelect v-model="materialSpecName" filterable :localdata="materialSpecNames">
								</zxzUniDataSelect> -->
								<u-input v-model="materialSpecName"  v-bind:disabled="true" border></u-input>
							</u-col>
						</u-row>
						<br />
						<!-- 规格 -->
						<u-row v-show = "false">
							<u-col span="3"><label style="text-align: right;">规格：</label> </u-col>
							<u-col span="8">
								<!-- <zxzUniDataSelect v-model="sdk_id"  filterable :localdata="sdkSpecs"></zxzUniDataSelect> -->
								<u-input type="text" v-bind:disabled="true" v-model="sdk_id" border> </u-input>
							</u-col>
						</u-row>
						<u-row>
							<u-col span="3"><label style="text-align: right;">SDK规格：</label> </u-col>
							<u-col span="8">
								<!-- <zxzUniDataSelect v-model="sdk_id"  filterable :localdata="sdkSpecs"></zxzUniDataSelect> -->
								<u-input type="text" v-bind:disabled="true" v-model="specName" border> </u-input>
							</u-col>
						</u-row>
						<br />
						<u-row>
							<u-col span="3"><label style="text-align: right;">阶段：</label> </u-col>
							<u-col span="8">
							<!-- 	<zxzUniDataSelect v-model="phase" filterable :localdata="phases"></zxzUniDataSelect> -->
								<u-input type="text" v-bind:disabled="true" v-model="phase" border> </u-input>
							</u-col>
						</u-row>
						<br />

						<u-row>
							<u-col span="3"><label style="text-align: right;">业助：</label> </u-col>
							<u-col span="8">
								<!-- <u-input type="text"  v-model="CAREER_ASSISTANCE" border> </u-input> -->
								<zxzUniDataSelect style="width: auto;" filterable v-model="CAREER_ASSISTANCE" :localdata="CAREER_ASSISTANCES"></zxzUniDataSelect>
							</u-col>
						</u-row>
						<br />
						<button  @click="closeDrawer" type="primary" size="mini">确认</button>
					</view>
				</scroll-view>
			</uni-drawer>
		</view>
		<u-modal :show="showModal" :title="titleModal" :content='contentModal'></u-modal>
	</view>
</template>

<script>
	import zxzUniDataSelect from "@/components/zxz-uni-data-select/zxz-uni-data-select.vue"
	import navVar from "@/components/navBar/navBar.vue"
	export default {
		components: {
			zxzUniDataSelect,
			navVar
		},
		data() {
			return {
				showModal: false,
				titleModal: "提示",
				contentModal:'是否确定返回时解绑?',
				navConfig:{
					navPadding: false,	
					isHome: false,
					navPadding:true,
					navFixed: true,
					bgImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))',
					isCustomFn: true,
					navTitle: {
						text: "销售预备货",
						color: "rgb(96, 98, 102)",
						fontSize: "14px", // px upx rpx
						fontWeight: "normal", // blod
					},
					leftText: {
						text: "返回",
						color: "rgb(96, 98, 102)",
						fontSize: "14px", // px upx rpx
						fontWeight: "", // blod
					},
					leftIconPath: '../../../../static/img/back.png'
				},
				background: {
					backgroundImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
				},
				bhShow : false,
				shiprequestName: "", //备货单号
				userId: "", //
				CAREER_ASSISTANCE : "",//业助
				CAREER_ASSISTANCES : [],
				siteName: "",
				BoxInfoList: [], //待备货内容
				materialSpecNames: [], //物料列表
				sdkSpecs: [], //规格列表
				bhBarCode : "",
				boxList: [], //传递后端的批次列表
				materialSpecName: "", //物料编码
				sdkSpec: "", //规格
				phase: "", //阶段
				disableButton: false,
				moreStatus: 'more', // 上拉加载更多  more加载前 loading加载中	no-more没有更多数据
				flag: true, // 上拉加载开关 防止一次触底查询多次问题,防止数据查完后触底还调接口问题
				barCode: "",
				MATERIALQUANTITY : 0,
				JS : 0,
				sdk_id : "",
				specName : "",
				pageNum: 1, // 页数
				pageSize: 50, // 条数
				total: 0, //每页总数
				totalAll: 0,
				focusBarCode: false, //焦点是否被选中
				column: [ //列
					{
						name: 'CHARGE',
						label: '批次',
						align: 'center',
						// fixed: true,
						// width: 210
					},
					{
						name: 'MATERIALSPECNAME',
						label: '料号'
					},
					{
						name: 'DESC_CN',
						label: '品名'
					},
					{
						name: 'SPECNAME',
						label: '规格'
					},
					{
						name: 'PHASE',
						label: '阶段',
						sorter: true
					},
					
					{
						name: 'ERPLOCATION',
						label: '库位'
					},
					{
						name: 'LOCATIONNAME',
						label: '货架'
					},{
						name: 'AREANAME',
						label: '库区'
					},
					{
						name: 'SHELFNAME',
						label: '立体库货架'
					},
					{
						name: 'MATERIALQUANTITY',
						label: '系统数量',
						sorter: true
					},
					{
						name: 'MATERIALQUANTITY2',
						label: '发货数量',
						sorter: true
					},
					{
						name: 'ISCHECK',
						label: '确认标识'
					},
					// {
					// 	name: 'MATERIALPACKINGNAME',
					// 	label: '条码',
					// 	width: 50
					// },
					{
						name: 'operation',
						type: 'operation',
						label: '操作',
						renders: [
							{
							 name:'立库备货',
							 size:'mini',
							 func:'lkbh' // func 代表子元素点击的事件 父元素接收的事件 父元素 @edit
							},
							{
								name: '编辑',
								size: 'mini',
								func: 'edit' // func 代表子元素点击的事件 父元素接收的事件 父元素 @edit
							},
							{
								name: '删除',
								size: 'mini',
								type: 'warn',
								func: "dele"
							},
						]
					},
				],
			}
		},
		mounted() {
			this.tabH = this.$GetRemainingHeight(4, 0); //定义表格的高度
			let that = this
			uni.getStorage({
				key: "sitename",
				success(res) {
					that.siteName = res.data
				}
			})
			uni.getStorage({
				key: "userid",
				success(res) {
					that.userId = res.data
				}
			})
		},
		methods: {
			onLeftClick(e) {
				if (this.BoxInfoList.every(item => item.BHFLG != 'Y')) {
					uni.navigateBack({
						delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页
					});
				}else {
					this.showModal = true;
					console.log(111, e,this.BoxInfoList)
					let self = this
					uni.showModal({
					      title: this.titleModal, // 模态框标题
					      content: this.contentModal, // 模态框内容
					      showCancel: true, // 是否显示取消按钮，默认为true
					      cancelText: '取消', // 取消按钮的文字
					      confirmText: '确定', // 确定按钮的文字
					      success(res) {
							  if (res.confirm) {
								  let listl = self.BoxInfoList.length;
								  for (let i = 0; i < listl; i++) {
									if(self.BoxInfoList[i].IS_CHECK == 'Y' || self.BoxInfoList[i].BHFLG == 'Y') {
										console.log(i, i,'all')
										self.dele(i, i,'all')
									}
								  }
								   uni.navigateBack({
									delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页
								  });
								console.log('用户点击了确定');
								// 执行确认后的逻辑
							  } else if (res.cancel) {
								console.log('用户点击了取消');
								// 执行取消后的逻辑
							  }
						}
					})
				}
			},
			bh(e) {
				let value = e.detail.value[0]
				console.log(value)
				if (value == 'cb') {
					this.bhShow = true
				} else {
					this.bhShow = false
				}
			},
			// 立库出货
			lkbh(index, row) {
				// 打开编辑对话框，或者直接修改 this.tableData[index]
				console.log("SSS"  + this.BoxInfoList[row].SHELFNAME)
				if (this.BoxInfoList[row].SHELFNAME == '' || this.BoxInfoList[row].SHELFNAME == null) {
					try {Vue.prototype.$playFail() } catch (e) {}
					this.$showMessage("非立库不能使用此功能")
					return
				}
				//this.showInputDialog(row)
				this.barCode = this.BoxInfoList[row].MATERIALPACKINGNAME
				this.confirmBarcode()
			},
			// 编辑发货数量
			buttonEdit(index, row) {
				// 打开编辑对话框，或者直接修改 this.tableData[index]
				console.log(this.BoxInfoList[row])
				if (this.BoxInfoList[row].ISCHECK != 'Y') {
					try {Vue.prototype.$playFail() } catch (e) {}
					this.$showMessage("未备货标签不能修改发货数量")
					return
				}
				this.showInputDialog(row)
			},
			dele(index, row, all) {
				if (this.BoxInfoList[row].ISCHECK != 'Y') {
					this.$showMessage("未备货标签不能取消")
					return
				}
				let boxList = []
				boxList.push(this.BoxInfoList[row])
				this.$MyRequest('/invoice/AssiginOrDessiginBarCode', {
					ShipRequestName: this.shiprequestName,
					ShipRequestDetailName: this.BoxInfoList[row].SHIPREQUESTDETAILNAME,
					type: "Dessign",
					user: this.userId,
					siteName: "SDK",
					boxList: boxList
				}).then(res => {
					this.barCode = '';
					this.focusBarCode = true
					this.focusShipRequest = false
					// 当删除所有时去除弹框
					if(all && all != 'all') {
						this.$showMessage(res.data.message)
					}
					this.serachMaterialList()
				}).catch(err => {
					this.barCode = '';
					this.focusBarCode = true
					this.focusShipRequest = false
					this.$showMessage(res)
				})
			},
			// 显示弹窗输入框
			showInputDialog(row) {
				uni.showModal({
					title: '请完成发货数量填写',
					content: '',
					editable: true, //是否显示输入框
					placeholderText: '请输入数量', //输入框提示内容
					confirmText: '确认',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							console.log('输入的内容：', res,res.content);
							if (Number(this.BoxInfoList[row].MATERIALQUANTITY) >= Number(res.content)) {
								this.BoxInfoList[row].MATERIALQUANTITY2 = res.content;
								this.$MyRequest('/SaleOut/updateSalePreOrder', {
									...this.BoxInfoList[row],
									user: this.userId,
									siteName: this.siteName == "" ? "SDK" :this.siteName,
								}).then(res => {
									this.$showMessage(res.data.message)
								}).catch(err => {
									this.$showMessage(err)
								})
							} else {
								this.$showMessage("发货数量不能大于标签数量")
							}
						}
					}
				});
			},

			// 设置是否审核的颜色状态
			cellStyleFn({
				row,
				column,
				rowIndex,
				columnIndex
			}) {
				return {
					backgroundColor: row.ISCHECK == 'Y' ? 'yellowgreen' : 'white'
				}
			},
			// 上拉刷新
			pullUp(done) {
				if (this.flag) {
					// this.moreStatus = 'loading' //加载中时的状态 转圈
					this.serachMaterialList()
					done('')
					this.moreStatus = 'more'
				} else {
					this.moreStatus = 'no-more'
					done('ok')
				}
			},
			pullUpLoading() {
				// this.$refs.zbTable.pullUpCompleteLoading('ok')	
			},
			serachMaterialList() {
				if (this.shipRequestName == "") {
					this.$showMessage("备货单号不能为空")
					return
				}
				//先获取已经备货明细
				this.BoxInfoList = []
				this.$MyRequest('/invoice/getBindStockOutInfo', {
					ShipRequestName: this.shiprequestName,
					siteName: "SDK"
				}).then(res => {
					if (res.data.success) {
						this.JS = 0
						this.MATERIALQUANTITY = 0
						for (var ii = 0; ii < res.data.resultObj.length; ++ii) {
							this.BoxInfoList.push(res.data.resultObj[ii])
							console.log("*********" + res.data.resultObj[ii] + "*********")
							this.JS = parseFloat(this.JS) + 1
							this.MATERIALQUANTITY = (cals.add(this.MATERIALQUANTITY,res.data.resultObj[ii].MATERIALQUANTITY2)).toNumber()
						}
						console.log(this.BoxInfoList)
						this.$MyRequest('/invoice/getPreStockOutInfo', {
							ShipRequestName: this.shiprequestName,
							shiprequestdetailName: "10",
							materialSpecName:this.materialSpecName,
							phase: this.phase,
							sdk_id: this.sdk_id,
							siteName: "SDK",
							CAREER_ASSISTANCE : this.CAREER_ASSISTANCE
						}).then(res => {
							if (res.data.success) {
								console.log("res.data.resultObj" + res.data.resultObj)
								for (var ii = 0; ii < res.data.resultObj.length; ++ii) {
									this.BoxInfoList.push(res.data.resultObj[ii])
								}
							} else {
								try {Vue.prototype.$playFail() } catch (e) {}
								this.$showMessage(res.data.message)
							}
						
						}).catch(err => {
							try {Vue.prototype.$playFail() } catch (e) {}
							this.$showMessage(err)
						})

					} else {
						try {Vue.prototype.$playFail() } catch (e) {}
						this.$showMessage(res.data.message)
					}

				}).catch(err => {
					try {Vue.prototype.$playFail() } catch (e) {}
					this.$showMessage(err)
				})
			},
			
			// 扫描条码
			confirmBarcode() {
				if (this.shipRequestName == "") {
					try {Vue.prototype.$playFail() } catch (e) {}
					this.$showMessage("备货单号不能为空")
					return
				}
				let list = this.BoxInfoList;
				console.log(list)
				var errcount = 0;
				var LbarCode = this.barCode;
				this.focusBarCode = false;
				let boxList = []
				for (var i = 0; i < list.length; ++i) {
					if (this.BoxInfoList[i]['MATERIALPACKINGNAME'] === LbarCode) {
						console.log(this.BoxInfoList[i])
						if (this.BoxInfoList[i]['GROUPNO'] == 0) {
							try {Vue.prototype.$playFail() } catch (e) {}
							this.$showMessage("标签已完成备货")
							this.$nextTick(() => {
								this.barCode = ""
								this.focusBarCode = true
								this.focusShipRequest = false
							})
							return
						} else if (this.BoxInfoList[i]['GROUPNO'] > 1) {
							try {Vue.prototype.$playFail() } catch (e) {}
							this.$showMessage("标签发货违背先进先出")
							this.$nextTick(() => {
								this.barCode = ""
								this.focusBarCode = true
								this.focusShipRequest = false
							})
							return
						}
						boxList.push(this.BoxInfoList[i])
						this.$MyRequest('/invoice/AssiginOrDessiginBarCode', {
							ShipRequestName: this.shiprequestName,
							ShipRequestDetailName: "10",
							type: "Assign",
							user: this.userId,
							siteName: this.siteName == "" ? "SDK" :this.siteName,
							boxList: boxList
						}).then(res => {
							if (res.data.success) {
								this.JS = 0
								this.MATERIALQUANTITY = 0
								this.serachMaterialList()
								try {Vue.prototype.$playSuccess() } catch (e) {}
								this.$nextTick(() => {
									this.barCode = ""
									this.focusBarCode = true
									this.focusShipRequest = false
								})
							} else {
								this.$showMessage(res.data.message)
								this.barCode = ""
								try {Vue.prototype.$playFail() } catch (e) {}
								this.$nextTick(() => {
									this.barCode = ""
									this.focusBarCode = true
									this.focusShipRequest = false
								})
							}
						}).catch(err => {
							this.$nextTick(() => {
								this.barCode = ""
								this.focusBarCode = true
								this.focusShipRequest = false
							})
						})
						this.$nextTick(() => {
							this.barCode = ""
							this.focusBarCode = true
							this.focusShipRequest = false
						})
						return
					} else {
						errcount++
					}
				}
				
				if (errcount == list.length) {
					try {Vue.prototype.$playFail() } catch (e) {}
					this.$showMessage("标签不在发货范围内")
					this.$nextTick(() => {
						this.barCode = ""
						this.focusBarCode = true
						this.focusShipRequest = false
					})
				}
				this.$nextTick(() => {
					this.barCode = ""
					this.focusBarCode = true
					this.focusShipRequest = false
				})
			
			},
			// 获得备货条件
			getBhCondition () { 
				this.bhConditionReset ()
				this.$MyRequest('/SaleOut/getBhCondition', {
					barCode: this.bhBarCode,
				}).then(res => {
					console.log(res)
					if (res.data.success) {
						try {Vue.prototype.$playSuccess() } catch (e) {}
						console.log(res.data.resultObj[0])
						this.materialSpecName = res.data.resultObj[0].MATERIALSPECNAME,
						this.phase = res.data.resultObj[0].PHASE,
						this.sdk_id = res.data.resultObj[0].SDK_ID
						// this.CAREER_ASSISTANCE = res.data.resultObj[0].CAREER_ASSISTANCE,
						this.specName = res.data.resultObj[0].SPECNAME
						console.log(this.specName)
						this.bhBarCode  = ""
						this.CAREER_ASSISTANCES = []
						if (res.data.resultObj[0].CAREER_ASSISTANCE != '') {
							var temp = res.data.resultObj[0].CAREER_ASSISTANCE
							var arr = temp.split(",")
							for (let i = 0; i < arr.length; i++) {
								this.CAREER_ASSISTANCES.push({
									text: arr[i],
									value: arr[i]
								});
							}
							this.CAREER_ASSISTANCES.push({
								text: "",
								value: ""
							});
						}
						
					} else {
						this.bhBarCode  = ""
						this.$showMessage(res.data.message)
						try {Vue.prototype.$playFail() } catch (e) {}
					}
					
				}).catch(err => {
				})
			},
			// 备货条件清空
			bhConditionReset () {
				this.materialSpecName = "",
				this.phase = "",
				this.sdk_id = "",
				this.CAREER_ASSISTANCE = "",
				this.specName = ""
			},
			selectShipRequestName() {
				this.$refs.showUp.open();
			},
			closeDrawer() {
				console.log("*******************")
				this.$MyRequest('/invoice/generateSalePreOrder', {
					user: this.userId,
					siteName: this.siteName || 'SDK',
					ERPFACTORY: JSON.parse(uni.getStorageSync('orgObject')).ERPFACTORY,
					MATERIALSPECNAME: this.materialSpecName,
					SDK_ID:this.sdk_id,
					PHASE: this.phase,
					CAREER_ASSISTANCE : this.CAREER_ASSISTANCE
				}).then(res => {
					console.log(res.data.message)
					this.$showMessage(res.data.message)
					this.shiprequestName = res.data.resultObj;
					this.$refs.showUp.close();
					this.barCode = '';
					this.focusBarCode = true
					this.serachMaterialList()
				}).catch(err => {
					this.$showMessage(err.message)
					this.barCode = '';
					this.focusBarCode = true
				})
			}
		}
	}
</script>

<style>
	.content {
		padding: 15px;
	}
	/* 减小 z-index 值 */
.uni-collapse {
  z-index: 0; /* 或其他适当的 z-index 值 */
}
 
/* 或调整定位属性 */
.uni-collapse {
  position: relative; /* 或 absolute 应该调整为 relative */
  top: 0; /* 根据需要调整 */
  left: 0; /* 根据需要调整 */
}
</style>
