<template>
  <view class="tiaoxingma"  :style="[{minHeight:windowHeight + 'px'}]" >
	  
	<view class="header" >
		<text>将二维码对准摄像头</text>
	</view>
	
	<view class="center border">
		<Ba-ScanViewS ref="scanViewS" style="height: 200; width: 100%"   :load="loadData" @onScan="onScan"> </Ba-ScanViewS>
	</view>

	<view class="" style="margin-bottom: 20rpx;" >
		<text>成功录入：{{cgLength}}条</text>
	</view>

	<scroll-view scroll-y="true" class="footer msg-center">
		<view class="msg-list" :class="item.type === 'res'?'cg':''" v-for="(item,index) in msgList">
			<text style="color: #999; text-align: center; font-size: 20rpx;" >{{item.time}}</text>
			<view class="msg-li" >
				<text >MAC码{{item.MAC}} - </text>
				<text v-if="item.type === 'res'" class="cg" >{{item.title}}</text>
				<text v-else-if="item.type === 'err'" class="sb" >{{item.title}}</text>
				<text v-else >{{item.title}}</text>
			</view>
		</view>
	</scroll-view>
	
	<view class="butScan"  style="margin-bottom: 20rpx;" >
		<text class="textScan" @click="openScan"> 打开扫描</text>
		<text class="textScan" @click="closeScan" style="border: 1px solid red; color: red;" >关闭扫描</text>
	</view>
	
	
  </view>
</template>

