<template>
	<view class="create-container">
		<custom-nav-bar :left="true" title="调货新增">
			<view class="fixed">
				<view align="right" class="icon iconfont icon-scan" @click="toQRCode"></view>
				<view align="right" class="icon iconfont icon-NFC1" @click="nfc"></view>
				<view align="right" class="iconfont icon-jia icon" @click="add"></view>
			</view>
		</custom-nav-bar>
		<uni-section title="基础信息" type="line">
			<u--form labelPosition="left" :model="briefForm" :rules="rules" ref="form">
				<u-line color="#D2D2D2"></u-line>
				<u-form-item label="调货仓库" prop="storageOutName" required>
					<u--input @click="showStorageOut=true" v-model="briefForm.storageOutName" border="none" disabled
						placeholder="请选择调货仓库" suffixIcon="arrow-right"></u--input>
				</u-form-item>
				<u-form-item label="接收仓库" prop="storageInName" required>
					<u--input @click="showStorageIn=true" v-model="briefForm.storageInName" border="none" disabled
						placeholder="请选择接收仓库" suffixIcon="arrow-right"></u--input>
				</u-form-item>
				<u-line color="#D2D2D2"></u-line>
				<u-form-item class="form-item" label="调货日期" prop="billDate" labelWidth="100px" required>
					<uni-datetime-picker v-model="briefForm.billDate" type="date" class="custom-input" />
				</u-form-item>
				<u-line color="#D2D2D2"></u-line>
				<u-form-item class="form-item" label="调货人" prop="operUser" labelWidth="100px" required>
					<u--input v-model.trim="briefForm.operUser" border="none" placeholder="" disabled
						class="custom-input"></u--input>
				</u-form-item>
				<u-line color="#D2D2D2"></u-line>
			</u--form>
		</uni-section>
		<uni-section title="明细清单" type="line">
			<u-line color="#D2D2D2"></u-line>
			<view class="item-container" v-for="item in dataList">
				<view style="display: flex; align-items: center; justify-content: space-between;">
					<view class="flex-text" style="margin: 15px;">
						<view class="flex-text-one" style="color: black;">
							{{ item.deviceCode }}：{{ item.deviceTypeName }}
						</view>
					</view>
					<view style="margin-right: 5px;">
						<u-button type="success" text="删除" @click="deleteDetail(item)" />
					</view>
				</view>
				<u-gap height="1" bgColor="#D2D2D2"></u-gap>
			</view>
		</uni-section>
		<view class="buttons">
			<u-button type="success" @click="submit">确认</u-button>
			<u-button @click="cancel">取消</u-button>
		</view>
		<u-action-sheet :show="showStorageIn" :actions="storageInData" title="接收仓库" description=""
			@close="showStorageIn = false" @select="onStorageInSelect"></u-action-sheet>
		<u-action-sheet :show="showStorageOut" :actions="storageOutData" title="调货仓库" description=""
			@close="showStorageOut = false" @select="onStorageOutSelect"></u-action-sheet>
		<u-modal title="手动输入" :show="showDeviceModal" showCancelButton buttonReverse height="300px"
			@confirm="confirmDevice" @cancel="cancelDeviceInfo">
			<view class="slot-content">
				<u--form labelPosition="left" :model="deviceInfoData" ref="formDevice">
					<u-form-item label="编号" prop="deviceCode" labelWidth="100px" required>
						<u--input v-model="deviceInfoData.deviceCode" placeholder="请输入编号"></u--input>
					</u-form-item>
				</u--form>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import store from "@/store"
	import {
		initNFC,
		closeNFC,
		//类型
		setNfcType
	} from '@/utils/nfc.js';
	import {
		getDeviceList,
		getPdaDeviceList
	} from "@/api/iot/device"
	import {
		getDeviceBillInfo,
		addDeviceBill,
		updateDeviceBill
	} from "@/api/iot/deviceBill"
	import {
		getDeviceStorageUserListByUserId,
		getDeviceStorageList
	} from "@/api/iot/deviceStorageUser"
	export default {
		data() {
			return {
				user: store.state.user.user,
				type: "add",
				billId: null,
				form: null,
				formDevice: null,
				dataList: [],
				briefForm: {},
				addType: 1,
				showDeviceModal: false,
				showStorageIn: false,
				showStorageOut: false,
				showDevicePda: false,
				storageInData: [],
				storageOutData: [],
				devicePdaData: [],
				deviceInfoData: {
					deviceCode: null
				},
				rules: {
					storageOutName: {
						type: "string",
						required: true,
						message: "调货仓库不能为空",
						trigger: ["blur", "change"]
					},
					storageInName: {
						type: "string",
						required: true,
						message: "接收仓库不能为空",
						trigger: ["blur", "change"]
					},
					operUser: [{
						type: "string",
						required: true,
						message: "调货人不能为空",
						trigger: ["blur", "change"]
					}],
					billDate: [{
						type: "string",
						required: true,
						message: "调货日期不能为空",
						trigger: ["blur", "change"]
					}]
				},
				editFlag: false
			}
		},
		created() {
			this.reset();
		},
		onLoad(options) {
			initNFC(({
				code,
				data,
				message
			}) => {
				if (code !== 200) {
					uni.$u.toast(message);
					return;
				}
				switch (data.type) {
					case 'cardNo':
						if (this.addType == 2) {
							this.getDeviceInfo(data.id);
						}
						break;
					case 'read':
						uni.$u.toast(data.text);
						break;
					case 'write':
						uni.$u.toast(message);
						break;
					default:
						uni.$u.toast("未知属性");
				}
			});
			if (options) {
				if (options.type) {
					this.type = options.type;
				}
				if (options.id) {
					this.billId = options.id;
				}
			}
			this.getDeviceStorageUserList();
			this.getDeviceStorageData();
			this.getPdaDeviceData();
			if (this.type == "edit") {
				this.getDeviceBill();
			}
		},
		onShow() {},
		methods: {
			reset() {
				this.briefForm = {
					billId: null,
					billTypeId: 2005,
					billCode: null,
					storageInId: null,
					storageInName: null,
					devicePdaId: null,
					devicePdaCode: null,
					sourceBillTypeId: null,
					storageOutType: null,
					sourceBillId: null,
					sourceBillCode: null,
					billDate: this.getNowFormatDate(),
					billTime: null,
					sourceBillId: null,
					sourceBillTypeId: null,
					storageOutId: null,
					operUser: this.user.userName,
					operUserId: this.user.userId,
					status: 0,
					billTime: null,
					deviceBillWmsVos: []
				};
			},
			//删除明细
			deleteDetail(item) {
				plugin.modal.confirm("确定删除吗?").then(res => {
					let index = this.dataList.findIndex(x => x.deviceId == item.deviceId);
					if (index != -1) {
						this.dataList.splice(index, 1);
					}
					if (this.type == "edit") {
						//明细时删除明细及更改设备仓库id及在库状态
						deleteDeviceBillWms(item.billDetailId)
							.then(res => {})
					}
				})
			},
			onStorageInSelect(e) {
				this.briefForm.storageInId = e.id
				this.briefForm.storageInName = e.name
			},
			onStorageOutSelect(e) {
				this.briefForm.storageOutId = e.id
				this.briefForm.storageOutName = e.name
			},
			confirmDevice() {
				this.addType = 1;
				this.showDeviceModal = false;
				this.getDeviceInfo(this.deviceInfoData.deviceCode);
			},
			cancelDeviceInfo() {
				this.showDeviceModal = false;
			},
			//提交
			submit() {
				if (this.type == "edit") {
					this.$refs["form"]
						.validate()
						.then(res => {
							//修改接口
							this.briefForm.deviceBillWmsVos = this.dataList;
							updateDeviceBill(this.briefForm).then(res => {
								uni.$u.toast("修改成功")
								this.cancel();
							})
						})
						.catch(errors => {
							uni.$u.toast("请补充摘要信息")
						})
				} else {
					// 新增用户
					this.$refs["form"]
						.validate()
						.then(res => {
							//新增接口
							this.briefForm.deviceBillWmsVos = this.dataList;
							addDeviceBill(this.briefForm).then(res => {
								uni.$u.toast("新增成功" + res.msg);
								this.cancel();
							})
						})
						.catch(errors => {
							uni.$u.toast("请补充摘要信息")
						})
				}
			},
			//返回
			cancel() {
				uni.navigateBack({
					delta: 1
				})
				uni.$emit("cancelpage", "close")
			},
			//扫码
			toQRCode() {
				this.addType = 1;
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module")
				mpaasScanModule.mpaasScan({
					// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
					'scanType': ['qrCode', 'barCode'],
					// 是否隐藏相册，默认false不隐藏
					'hideAlbum': false,
					//ios需要设置这个参数，只支持中英文 zh-Hans、en，默认中文                       
					'language': 'en',
					//相册选择照片识别错误提示(ios)
					'failedMsg': '未识别到二维码，请重试',
					//Android支持全屏需要设置此参数
					'screenType': 'full'
				}, (ret) => {
					if (ret.resp_code == 1000) {
						this.getDeviceInfo(ret.resp_result);
					}
				})
			},
			//选择签收单
			onselectBillCode: function() {
				uni.navigateTo({
					url: '/pages/retrace/selectDeviceBill?billTypeId=2002'
				});
			},
			//获取扫码或nfc查询设备
			getDeviceInfo(code) {
				let query = {};
				if (this.addType == 1) {
					query.deviceCode = code;
				} else {
					query.nfcCode = code;
				}
				getDeviceList(query).then(res => {
					if (res && res.data && res.data.length) {
						let index = this.dataList.findIndex(x => x.deviceId == res.data[0].id);
						if (index == -1) {
							let addObj = {}
							addObj.deviceId = res.data[0].id;
							addObj.deviceCode = res.data[0].deviceCode;
							addObj.deviceTypeId = res.data[0].deviceTypeId;
							addObj.deviceTypeName = res.data[0].deviceTypeName;
							this.dataList.push(addObj);
						}
					} else {
						uni.$u.toast("未查询到设备" + code)
					}
				})
			},
			getDeviceStorageUserList() {
				getDeviceStorageUserListByUserId().then(res => {
					if (res && res.data) {
						this.storageInData = res.data.map(
							item => {
								return {
									name: item.storageName,
									id: item.id,
									item: item
								}
							});
					}
				})
			},
			//获取调货仓库
			getDeviceStorageData() {
				getDeviceStorageList().then(res => {
					console.log(res)
					if (res && res.data) {
						this.storageOutData = res.data.map(
							item => {
								return {
									name: item.storageName,
									id: item.id,
									item: item
								}
							});
					}
				})
			},
			//获取手持机
			getPdaDeviceData() {
				getPdaDeviceList().then(res => {
					if (res && res.data) {
						this.devicePdaData = res.data.map(
							item => {
								return {
									name: item.deviceCode,
									id: item.id,
									item: item
								}
							});
					}
				})
			},
			getDeviceBill() {
				getDeviceBillInfo(this.billId).then(res => {
					if (res && res.data) {
						this.briefForm = res.data;
						if (this.briefForm) {
							this.dataList = this.briefForm.deviceBillWmsVos;
						}
					}
				})
			},
			//获取当前日期
			getNowFormatDate() {
				let date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let d = date.getDate();
				if (month < 10) {
					month = "0" + month;
				}
				if (d < 10) {
					d = "0" + d;
				}
				return year + "-" + month + "-" + d;
			}
		}
	}
</script>
<style lang="scss">
	.create-container {
		background-color: #FFF;

		::v-deep .u-form {
			padding: 10px;

			.u-form-item__body {
				margin-bottom: 10px;
				margin-left: 10px;
				padding: 0;

				.u-form-item__body__left {
					width: 80px !important;
				}

				.u-input--square {
					height: 35px;
					padding: 0px 10px !important;
				}
			}

		}

		.buttons {
			margin: 10px 50px;
			display: flex;
			justify-content: space-between;

			button {
				margin: 0px 20px;
			}
		}
	}
</style>