<template>
	<view>
		<view>
			<navVar :mysNavConfig="navConfig" @onLeftClick="onLeftClick"></navVar>
		</view>
		<view style="margin: 10rpx;">
			<u-form ref="testForm">
				<u-form-item :border-bottom="false">
					<label>成本中心:</label>&nbsp;&nbsp;&nbsp;&nbsp;
					<zxzUniDataSelect filterable v-model="costName" :localdata="itemsCostName">
					</zxzUniDataSelect>
				</u-form-item>
				<u-form-item :border-bottom="false">
					<label>选择仓库:</label>&nbsp;&nbsp;&nbsp;&nbsp;
					<zxzUniDataSelect filterable v-model="ERPLOCATION" :localdata="items" @change="change">
					</zxzUniDataSelect>
				</u-form-item>
				<u-form-item :border-bottom="false">
					<label>选择库位:</label>&nbsp;&nbsp;&nbsp;&nbsp;
					<zxzUniDataSelect filterable v-model="LOCATIONNAME" :localdata="items_Location"
						:disabled="Locatiaon_state"></zxzUniDataSelect>
				</u-form-item>
				<u-form-item :border-bottom="false">
					<p>扫描条码:</p>
					<u-input :border="true" v-model="MATERIALPACKINGNAME" placeholder="请扫描条码" :focus="focusBarCode"
						@confirm="ScanFGBarCode" />
				</u-form-item>
				<br />
				<u-row>
					<u-col span="3"><label>扫描标签：</label> </u-col>
					<u-col span="9"><label>{{MATERIALPACKINGQTY}}</label> </u-col>
					<u-col span="3"><label style="text-align: right;">扫描数量：</label> </u-col>
					<u-col span="9"><label>{{MATERIALPACKINGNUMBER}}</label> </u-col>
				</u-row>
			</u-form>
			<br />
			<zb-table style="height: 450upx;" ref="zbTable" :show-header="true" :columns="column" :stripe="true"
				:fit="true" :highlight="true" :border="true" :data="BoxListInfo" @dele="del"></zb-table>
			<br />
			<view class="tabbar_bottom">
				<u-input v-if="false" v-model="opCode" />
				<uni-datetime-picker style="align-items: center;" type="date" :clear-icon="false" v-model="commitDate"
					@maskClick="maskClick" />
				<u-button @click="NoInvoiceStockIn" type="primary" :loading="loading">确定</u-button>
			</view>
			<u-modal :show="showModal" :title="titleModal" :content='contentModal'></u-modal>
		</view>
	</view>

</template>

