<template>
	<view class="nvue-page-root">
		<view class="head">
			<view class="header-wrap">
				<view class="index-header">
					<uni-icons class="fanhui" custom-prefix="iconfont" type="icon-fanhui"
						@click="leftClick"></uni-icons>
					<view class="input-wrap">
						<text class="iconfont">批次管理</text>
					</view>
					<view class="map-wrap" @click="rightClick">
						<uni-icons class="lanya" custom-prefix="iconfont" type="icon-lanya"></uni-icons>
					</view>
				</view>
			</view>
			<view class="blank"></view>
		</view>
		<view class="uni-common-mt" style="padding: 5px;">
			<view class="uni-form-item uni-column">
				<view class="uni-input-wrapper" style="margin: 5px auto;">
					<text class="uni-form-item__title">批次</text>
					<input class="uni-input" :value="query_code" @input="hideKeyboard" />
				</view>
				<view class="uni-input-wrapper table-title">
					<view class="tab-tr" style="width: 40%;">批次</view>
					<view class="tab-tr" style="width: 25%;font-size: 13px;">已入/待入(吨)</view>
					<view class="tab-tr" style="width: 20%;">状态</view>
					<view class="tab-tr-end" style="width: 15%;">操作</view>
				</view>
				<view style="min-height:335px;overflow-y:auto;max-height:335px">
					<view class="uni-input-wrapper table-data" v-for="(item,index) in tableData" :key="index">
						<view class="tab-tr"
							style="width: 40%;text-align: left;word-break: break-all;word-wrap: break-word;line-height: initial;">
							{{item.name}}
						</view>
						<view class="tab-tr" style="width: 25%; overflow-wrap: break-word; ">
							{{item.in_num}}/{{item.wait_num}}
						</view>
						<view class="tab-tr" style="width: 20%; overflow-wrap: break-word; ">{{item.default}}</view>
						<view class="tab-tr-end"
							style="width: 15%; overflow-wrap: break-word;color: #0039a6;font-size: 13px;"
							@click="SelectProduct(item)">设为默认</view>
					</view>
				</view>
				<view class="uni-input-wrapper button-sp-area">
					<button type="primary" plain="true" @click="batchGetNew()">添加</button>
				</view>
			</view>
		</view>
		<view>
			<!-- 提示窗示例 -->
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog type="info" cancelText="取消" confirmText="确定" title="提示" :content="tips"
					@confirm="SelectConfirm" @close="dialogClose"></uni-popup-dialog>
			</uni-popup>
		</view>
		<!-- 引入自定义模态框 -->
		<custom-modal :visible="addBatchModalVisible">
			<!-- 模态框的内容 -->
			<view>
				<text>提示:创建新批次,会把上一批次待入库作废, 并把新批次设置为当前默认批次,请慎重操作</text>
				<view class="uni-input-wrapper" style="margin: 5px auto;">
					<text class="uni-form-item__title" style="width: 30%;">新批次号</text>
					<input class="uni-input" :value="newBatch" />
				</view>

				<br><br>
				<view>
					<button class="mini-btn" size="mini" @click="closeAddBatchModal"
						style="width: 50%;float: left;">关闭</button>
					<button class="mini-btn" type="primary" size="mini" @click="batchAdd"
						style="width: 50%;">确定</button>
				</view>
			</view>
		</custom-modal>
	</view>
