<template>
	<view class="content contentBg">

<uni-nav-bar class="nvbar" leftIcon="left" @clickLeft="navigatorBack">
			<view slot="left">
				<uni-icons type="back" size="23" color="#FFFFFF"></uni-icons>
			</view>
			<view slot="default" class="center uninavebartext">
				{{Status.navbar.title}}
			</view>
			<view slot="right">
				<view class="navbarRight center">
					<view class="imgContent" :class="{'visibilityHidden':Status.apiType!=item.apiType}"
						@click.stop="handleRightClick(item,index)" v-for="item,index in Status.navbar.icons">
						<image class="img" :src="item.src" mode="aspectFit"></image>
						<view class="baber" v-if="item.math">{{item.math>9?'9+':item.math}}</view>
					</view>

				</view>

			</view>

		</uni-nav-bar>



		<view class="ul">
			<view class="red">扫码或输入IMEI,以添加设备</view>
			<text>IMEI列表:</text>
			<view class="li" v-for="item,index in imeis">
				<view>
					<view class="txt">IMEI:{{item.imei}}</view>
					<view class="txt">Mac:{{item.mac}}</view>
					<view class="remark" :class="item.isUpload?'green':'red'">状态:{{item.msg}}</view>
				</view>

				<image :src="isItemLink(item,index,'upload')" class="img" mode="aspectFit">
				</image>

			</view>
		</view>

		<view class="footer">
			<view class="row">


				<view class="inputContent">

					<uni-easyinput v-model="input" placeholder="请输入IMEI"></uni-easyinput>

				</view>
				<view class="btn" @click="addImei(null)">
					确定
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Common from '@/utils/Common';
	import request from '@/utils/request';
	import MqHelper from '@/utils/MqHelper';

	var eventChannel = null;
	var these = null;
	var mq = null;
	export default {
		data() {
			return {
				Status:{
					navbar: {
						icons: [{
							src: '/static/images/common/scane.png',
							callback: this.scan
							
						}],
						title: '添加IMEI'
					
					}
				},
				groupid: '',
				type: {


				},
				input: '',
				imeis: [],
				topic: ""
			}
		},
	
		onUnload() {
			if (mq) {
				mq.unSubscribes();
				mq.disconnect();
				mq = null;
			}
		},
		onLoad(opt) {
			this.groupid = Common.DateFormat(new Date(), 'yyyy-MM-dd HH:mm:ss');
			these = this;
			eventChannel = this.getOpenerEventChannel();


			eventChannel.on('addType', function(rec) {
				console.log("接收到父页面的参数:", rec);
				these.type = rec.data;
				these.Status.navbar.title="添加" + rec.data.typeName;
				
				
				let typeName = these.type.typeName.replace(/-/g, '').replace(/_/g, '').replace(
					/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '').toUpperCase();
				these.topic = 'regis/equip/' + typeName;
				mq = MqHelper.getMqTool();
				mq.init().then(res => {
					let arr = [{
						topic: these.topic,
						callback: these.mqReceive
					}];
					mq.subscribes(arr).catch(ex => {
						console.error("出现错误", ex);
					});
				});
			});


		},
		methods: {
			handleRightClick(item, s) {
				if (item && item.callback) {
					item.callback(item, s);
				} else {
					uni.showModal({
						content: '敬请期待'
					})
			
				}
			},
			navigatorBack() {
				uni.navigateBack();
			},
			//收到上报消息时的处理方法
			mqReceive(receive) {
				console.log("收到主题消息：", receive);

				let task = () => {
					return new Promise((resolve, reject) => {
						try {
							let json = JSON.parse(receive.payload);
							let imei = "";
							if (json.imei) {
								imei = json.imei;
							}

							let f = this.imeis.find(v => {
								return v.imei === imei
							});

							let mac = "";
							if (json.mac) {
								if (!json.mac.includes(':')) {
									mac = json.mac.replace(/(.{2})/g, '$1:').slice(0, -1)
								}
							}


							let dev = {
								imei: imei,
								mac: mac,
								isUpload: false,
								msg: '正在上传'
							};
							if (!f) {
								this.imeis.unshift(dev);
							}


							this.uploadItem(dev).then(res => {
								this.sendSuccNotice(imei);
								resolve(true);
							}).catch(ex => {
								console.error("ex=", ex);
								reject(ex);
							});
						} catch (err) {
							console.error("出现错误:", err);
							reject(err);
						}
					});
				}

				task();
			},
			//发送成功的通知
			sendSuccNotice(imei) {
				let json = JSON.stringify({
					code: 200
				});
				mq.sendData("regis/" + imei, json, false);
			},
			isItemLink: function(item, index, type) {
				console.log("item=", item);
				let src = '/static/images/BLEAdd/noLink.png';
				if (!item) {

					return src;
				}

				if (type == 'upload') {
					if (item.isUpload) {
						src = '/static/images/BLEAdd/linked.png';
					}
				}

				return src;
			},
			//扫码
			scan() {
				let systemInfo = uni.getSystemInfoSync();
				if (systemInfo.uniPlatform == 'web') {
					uni.showModal({
						content:"Web平台不支持此功能,请手工录入或设备开机上报"
					});
					return;
				}
				
				uni.scanCode({
					onlyFromCamera: false,
					scanType: ['qrCode'],
					autoDecodeCharset: true,
					autoZoom: true,
					barCodeInput: true,
					hideAlbum: false,
					success: (res) => {

						if (res.result) {

							console.log("扫码成功,", res);
							this.input = res.res
							this.addImei(res.result);
						}
					},
					fail: (ex) => {
						console.log("扫码失败,", ex);
					}
				});
			},
			//手动输入
			addImei(txt) {
				debugger;
				if (!txt) {
					txt = this.input
				}
				let imei = "";
				let mac = "";
				console.log("txt=", txt);
				try {
					let json = JSON.parse(txt);
					if ('blue' in json) {
						mac = json.blue;
						if (mac) {
							if (!mac.includes(':')) {
								mac = mac.replace(/(.{2})/g, '$1:').slice(0, -1)
							}

						}
					}

					if ('imei' in json) {
						imei = json.imei;
						console.log("imei=", imei)
					}

				} catch (error) {
					console.error("出现异常:", error);
					imei = txt;
				}

				let f = this.imeis.find(v => {
					return v.imei === imei
				});

				if (!f) {
					let dev = {
						imei: imei,
						mac: mac,
						isUpload: false,
						msg: '正在上传'
					};
					this.imeis.unshift(dev);

					this.uploadItem(dev).then(res => {

					}).catch(ex => {
						console.error("ex=", ex);
					});

				} else {
					uni.showModal({
						content: "IMEI重复了"
					})
				}
			},
			//上报设备至服务器
			uploadItem(item) {
				return new Promise((resolve, reject) => {
					console.log("item=", this.type);
					let json = {
						"deviceType": this.type.id,
						"deviceName": this.type.typeName,
						"deviceImei": item.imei,
						"remark": this.groupid,
						"deviceMac": item.mac,
						"bluetoothName": this.type.typeName,
					}
					console.log("111111", json)
					request({
						url: '/app/xinghan/device/add',
						method: 'post',
						data: json
					}).then(res => {

						if (res && res.code) {


							this.imeis.find((v, index) => {
								if (v.imei == item.imei) {
									this.$set(this.imeis[index], "isUpload", (res && res.code ==
										200));
									this.$set(this.imeis[index], "msg", res.msg);
									return true;
								}
								return false;
							});
							this.input = "";
							if (res.code == 200) {
								console.log("成功了,", res);
								resolve(true);
								return;
							} else if (res.code == 500) {
								if (res.msg.indexOf('已存在') > -1) {
									resolve(true);
									return;
								}
							}
							
							
						}

							console.log("出现错误，", res);
							reject(res);
						

					});
				});

			}
		}
	}