<script>
	import zxzUniDataSelect from "@/components/zxz-uni-data-select/zxz-uni-data-select.vue"
	import navVar from "@/components/navBar/navBar.vue"
	import {
		getOpCode
	} from '@/common/api.js';
	import { cals } from '@/utils/cal'
	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'
				},
				column: [ //列
					{
						name: 'MATERIALPACKINGNAME',
						label: '标签',
						align: 'center',
						// fixed: true,
						// width: 210
					},
					{
						name: 'CHARGE',
						label: '批次'
					},
					{
						name: 'DESC_CN',
						label: '品名'
					},
					{
						name: 'MATERIALSPECNAME',
						label: '料号'
					},
					{
						name: 'SPECNAME',
						label: '规格'
					},
					{
						name: 'PHASE',
						label: '阶段'
					},
					{
						name: 'MATERIALQUANTITY',
						label: '数量'
					},
					{
						name: 'ERPFACTORY',
						label: '组织'
					},
					{
						name: 'ERPLOCATION',
						label: '仓库'
					},
					{
						name: 'LOCATIONNAME',
						label: '货位'
					},
					{
						name: 'operation',
						type: 'operation',
						label: '操作',
						renders: [{
							name: '删除',
							size: 'mini',
							type: 'warn',
							func: "dele"
						}, ]
					},
				],
				orgObject: {
					ERPFACTORY: '',
					DESCRIPTION: ''
				}, // 组织对象
				LocationName: '', //库位信息
				LOCATIONNAME: '',
				MATERIALPACKINGQTY: 0,
				MATERIALPACKINGNUMBER: 0,
				ERPFACTORY: JSON.parse(uni.getStorageSync('orgObject')).ERPFACTORY, //组织
				ERPFACTORYNAME: JSON.parse(uni.getStorageSync('orgObject')).DESCRIPTION, //组织名称
				ERPLOCATION: '', //库位
				tabH: 800, //表格的宽度
				MATERIALSPECNAME: '',
				MATERIALPACKINGNAME: '', //条码
				Locatiaon_state: false,
				CHARGE: '', //批次
				DESC_CN: '', //品名
				SPECNAME: '', //规格
				RECEIVEACTNO: '', //入库单号
				UNIT: '', //单位
				PHASE: '', //阶段
				QTY: '', //数量
				background: {
					backgroundImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
				}, //返回按钮的样式
				colors: ['#007aff', '#4cd964', '#dd524d'],
				styleType: 'button',
				current: 0,
				BoxListInfo: [], //后端传回来的绑定表格的数据
				colorIndex: 0,
				activeColor: '#007aff',
				loading: false,
				scanData: [], //已扫描箱
				barCode: "", //条码
				DURABLENAMECode: "", //卷芯
				focusBarCode: false, //焦点是否被选中
				focusShipRequest: true, //默认焦点在单号
				siteName: "",
				userId: "",
				items: [],
				items_Location: [],
				commitDate: '',
				opCode: '',
				costName: '',
				itemsCostName: [{text: '财务部中心',value: '1010109040'}]
			}
		},

		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
				}
			})
			this.orgObject = JSON.parse(uni.getStorageSync('orgObject'))
			this.getTimeData();
			this.getERPLocation();
			this.getCostCenter();
			// let Things = 20
			// for (var i = 0; i < Things; i++) {
			// 	this.BoxListInfo.push({aa:"1"}) 
			// }	
		},
		methods: {
			getTimeData() {
				var year = new Date().getFullYear(); //年
				if (year < 1900) year = year + 1900;
				var month = new Date().getMonth() + 1; //月
				if (month < 10) month = '0' + month;
				var day = new Date().getDate(); //日
				if (day < 10) day = '0' + day;
				const calendar1 = year + '-' + month + '-' + day
				this.commitDate = calendar1
			},
			maskClick(e) {
				console.log('maskClick事件:', e);
			},
			getCostCenter(){
				let erpFactory = JSON.parse(uni.getStorageSync('loginInfoObject')).org
				this.$MyRequest('/CostCenter/getCostCenter',{erpFactory: erpFactory},'GET').then(res => {
					this.itemsCostName = res.data.data.map(item => ({
						text: item.costName,
						value: item.costCode,
					}));
				})
			},
			onLeftClick() {
				uni.showModal({
					title: this.titleModal, // 模态框标题
					content: this.contentModal, // 模态框内容
					showCancel: true, // 是否显示取消按钮，默认为true
					cancelText: '取消', // 取消按钮的文字
					confirmText: '确定', // 确定按钮的文字
					success(res) {
						if (res.confirm) {
							uni.navigateBack({
								delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页
							});
							console.log('用户点击了确定');
							// 执行确认后的逻辑
						} else if (res.cancel) {
							console.log('用户点击了取消');
							// 执行取消后的逻辑
						}
					}
				})
			},
			del(row, index) {
				this.BoxListInfo.splice(index, 1)
				this.MATERIALPACKINGNUMBER = this.MATERIALPACKINGNUMBER - row.MATERIALQUANTITY
				this.MATERIALPACKINGQTY = this.MATERIALPACKINGQTY - 1
				this.$showMessage("删除成功")
			},
			change(e) {
				this.ERPLOCATION = e.value;
				this.LOCATIONNAME = ""
				this.Huowei = e.Huowei
				if (e.Huowei == 'Y') {
					this.Locatiaon_state = false
					this.getLocationName();
				} else {
					this.$showMessage(e.text + "仓库没有启用货位管理")
					this.Locatiaon_state = true
					this.focusBarCode = true
				}
			},
			//获取焦点的公共方法
			getfocus(nextfocus) {
				this.initfocus()
				this[nextfocus]
				this.$nextTick(() => { //vue是数据全部修改后才进行的视图更新，哪nextTick函数就是为了拿到最新的数据，还不懂的可以去百度
					this[nextfocus] = true
				})
			},
			getERPLocation() {
				this.items = [];
				this.$MyRequest('/api/storage/getERPLocation', {
					ERPFACTORYNAME: this.ERPFACTORY
				}).then(res => {
					if (res.data.success) {
						for (let i = 0; i < res.data.resultObj.length; i++) {
							var _Arr = res.data.resultObj[i];
							this.items.push({
								text: _Arr.DESCRIPTION,
								value: _Arr.ERPLOCATIONNAME,
								Huowei: _Arr.USE_LOCATION,
							});
						}
					} else {
						this.$showMessage(res.data.message)
					}
				});
			},
			getLocationName() {
				this.items_Location = []
				if (this.ERPLOCATION != '') {
					this.$MyRequest('/api/storage/getLocationNameForERPLocation', {
						ERPLocation: this.ERPLOCATION
					}).then(res => {
						if (res.data.success) {
							for (let i = 0; i < res.data.resultObj.length; i++) {
								var _Arr = res.data.resultObj[i];
								this.items_Location.push({
									text: _Arr.DESCRIPTION,
									value: _Arr.STORAGENAME
								});
							}
						} else {
							this.$showMessage(res.data.message)
						}
						this.focusBarCode = true
						this.focusShipRequest = false
					}).catch(err => {
						this.$showMessage(err)
					});
				} else {
					this.$showMessage("请先选择仓库")
				}

			},
			async ScanFGBarCode() {
				this.focusBarCode = false;
				if (this.BoxListInfo.some(box => box.MATERIALPACKINGNAME === this.MATERIALPACKINGNAME)) {
					this.$showMessage("改标签已扫描，请不要重复扫描！");
					this.$nextTick(() => {
						this.MATERIALPACKINGNAME = ""
						this.focusBarCode = true
						this.focusShipRequest = false
					})
					this.$playFail()
					return;
				}
				// if ((this.LOCATIONNAME == null || this.LOCATIONNAME == "") && (this.Huowei == 'Y')) {
				// 	this.$showMessage("请选择货位！");
				// 	this.$nextTick(() => {
				// 		this.MATERIALPACKINGNAME = ""
				// 		this.focusBarCode = true
				// 		this.focusShipRequest = false
				// 	})
				// 	this.$playFail()
				// 	return;
				// }
				if (this.ERPFACTORY == null || this.ERPFACTORY == "") {
					this.$showMessage("请选择组织！");
					this.$nextTick(() => {
						this.MATERIALPACKINGNAME = ""
						this.focusBarCode = true
						this.focusShipRequest = false
					})
					this.$playFail()
					return;
				}
				if (this.ERPLOCATION == null || this.ERPLOCATION == "") {
					this.$showMessage("请选择仓库！");
					this.$nextTick(() => {
						this.MATERIALPACKINGNAME = ""
						this.focusBarCode = true
						this.focusShipRequest = false
					})
					this.$playFail()
					return;
				}
				var barCodeArr = this.MATERIALPACKINGNAME.split("|");
				// 470110856|1|C|75mm*1000m|SHBP01JT1202305240009|20230524|11|75
				if (barCodeArr.length < 7) {
					this.$showMessage("条码规则不符合需求!")
					this.$nextTick(() => {
						this.MATERIALPACKINGNAME = ""
						this.focusBarCode = true
						this.focusShipRequest = false
					})
					this.$playFail()
					return;
				}
				// this.loading = true;
				this.MATERIALPACKINGQTY = 0
				this.MATERIALPACKINGNUMBER = 0
				await this.$MyRequest('/api/NoInvoice/getBarCode', {
					MATERIALPACKINGNAME: this.MATERIALPACKINGNAME,
					LOCATIONNAME: this.LOCATIONNAME,
					ERPFACTORY: this.ERPFACTORY,
					ERPLOCATION: this.ERPLOCATION,
					CREATEUSER: this.userId
				}).then(res => {
					if (res.data.success) {
						var _Arr = res.data.resultObj;
						// this.MATERIALPACKINGNAME = _Arr[0].MATERIALPACKINGNAME;
						// this.CHARGE = _Arr[0].CHARGE;
						// this.MATERIALSPECNAME = _Arr[0].MATERIALSPECNAME;
						// this.SPECNAME = _Arr[0].SPECNAME;
						// this.DESC_CN = _Arr[0].DESC_CN;
						// this.PHASE = _Arr[0].PHASE;
						// console.log(new Set(this.BoxListInfo))
						this.BoxListInfo.push(...res.data.resultObj);
						this.MATERIALPACKINGQTY = this.BoxListInfo.length
						for (let i = 0; i < this.BoxListInfo.length; i++) {
							this.MATERIALPACKINGNUMBER = (cals.add(this.MATERIALPACKINGNUMBER,this.BoxListInfo[i].MATERIALQUANTITY)).toNumber()
						}
						// this.loading = false;
						this.$nextTick(() => {
							this.MATERIALPACKINGNAME = ""
							this.focusBarCode = true
							this.focusShipRequest = false
						})
						try {
							Vue.prototype.$playSuccess()
						} catch (e) {}
					} else {
						// this.loading = false;
						this.$showMessage(res.data.message)
						this.$nextTick(() => {
							this.MATERIALPACKINGNAME = ""
							this.focusBarCode = true
							this.focusShipRequest = false
						})
						this.$playFail()
					}

				}).catch(err => {
					this.loading = false;
					this.$showMessage(err)
					this.$nextTick(() => {
						this.MATERIALPACKINGNAME = ""
						this.focusBarCode = true
						this.focusShipRequest = false
					})
					this.$playFail()
				});
			},

			/**
			 * 入库审核
			 */
			NoInvoiceStockIn() {
				console.log(this.commitDate)
				if (this.BoxListInfo.length <= 0) {
					this.$showMessage("入库列表为空")
					return
				}
				this.loading = true;
				this.focusBarCode = false
				this.BoxListInfo.map(item => {
					if (item.hasOwnProperty("key")) {
						delete item.key
					}
				})
				getOpCode({
					opcode: this.opCode,
					user: this.userId
				}).then((res) => {
					this.$MyRequest('/api/NoInvoice/QTRCommit', {
						boxList: this.BoxListInfo,
						user: this.userId,
						commitDate: this.commitDate,
						opcode: this.opCode,
						qtc: 'Z06',
						costName: this.costName
					}).then(res => {
						if (res.data.success) {
							this.$showMessage(res.data.message)
							this.loading = false;
							this.MATERIALPACKINGQTY = 0
							this.MATERIALPACKINGNUMBER = 0
							this.resetValue();
						} else {
							this.loading = false;
							this.$showMessage(res.data.message)
						}
						this.$nextTick(() => {
							this.focusBarCode = true
							this.focusShipRequest = false
						})
					}).catch(err => {
						this.loading = false;
						this.$showMessage(err)
						this.$nextTick(() => {
							this.focusBarCode = true
							this.focusShipRequest = false
						})
					});
				})

			},

			resetValue() {
				this.opCode = "";
				this.MATERIALPACKINGNAME = "";
				this.LocationName = "";
				// this.ERPFACTORY = "";
				this.ERPLOCATION = "";
				this.BoxListInfo = [];
				this.RECEIVEACTNO = "";
				this.MATERIALSPECNAME = "";
				this.PHASE = "";
				this.SPECNAME = "";
				this.DESC_CN = "";
				this.CHARGE = "";
				this.LOCATIONNAME = "";
				this.costName = "";
			}
		}
	}
</script>
<style>
	.btn-bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		left: 0;
	}
</style>
<style lang="scss">
	switch {
		color: #FFCC33;
	}

	/* 基础样式 */
	.picker {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		width: 100%;
		/* 根据需要调整宽度 */
	}

	.row {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10px;
		/* 行与行之间的间距 */
	}

	.col {
		flex: 1;
		/* 使得每列占据相等的空间 */
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	label {
		// font-weight: bold;
		/* 标签加粗 */
		margin-bottom: 5px;
		/* 标签和值之间的间距 */
	}

	.value {
		/* 值的样式，可以根据需要调整 */
	}
</style>