</template>
<script>
	import CustomModal from "@/components/CustomModal/CustomModal.vue";
	const SpeechTTS = uni.requireNativePlugin('MT-TTS-Speech');
	const modal = uni.requireNativePlugin('modal');

	let _this = null;
	import {
		mapGetters,
		mapActions
	} from 'vuex';
	import {
		GET_INFODATA,
		GET_CONNECTBLEDATA
	} from "@/store/gettersType.js";
	import {
		SET_CONNECTBLEDATA
	} from '@/store/actionsType.js';
	var reqRootUrl = plus.storage.getItem("reqRootUrl");
	const printModule = uni.requireNativePlugin('PrintModuleCPCL');
	export default {
		components: {
			CustomModal
		},
		data() {
			return {
				url: '',
				tableData: [],
				query_code: "",
				code: "",
				tips: "",
				addBatchModalVisible: false,
				newBatch: "",
				sn: "",
				name: ""
			}
		},
		methods: {
			leftClick: function() {
				setTimeout(() => {
					uni.navigateBack();
					// uni.redirectTo({
					// 	url: '/pages/sample/group',
					// })
				}, 30);
				// this.$emit('change', this.value)
			},
			onLoad() {
				this.platform = uni.getSystemInfoSync().platform
				// #ifdef APP-PLUS-NVUE
				this.isNvue = true
				// #endif
				_this = this;
				setTimeout(() => {
					this.getList();
					this.speak_init();
				}, 350);
			},
			speak_init() {
				// console.log('>> TTS:init...')
				SpeechTTS.init((callback) => {
					// SpeechTTS.setEngine("com.iflytek.speechcloud"); // 设置引擎 
					SpeechTTS.setEngine("com.google.android.tts"); // 设置引擎 
					// console.log('>> tts: init success');
					SpeechTTS.setPitch(50); // 设置语调 setPitch(num) 0-100, 默认 50
					SpeechTTS.setSpeed(65); // 设置语速 setSpeed(num) 0-100, 默认 50
				});
				SpeechTTS.onDone((res) => {
					// console.log(">> tts: play end " + res)
				});
			},
			onShow() {
				uni.hideKeyboard();
				setTimeout(() => {
					// this.getList();
				}, 350);
			},
			SelectProduct(item) {
				this.code = item.code
				this.sn = item.sn
				this.name = item.name
				this.tips = "确定设置" + item.name + "为当前默认?";
				this.$refs.alertDialog.open()
			},
			dialogClose() {
				console.log('点击关闭')
				this.$refs.alertDialog.close()
			},
			SelectConfirm() {
				setTimeout(() => {
					setTimeout(() => {
						uni.request({
							url: reqRootUrl + '/wms/api',
							method: 'POST',
							headers: {
								'Content-Type': 'application/json'
							},
							data: JSON.stringify({
								"method": "BatchUpdateDefault",
								"param": {
									[_this.sn]: {
										"default": true
									}
								}
							}),
							success: (ret) => {
								uni.setStorageSync("batch", _this.name)
								_this.getList()
							},
							fail: (err) => {
								// console.log('request fail', err);
							},
							complete: () => {
								// console.log('complete');
							}
						})
					}, 30);
					// 关闭窗口后，恢复默认内容
					this.$refs.alertDialog.close()
				}, 30)
			},
			rightClick: function() {
				setTimeout(() => {
					uni.navigateBack();
					// uni.navigateTo({
					// 	url: '/pages/sample/richAlert',
					// })
				}, 30);
				// this.$emit("rightClick")
			},

			containerAdd() {
				setTimeout(() => {
					uni.request({
						url: reqRootUrl + '/wms/api',
						method: 'POST',
						headers: {
							'Content-Type': 'application/json'
						},
						data: JSON.stringify({
							"method": "ContainerAdd",
							"param": {
								"num": "1"
							}
						}),
						success: (ret) => {
							_this.getList()
						},
						fail: (err) => {
							// console.log('request fail', err);
						},
						complete: () => {
							// console.log('complete');
						}
					})
				}, 30);
			},
			printCode: function(code) {
				this.handlePrint(code)
			},
			hideKeyboard: function(event) {
				let Value = event.detail.value;
				Value.trim();
				this.query_code = Value;
				_this.ContainerQuery();
			},

			ContainerQuery() {
				if (this.query_code !== "" && this.query_code !== null && this.query_code !== undefined) {
					uni.request({
						url: reqRootUrl + '/wms/api',
						method: 'POST',
						headers: {
							'Content-Type': 'application/json'
						},
						data: JSON.stringify({
							"method": "BatchQuery",
							"param": {
								"code": this.query_code,
								"model": "regex"
							}
						}),
						success: (ret) => {
							let rows = ret.data.data;
							if (!_this.isEmpty(rows)) {
								for (var i = 0; i < rows.length; i++) {
									let str = ""
									if (rows[i]["default"]) {
										str = "当前默认"
									}
									rows[i]["default"] = str;
								}
							}
							this.tableData = rows;
						},
						fail: (err) => {
							// console.log('request fail', err);
						},
						complete: () => {
							// console.log('complete');
						}
					})
				} else {
					_this.getList()
				}
			},

			getList() {
				uni.request({
					url: reqRootUrl + '/wms/api',
					method: 'POST',
					headers: {
						'Content-Type': 'application/json'
					},
					data: JSON.stringify({
						"method": "BatchQuery",
						"param": {}
					}),
					success: (ret) => {
						let rows = ret.data.data;
						if (!_this.isEmpty(rows)) {
							for (var i = 0; i < rows.length; i++) {
								let str = ""
								if (rows[i]["default"]) {
									str = "当前默认"
								}
								rows[i]["default"] = str;
							}
						}
						this.tableData = rows;
					},
					fail: (err) => {
						// console.log('request fail', err);
					},
					complete: () => {
						// console.log('complete');
					}
				})
			},
			batchGetNew() {
				uni.request({
					url: reqRootUrl + '/wms/api',
					method: 'POST',
					headers: {
						'Content-Type': 'application/json'
					},
					data: JSON.stringify({
						"method": "BatchGetNew",
						"param": {}
					}),
					success: (ret) => {
						if (ret.data.ret === "ok") {
							this.newBatch = ret.data.data
							this.addBatchModalVisible = true
							uni.setStorageSync("batch", _this.name)
						}
					},
					fail: (err) => {
						// console.log('request fail', err);
					},
					complete: () => {
						// console.log('complete');
					}
				})
			},

			closeAddBatchModal() {
				// 关闭模态框  
				this.addBatchModalVisible = false;
			},
			batchAdd() {
				let batch = uni.getStorageSync("batch")
				console.log("AAA ", _this.newBatch, batch)
				// if (_this.newBatch === "" || _this.newBatch === batch) {
				// 	_this.alertInfo("添加失败，请填写新的批次号")
				// 	return;
				// }
				uni.request({
					url: reqRootUrl + '/wms/api',
					method: 'POST',
					headers: {
						'Content-Type': 'application/json'
					},
					data: JSON.stringify({
						"method": "BatchAdd",
						"param": {
							"name": _this.newBatch,
						}
					}),
					success: (ret) => {
						if (ret.data.ret === "ok") {
							_this.batch = _this.newBatch;
							_this.newBatch = "";
							uni.setStorageSync("batch", _this.batch)
							_this.addBatchModalVisible = false
							_this.alertInfo("创建新批次成功！")
						}
					},
					fail: (err) => {
						// console.log('request fail', err);
					},
					complete: () => {
						// console.log('complete');
					}
				})
				// uni.setStorageSync(key, value)
				// uni.getStorageSync("batch")
				// uni.removeStorageSync(key)
			},
			// 打印机相关
			...mapActions([SET_CONNECTBLEDATA]),
			// 连接打印机
			confirm_bluetooth(item) {
				// let {
				// 	name,
				// 	mac
				// } = item;
				uni.showLoading({
					title: "连接中...",
					mask: true
				})
				let mac = item.mac;
				try {
					printModule.connectionBT({
						'address': mac
					}, result => {
						const msg = JSON.stringify(result);
						this.result = JSON.parse(msg).result;
						modal.toast({
							message: msg,
							duration: 6
						});
						uni.hideLoading()
						printModule.setDisConnectBTListener((ret) => {
							modal.toast({
								message: '蓝牙断开',
								duration: 6
							});
						})
					})
				} catch (e) {
					console.log(e)
				}
			},
			//搜索没匹配的蓝牙设备
			search_bluetooth(address) {
				let _this = this;
				//检查蓝牙是否开启
				this.$check_bluetooth_open().then(ores => {
					if (ores) {
						console.log(ores);
						//搜索蓝牙
						_this.$search_bluetooth().then(bres => {
							console.log(bres);
							if (bres.code) {
								_this.$search_pipei().then(pres => {
									console.log(pres);
								})
							}
						})
					}
				})
			},

			handlePrint(code) {
				printModule.printAreaSize({
					'height': '400',
					'number': '1'
				}, result => {})
				printModule.printBarCode({
					'x_pos': '0',
					'y_pos': '20',
					'code_type': '128',
					'ratio': '1',
					'height': '250',
					'width': '1',
					'rotation': 'BARCODE',
					'undertext': true,
					'number': '4',
					'offset': '5',
					"textAlign": "right",
					'code_data': code
				});
				printModule.printForm()
				printModule.print()
			},
			closeBT() {
				printModule.closeBT();
			},
			isEmpty(obj) {
				return typeof obj === undefined || obj == null || obj === "" || obj === "000000000000000000000000" || obj
					.length === 0;
			},
			alertInfo(str) {
				SpeechTTS.speak({
					text: str,
				});
				modal.toast({
					message: str,
					duration: 6,
				});
			},
		},
	}