</script>

<style>
	.content {
		box-sizing: border-box;
		width: 100%;
		min-height: 100vh;
		height: auto;
		padding: 30rpx;
	}



	.li {
		width: 100%;

		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		align-content: center;
		align-items: center;
		justify-content: space-between;
		background: #1A1A1A;
		box-sizing: border-box;
		padding: 20rpx;
		border-radius: 16rpx;
		margin-top: 20rpx;
	}

	.txt {
		font-size: 34rpx;
		font-weight: 400;

	}

	.remark {
		font-size: 26rpx;
		font-weight: 300;
	}

	.img {
		width: 50rpx;
		height: 50rpx;
	}

	.footer {
		position: fixed;
		width: 100%;
		bottom: 0rpx;
		left: 0rpx;
	}

	.footer .row {
		width: 100%;
		height: auto;
		box-sizing: border-box;
		padding: 20rpx;
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		align-content: center;
		align-items: center;
		justify-content: space-between;
	}

	.inputContent {
		width: calc(100% - 110rpx);
	}

	.footer .btn {
		width: 100rpx;
		text-align: center;
		background-color: #09a0f7;
		color: #fff;
		border-radius: 16rpx;
		height: 70rpx;
		line-height: 70rpx;
	}
	
	
	
	.navbarRight {
		width: 40px;
		height: 100%;
	
	}
	
	.navbarRight .imgContent {
		width: 36rpx;
		height: 36rpx;
		position: relative;
	}
	
	.navbarRight .imgContent:first-child {
	
		width: 38rpx !important;
		height: 38rpx !important;
		margin-top: -2rpx;
	}
	
	.navbarRight .imgContent .baber {
		position: absolute;
		z-index: 100;
		width: 30rpx;
		height: 30rpx;
		line-height: 30rpx;
		right: -15rpx;
		top: -15rpx;
		border-radius: 50%;
		background: #f12828;
		color: #ffffff;
		font-family: 'PingFang SC';
		font-style: Regular;
		font-size: 20rpx;
		font-weight: 400;
	
		text-align: center;
		overflow: hidden;
		white-space: nowrap;
	
	}
	
	.navbarRight .imgContent .img {
		width: 100%;
		height: 100%;
	
		box-sizing: border-box;
		position: relative;
	}
	
	.navbarRight .imgContent .img:last-child {
		padding: 1rpx;
	}
	
	.nvbar {
		top: 0px;
	}
	
	/deep/ .uni-navbar--fixed {
		top: 0px;
	}
	
	.uninavebartext {
		width: 100%;
		font-size: 32rpx;
	}
</style>