<script>
export default {
  data() {
    return {
      loadData: {
        //配置
        scanTimeSpace: 1000, //时间间隔
        //isDirScanMulti: true,//是否直接返回多码，默认fasle（弹窗多码标识，用户自己选择）
        //rpCancelBtnText: 'cancel',
        isShowToast: false,
      },
      msgList: [],
	  newList: {},
	  luType: 'zhengchang',
	  cgLength :0,
	  windowHeight: 0
    }
  },
  
    onReady() {
      // 获取屏幕高度
      uni.getSystemInfo({
        success: (res) => {
          this.windowHeight = res.windowHeight
        }
      })
    },
  
  onLoad() {
    let that = this
    //监听扫码结果（vue2和vue3都支持）
    var globalEvent = uni.requireNativePlugin('globalEvent')
    globalEvent.addEventListener('baScanViewEvent', function (e) {
	   if (that.luType === 'zhengchang') {
		  let newMac = e.detail.result.split(',')
		  let objMac = newMac.reduce((acc, value, index) => {
			let newMac = value.split('=')
			acc[newMac[0]] = newMac[1];
			return acc;
		  }, {});
		  objMac.title='准备录入中...'
		  objMac.time= that.formatDate(new Date())
		  that.luType = 'loading'
		  // console.log(objMac, 'objMac--------')
		  // console.log('onScan：' + e.detail.result)		  
		  that.msgList.unshift(objMac)
		  that.newList = e.detail.result
		  
		  that.onRequest(objMac)
		  // 请求接口录入路由器信息
		  // console.log('baScanViewEvent' + JSON.stringify(e))
	   } else if (that.luType === 'loading') {
			uni.showToast({
			  title: '有数据正在录入...',
			  icon: 'none'
			})
	   }
		
    })
  },
  methods: {
    onScan(e) {
      //扫码监听（仅支持vue2，vue3请使用globalEvent方式）
      console.log('onScan：' + e.detail.result)
      console.log('onScan：' + e.detail.results) //多个
      this.msgList.unshift(JSON.stringify(e.detail))
    },
	
	// 定义格式化函数
	 formatDate(date) {
	  // 获取年份、月份和日期
	  const year = date.getFullYear();
	  const month = String(date.getMonth() + 1).padStart(2, '0'); // +1因为getMonth()返回的是0-11
	  const day = String(date.getDate()).padStart(2, '0');
	
	  // 获取小时、分钟和秒
	  const hours = String(date.getHours()).padStart(2, '0');
	  const minutes = String(date.getMinutes()).padStart(2, '0');
	  const seconds = String(date.getSeconds()).padStart(2, '0');
	
	  // 返回格式化后的日期字符串
	  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	},
	
	onRequest(data) {
		
		if (!data.MAC) {
			uni.showToast({
			  title: '二维码数据异常，没有MAC数据',
			  icon: 'none'
			})
			return
		}
		
		let that = this
		that.luType === 'loading'
		uni.request({
		    url: 'https://api.hninpop.com/api/addbox?routerboxmac='+data.MAC, // 你的API接口
		    method: 'GET', // 请求方法，根据需要可能是 'GET', 'POST' 等
		    data: {
				routerboxmac: data.MAC
		        // 这里放置需要传递给服务器的数据
		    },
		    header: {
		        // 设置请求的 header，例如：'Content-Type': 'application/json'
		    },
		    success: (res) => {
				// 请求成功的回调函数
				if (res.data.Status === 0) {
					that.cgLength++
					let objMac = {
						title: '录入成功',
						type: 'res',
						MAC: data.MAC,
					}
					objMac.time= that.formatDate(new Date())
					that.msgList.unshift(objMac)
				} else {
					let objMac = {
						title: '录入失败 ' + res.data.Message,
						type: 'err',
						MAC: data.MAC,
					}
					objMac.time= that.formatDate(new Date())
					that.msgList.unshift(objMac)
				}
		        console.log(res.data.Status, 'success');
		    },
		    fail: (err) => {
				let objMac = {
					title: '录入失败',
					type: 'err',
					MAC: data.MAC,
				}
				objMac.time= that.formatDate(new Date())
				that.msgList.unshift(objMac)
		        // 请求失败的回调函数
		        console.error(err, 'fail');
		    },
		    complete: (value) => {
				console.log(value, 'value');
				that.luType = 'zhengchang'
		        // 请求结束的回调函数（无论成功或失败都会执行）
		    }
		});
	},
	
    openScanLight() {
      //打开闪光灯
      this.$refs.scanViewS.openScanLight()
    },
    closeScanLight() {
      //关闭闪光灯
      this.$refs.scanViewS.closeScanLight()
    },
    isLightOn() {
      //是否打开闪光灯
      this.$refs.scanViewS.isLightOn((res) => {
        uni.showToast({
          title: 'isLightOn：' + res.isLightOn,
          icon: 'none'
        })
      })
    },
    openAlbumPage() {
      //相册识别
      this.$refs.scanViewS.openAlbumPage()
    },
    openScan() {
      //打开扫描
      this.$refs.scanViewS.openScan()
	  this.isScanOpen()
    },
    closeScan() {
      //关闭扫描
      this.$refs.scanViewS.closeScan()
	  this.isScanOpen()
    },
    isScanOpen() {
      //是否打开扫描
      this.$refs.scanViewS.isScanOpen((res) => {
        uni.showToast({
          title: res.isScanOpen? '已打开扫描':'已关闭扫描',
          icon: 'none'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tiaoxingma {
	height: 100vh;
	padding: 40rpx 40rpx;
	border: 1px solid #eee;
	overflow: auto;
	padding-top: 100rpx;
	.border{
		border: 1px solid #333;
	}
	.center{
		height: 380rpx;
		margin: 20rpx 0rpx;
	}
	.footer{
		height: 800rpx;
		overflow-y: auto; /* 在垂直方向上启用滚动 */
		.msg-list{
			background: #eee;
			padding: 8rpx 20rpx;
			border-radius: 10rpx;
			margin-bottom: 10rpx;
		}
		.msg-li{
			display: flex;
			flex-direction: row;
		}
	}
	.cg{
		color: green;
	}
	.sb{
		color: red;
	}
	.butScan{
		margin-top: 20rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		padding: 0rpx 70rpx;
		.textScan{
			border: 1px solid green;
			color: green;
			border-radius: 10rpx;
			padding: 20rpx 40rpx;
		}
	}
	
}
</style>
