<template>
	<view>
		<u-navbar back-text="返回" title="物料拣配/出库" :background="background"></u-navbar>
		<view v-show="loadding"
			style="width: 100%; height: 900rpx; display: flex; justify-content: center; align-items: center;">
			<u-loading mode="circle" :size="70" color="#00aaff"></u-loading>
		</view>
		<view class='content' v-show="!loadding">
			<u-select v-model="show" mode="single-column" :list="dlist" @confirm="confirm" confirm-text='确认选择' />
			<view style="display: flex; justify-content: space-between; margin-top: 10rpx;">
				<u-input v-model="form.plan" :border="true" style="background: #FFFFFF; margin-right: 10rpx;"></u-input>
				<u-button @click="handleSelectFormId" style="width: 26%;">选单号</u-button>
			</view>
			<view v-if="exportViewFlag" @click="exportTimeView" style="background-color: #b3c1ff;width: 520rpx;height: 40rpx;margin-top: 10rpx;font-size: 30rpx;
			padding-left: 22rpx;">
			{{exportTime}}</view>
<!-- 			<view v-if="exportTagFlag" style="margin-top: 10rpx;margin-bottom: 5rpx;">
								<ir-date-time-picker type="border-bottom" start="2021-1-1" end="2050-12-31" :value="exportTime"
					 placeholder="请选择出库单时间" :showIcon="true" :showArrow="true" :showClear="true"
					@change="exportChange" />
			</view> -->
			<u-picker mode="time" v-model="exportFlag" :params="params" :value="exportTime" @confirm="exportChange"
				@cancle="exportTimeCancle"></u-picker>
			<!-- <view style="height: 30rpx;" /> -->
			<u-select v-show="mVisibleFlag" v-model="mshow" mode="single-column" :list="mlist"
				@confirm="materialConfirm" confirm-text='确认选择' />
			<view v-show="mVisibleFlag" style="display: flex; justify-content: space-between; margin-top: 10rpx;">
				<u-input v-model="form.material" :border="true" style="background: #FFFFFF; margin-right: 10rpx;">
				</u-input>
				<u-button @click="handleSelectMaterial" style="width: 26%;">选物料</u-button>
			</view>
			<u-select v-show="additionalFlag" mode="single-column" v-model="additionalShow" :list="additionalList"
				@confirm="additionalSelectConfirm" comfirm-text="确认选择"></u-select>
			<view v-if="additionalFlag" style="display: flex; justify-content: space-between; margin-top: 10rpx;">
				<u-input v-model="form.additionalId" :border="true" style="background: #FFFFFF; margin-right: 10rpx;">
				</u-input>
				<u-button @click="handleSelectAdditional" style="width: 26%;">选超领单</u-button>
			</view>
			<!-- <view v-if="exportAdditonFlag" style="margin-top: 10rpx;margin-bottom: 5rpx;">
				<ir-date-time-picker type="border-bottom" start="2021-1-1" end="2050-12-31" :value="exportAdditonTime"
					placeholder="请选择超领单时间" :showIcon="true" :showArrow="true" :showClear="true"
					@change="exportAdditionChange" />
			</view> -->
			<view v-if="exportAddViewFlag" @click="exportAddTimeView" style="background-color: #b3c1ff;width: 520rpx;height: 40rpx;margin-top: 10rpx;font-size: 30rpx;
			padding-left: 22rpx;">
			{{exportAdditonTime}}</view>
			<u-picker mode="time" v-model="exportAdditonFlag" :params="params" :value="exportAdditonTime" @confirm="exportAdditionChange"
				@cancle="exportAdditionCancle"></u-picker>
			<u-line-progress style="margin-top: 30rpx;" active-color="#32CD32" :percent="progress"></u-line-progress>
			<u-card style="border: 1rpx solid #0081FF;" :show-head="false" :full="true"
				:body-style="{height: '100rpx'}">
				<view class="card-body" slot="body">
					<u-row justify="between">
						<u-col :span="isAdditional ? 4 : 6">
							<view class="info-label">需拣数量</view>
							<view>{{ cntInfo.materialrequstcnt }}</view>
						</u-col>
						<u-col :span="isAdditional ? 4 : 6">
							<view class="info-label">已拣数量</view>
							<view>{{ cntInfo.materialoutcnt }}</view>
						</u-col>
						<u-col v-if="isAdditional" :span="isAdditional ? 4 : 0">
							<view class="info-label">超领单数量</view>
							<view>{{ cntInfo.materialAdditionalCnt }}</view>
						</u-col>
					</u-row>
				</view>
			</u-card>
			<view style="display: flex; justify-content: space-between; align-items: center;">
				<view style="width: 90rpx;">BOX ID</view>
				<u-input v-model="form.currentBox" :focus="focus" :border="true"
					style="background: #FFFFFF; margin: 10rpx 10rpx 0 10rpx;" @input='handlePalletInput'></u-input>
			</view>
			<u-card style="border: 1rpx solid #0081FF;" :show-head="false" :full="true"
				:body-style="{height: '150rpx'}">
				<view class="card-body" slot="body">
					<u-row gutter="8" justify="between">
						<u-col span="12">
							<view class="info-label">BOX ID</view>
							<view>{{ lastBox['box_id'] || "--" }}</view>
						</u-col>
						<u-col span="12">
							<view class="info-label">数量</view>
							<view>{{ lastBox['cnt'] || "0" }}</view>
						</u-col>
					</u-row>
				</view>
			</u-card>
			<u-table class="main-table">
				<u-tr class="u-tr">
					<u-th class="u-th">BOX ID</u-th>
					<u-th class="u-th">领料单号</u-th>
					<u-th class="u-th" width="140rpx">物料号</u-th>
					<u-th class="u-th" width="140rpx">数量</u-th>
				</u-tr>
				<u-tr class="u-tr" v-for="(item,index) in tableDisplaySource" :key="index">
					<u-td class="u-td">{{ item.box_id }}</u-td>
					<u-td class="u-td">{{ item.export_no }}</u-td>
					<u-td class="u-td" width="140rpx">{{ item.material_code }}</u-td>
					<u-td class="u-td" width="140rpx">{{ item.cnt }}</u-td>
				</u-tr>
			</u-table>
			<!-- <view style="position: fixed; bottom: 0; width: 100%; margin-left: -18rpx; padding: 10rpx;">
				<u-button type="primary" @click="handleMaterialPick">出库</u-button>
			</view> -->
		</view>
		<u-toast ref="uBankOutToast" />
		<u-modal v-model="showModal" :content="modalContent" @confirm="modalConfirm" :show-cancel-button="true"
			@cancel="modalCancel"></u-modal>
		<u-modal v-model="additionalModal" :content="additionalContent" @confirm="additionalModalConfirm"
			@cancel="additionalModalCancel" :show-cancel-button="true"></u-modal>

		<u-modal v-model="exportModal" :content="exportContent" @confirm="exportConfirm" :show-cancel-button="true"
			@cancel="exportCancel"></u-modal>
		<u-modal v-model="exportAdditionalModal" :content="exportAdditionalContent" @confirm="exportAdditionalConfirm"
			@cancel="exportAdditionalCancel" :show-cancel-button="true"></u-modal>
	</view>