</script>

<style scoped>
	.nvue-page-root {
		background-color: #F8F8F8;
		padding-bottom: 0px;
	}

	.uni-form-item__title {
		margin: 5px auto;
	}

	.uni-input-wrapper {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		flex-wrap: nowrap;
		background-color: #FFFFFF;
	}

	.uni-input {
		height: 28px;
		line-height: 28px;
		font-size: 15px;
		padding: 1px;
		flex: 1;
		border-radius: 5px;
		border: 1px solid #cfdadd;
		background-color: #FFFFFF;
	}

	.mini-btn {
		height: 30px;
		padding-left: 1px;
		padding-right: 1px;
	}

	.uni-eye-active {
		color: #007AFF;
	}

	.table-title {
		background-color: aliceblue;
		font-weight: 700;
		margin-top: 10px;
		height: 40px;
	}

	.table-data {
		background-color: aliceblue;
		font-weight: 700;
		margin-top: 1px;
		height: 40px;
	}

	.tab-tr {
		width: 25%;
		height: 50px;
		line-height: 25px;
		border-right: 1px solid #ccc;
		margin: auto;
		text-align: center;
	}

	.tab-tr-end {
		width: 25%;
		height: 50px;
		line-height: 25px;
		border-right: 0px solid #ccc;
		margin: auto;
		text-align: center;
	}
</style>
<style lang="scss">
	$color-base: #0039a6;
	$words-color-base: #333333;
	$words-color-light: #999999;

	.header-wrap {
		width: 100%;
		position: fixed;
		top: 0;
		z-index: 999;

		.index-header {
			height: 88upx;
			line-height: 88upx;
			padding: 0 30upx;
			padding-top: 40upx;
			background-color: $color-base;
			font-Size: 28upx;
			color: #fff;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.fanhui {
				color: #fff !important;
				font-size: 28px;
				padding-top: 5px;
				font-weight: 700;
			}

			.lanya {
				color: #fff !important;
				font-size: 28px;
				padding-top: 5px;
			}

			.map-wrap {
				padding-top: 5px;
			}
		}
	}

	.blank {
		height: 126upx;
	}
</style>