</template>

<script>
	import {
		MaterialExportNoListData,
		MaterialExportCntData,
		QueryMaterialData,
		MaterialPick,
		MaterialPickCnt,
		MaterialListByExportNo,
		MaterialAdditionalExportNoListData,
		MaterialAdditionalExportCntData
	} from '../../../common/api.js'
	let timer = null;
	export default {
		data() {
			return {
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
				},
				exportViewFlag: false,
				exportTime: '',
				exportFlag: false,
				exportModal: false,
				exportContent: '',
				exportAdditonTime: '',
				exportAdditonFlag: false,
				exportAdditionalModal: false,
				exportAdditionalContent: '',
				exportAddViewFlag: false,
				form: {
					plan: '',
					material: '',
					currentBox: '',
					//超领单号
					additionalId: '',
				},
				list: [{
						name: '出库时间'
					},
					{
						name: '隐藏'
					}
				],
				background: {
					backgroundImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
				},
				loadding: true,
				show: false,
				mshow: false,
				datasource: [],
				tableDisplaySource: [],
				sourceList: [],
				dlist: [],
				mlist: [],
				mVisibleFlag: false,
				lastBox: {},
				progress: 0,
				cntInfo: {
					materialrequstcnt: 0,
					materialoutcnt: 0,
					materialAdditionalCnt: 0
				},
				exeFlag: false,
				showModal: false,
				modalContent: '',
				resReply: {},
				focus: false,
				additionalFlag: false,
				additionalShow: false,
				additionalList: [],
				additionalModal: false,
				additionalContent: '',
				isAdditional: false,
				username: ''
			}
		},
		mounted() {
			this.$nextTick(function() {
				this.loadding = false
				// timer = setInterval(() => {
				// 	uni.hideKeyboard()
				// }, 10)
			})
			this.username = uni.getStorageSync('username')
		},
		destroyed() {
			if (timer) {
				clearInterval(timer)
			}
		},
		watch: {
			additionalName(newVal) {
				if (newVal === '') {
					this.cntInfo.materialAdditionalCnt = 0
				}
			},
			planName() {
				this.additionalFlag = false
				this.isAdditional = false
				this.exportAddViewFlag = false
			}
		},
		computed: {
			additionalName() {
				return this.form.additionalId
			},
			planName() {
				return this.form.plan
			}
		},
		methods: {
			tagClick() {
				this.exportFlag = true
			},
			exportTimeView(){
				this.exportFlag = true
			},
			exportChange(e) {
				this.exportTime = e['year'] + '-' + e['month'] + '-' + e['day'] + ' ' + e['hour'] + ':' + e['minute']
				this.exportViewFlag = true

				//console.log(e)
				//console.log('出库单时间' + this.exportTime)
			},
			exportTimeCancle() {
				//this.exportTime = ''
			},
			exportAdditionChange(e) {
				this.exportAdditonTime =  e['year'] + '-' + e['month'] + '-' + e['day'] + ' ' + e['hour'] + ':' + e['minute']
				this.exportAddViewFlag = true
				//console.log('超领单时间' + this.exportAdditonTime)
			},
			exportAdditionCancle(){
				//this.exportAdditonTime = ''
			},
			exportConfirm() {
				this.exportFlag = true
			},
			exportCancel() {
				this.focus = true
			},
			exportAdditionalConfirm() {
				this.exportAdditonFlag = true
			},
			exportAdditionalCancel() {
				this.focus = true
			},
			exportAddTimeView(){
				this.exportAdditonFlag = true
			},
			confirm(data) {
				this.clearAdditionalInfo()
				if (this.datasource.length === 0 || this.datasource[0]['export_no'] === data[0]['value']) {
					this.form.plan = data[0]['value']
					this.form.material = ''
					this.cntInfo.materialoutcnt = 0
					this.mVisibleFlag = true
					MaterialListByExportNo({
						export_no: this.form.plan
					}).then(res => {
						if (res && res['mesg'] === 'success') {
							this.mlist = res['res']
							if (res['isholdno'] === 'true') {
								this.exportModal = true
								this.exportContent = '当前工单为跨月工单，是否要人工选择出库时间？'
							}

						} else {
							this.showToast("获取数据失败" + res['reason'], 'error')
						}
					})
					// MaterialExportCntData({export_no: data[0]['value'], material_code: data[1]['value']}).then(res => {
					// 	if(res && res['mesg'] === 'success') {
					// 		const result = res['res']
					// 		this.cntInfo.materialrequstcnt = result['fgcodecnt']
					// 		this.datasource.forEach(d => {
					// 			if(d['export_no'] === data[0]['value'] && d['material_code'] === data[1]['value']){
					// 				this.cntInfo.materialoutcnt += parseInt(d['cnt'])
					// 			}
					// 		})
					// 	}else{
					// 		this.showToast("获取数据失败"+res['mesg'], 'error')
					// 	}
					// })
				} else {
					this.showToast("领料单：" + this.datasource[0]['export_no'] + '未检完', 'error')
				}
			},
			materialConfirm(data) {
				this.form.material = data[0]['value']
				this.cntInfo.materialoutcnt = 0
				MaterialExportCntData({
					export_no: this.form.plan,
					material_code: this.form.material
				}).then(res => {
					if (res && res['mesg'] === 'success') {
						const result = res['res']
						this.cntInfo.materialrequstcnt = result['materialrequstcnt'] === '' ? 0 : parseInt(result[
							'materialrequstcnt'])
						this.cntInfo.materialoutcnt = result['materialoutcnt'] === '' ? 0 : parseInt(result[
							'materialoutcnt'])
						this.progress = parseFloat(((this.cntInfo.materialoutcnt / this.cntInfo
							.materialrequstcnt) * 100).toFixed(2))
						this.focus = true
					} else {
						this.showToast("获取数据失败" + res['reason'], 'error')
					}
				})
			},
			showToast(text, type) {
				this.$refs.uBankOutToast.show({
					title: text,
					type: type,
					duration: 5000,
					position: "center"
				})
			},
			handlePalletInput(value) {
				if (this.form.plan === '') {
					this.showToast("未选择领料单号", 'error')
				} else {
					if (this.exportFlag) {
						if (this.exportTime === '') {
							this.showToast("当前工单为跨月工单，出库时间不可为空", 'error')
							return
						}
					}
					if (this.exportAdditonFlag) {
						if (this.exportAdditonTime === '') {
							this.showToast("当前超选单为跨月工单，出库时间不可为空", 'error')
							return
						}
					}

					if (value.length > 6 && !this.exeFlag) {
						this.exeFlag = true
						MaterialPickCnt({
							box_id: value,
							material_code: this.form.material
						}).then(res => {
							if (res && res['mesg'] === 'success') {
								this.resReply = res['res']
								if (res['code'] === '400') {
									this.showModal = true
									this.focus = false
									this.modalContent = res['reason']
								} else if (res['code'] === '200') {
									this.handlePick()
								}
							} else {
								this.showToast("获取数据失败: " + res['reason'], 'error')
							}
							setTimeout(() => {
								this.form.currentBox = ''
								this.exeFlag = false
							}, 500)
						})
					}
				}
				setTimeout(() => {
					this.form.currentBox = ''
				}, 500)
			},
			handlePick() {
				const result = this.resReply
				const p_c = parseInt(result['cnt'])
				let totalNumber = this.cntInfo.materialrequstcnt + this.cntInfo.materialAdditionalCnt
				if ((this.cntInfo.materialoutcnt + p_c) <= totalNumber) {
					result['export_no'] = this.form.plan
					result['material_code'] = this.form.material
					//result['username'] = this.username
					if (this.cntInfo.materialAdditionalCnt != 0) {
						result['additional_export_no'] = this.form.additionalId
					}
					this.lastBox = result
					this.datasource.push(result)
					this.showToast("BOX符合，出库中...", 'success')
					MaterialPick({
						box_list: JSON.stringify(this.datasource),
						username: this.username,
						export_time: this.exportTime,
						export_addtion_time: this.exportAdditonTime
					}).then(res => {
						if (res && res['mesg'] === 'success') {
							this.showToast("出库成功", 'success')
							this.cntInfo.materialoutcnt += p_c
							this.progress = parseFloat(((this.cntInfo.materialoutcnt / this.cntInfo
								.materialrequstcnt) * 100).toFixed(2))
							this.tableDisplaySource.push(this.lastBox)
							this.datasource = []
							// this.cntInfo.materialrequstcnt = 0
							// this.cntInfo.materialoutcnt = 0
							// this.form.plan = ''
							// this.form.material = ''
							this.form.currentBox = ''
							// this.lastBox = {}
							// this.progress = 0
						} else {
							this.showToast("出库失败: " + res['reason'] || JSON.stringify(res), 'error')
							this.datasource = []
						}
						this.focus = true
					})
				} else {
					//this.showToast("超出所需数量，无法添加: " + p_c, 'error')
					//用户自行决定是否进行超领单操作
					this.additionalModal = true
					this.additionalContent = "超出所需数量，无法添加: " + p_c + "！是否需要物料超领拣配？"
					this.focus = false
				}

			},
			handleSelectFormId() {
				if (this.form.plan === '') {
					this.showToast("为保证数据量可控，请输入单号前缀", 'warning')
				} else {
					MaterialExportNoListData({
						export_no: this.form.plan
					}).then(res => {
						if (res && res['mesg'] === 'success') {
							this.dlist = res['res']
							//console.log(this.dlist)
							// this.dlist = this.sourceList.filter(sl => {return sl['value'].toLowerCase().indexOf(this.form.plan.toLowerCase()) >= 0})
							if (this.dlist.length > 0) {
								this.show = true
							} else {
								this.showToast("未查找到此前缀单号", 'warning')
							}
						} else {
							this.showToast("获取数据失败: " + res['reason'], 'error')
						}
					})
				}
			},
			handleSelectMaterial() {
				this.mshow = true
			},
			modalConfirm() {
				this.handlePick()
			},
			modalCancel() {
				this.focus = true
			},
			additionalModalConfirm() {
				this.clearAdditionalInfo()
				this.additionalFlag = true
			},
			additionalModalCancel() {
				this.clearAdditionalInfo()
				this.focus = true
			},
			additionalSelectConfirm(data) {
				this.form.additionalId = data[0]['value']
				this.cntInfo.materialAdditionalCnt = 0
				MaterialAdditionalExportCntData({
					additional_export_no: this.form.additionalId,
					material_code: this.form.material
				}).then(res => {
					if (res && res['mesg'] === 'success') {
						this.cntInfo.materialAdditionalCnt = result['additionalrequstcnt'] === '' ? 0 : parseInt(
							result['additionalrequstcnt'])
						this.isAdditional = true
						this.focus = true

						if (res['isholdno'] === 'true') {
							this.exportAdditionalModal = true
							this.exportAdditionalContent = '当前超领单为跨月工单，是否要人工选择出库时间？'
						}
					} else {
						this.showToast('获取数据失败' + res['reason'], 'error')
					}
				})
			},
			handleSelectAdditional() {
				if (this.form.additionalId === '') {
					this.showToast('为保证数据量可控，请输入单号前缀', 'warning')
				} else {
					MaterialAdditionalExportNoListData({
						additional_export_no: this.form.additionalId
					}).then(res => {
						if (res && res['mesg'] === 'success') {
							this.additionalList = res['res']
							//console.log(this.additionalList)
							if (this.additionalList.length > 0) {
								this.additionalShow = true
							} else {
								this.showToast('未查找到此前缀单号', 'warning')
							}
						} else {
							this.showToast('获取数据失败: ' + res['reason'], 'error')
						}
					})
				}

			},
			//清空上一个超拣单信息
			clearAdditionalInfo() {
				this.form.additionalId = ''
				this.cntInfo.materialAdditionalCnt = 0
			}

		}
	}
</script>

<style lang="scss" scoped>
	.content {
		margin: 5rpx 18rpx;
	}

	.card-body {
		::v-deep .u-col {
			margin-bottom: 16rpx;

			view {
				display: inline-block;
			}

			view+view {
				margin-left: 20rpx;
				color: #068bff;
			}
		}
	}

	.main-table {
		::v-deep .u-th {
			background: #0081FF !important;
			color: #ffffff;
		}

		::v-deep .u-td {
			overflow: hidden;
		}
	}

	.info-label {
		width: 140rpx;
	}
</style>
