<template>
  <view class="container">
    <view class="setting">

      <view class="prop-item">
        <view class="prop-title">充电电流</view>
        <view class="prop-value">
          <view :style="item.style" class="value-tag" @click="checkItem(current,item)" v-for="item in current.items">
            {{ item.text }}
          </view>
        </view>
        <view class="prop-input" v-if="current.custom">
          <input v-model="current.customValue" class="input" placeholder="请输入电流"/>
          <view style="color: #0E9F9B">A</view>
        </view>
      </view>

    </view>


    <view class="bottom-area">

      <view class="btn" @click="confirm">确认</view>


      <view class="areas">
        <view class="areas-item" @click="sendMainboardCmd">
          <view class="areas-img">
            <image style="width: 50px;height: 50px" :src="imgUrl+'/seting/mainboard.png'"></image>

          </view>
          <view>
            <view>获取主板配置</view>
          </view>
        </view>

        <view class="areas-item" @click="resetMainboard">
          <view class="areas-img">
            <image style="width: 50px;height: 50px" :src="imgUrl+'/seting/reset.png'"></image>
          </view>
          <view>
            <view >恢复默认配置</view>
          </view>
        </view>

        <view class="areas-item" @click="restartMainboard">
          <view class="areas-img">
            <image style="width: 50px;height: 50px" :src="imgUrl+'/seting/restart.png'"></image>
          </view>
          <view>
            <view>重启充电桩</view>
          </view>
        </view>

      </view>
    </view>
  </view>
</template>

<script>
import {setCurrent, getMainbordConfig,sendMainboardCmd, reset, restart,parseDataObj} from "@/utils/weitiandi/device/device.js";
// #ifdef APP
import ecUI from '@/utils/ecUI.js'
import ecBLE from '@/utils/ecBLE/ecBLE.js'
// #endif
// #ifdef MP
const ecUI = require('@/utils/ecUI.js')
const ecBLE = require('@/utils/ecBLE/ecBLE.js')
// #endif
let ctx
let isCheckScroll = true
let isCheckRevHex = false
let isCheckSendHex = false
let sendData = ''
export default {
  data() {
    return {

      scriptTask:null,
      deviceId: "",
      ccid:"",
      visitTime: "",
      mainBoardInfo:{},
      current: {
        items: [
          {text: "8A", style: "", value: 8},
          {text: "10A", style: "", value: 10},
          {text: "16A", style: "", value: 16},
          {text: "32A", style: "", value: 32},
          {text: "自定义", style: "", value: -1}
        ],
        custom: false,
        customValue: ''
      }

    }

  },
  onUnload (){
    this.closeSocket();
  },
  computed: {
    imgUrl: function () {
      return getApp().globalData.config.imgUrl;
    }
  },
  onLoad(opt) {
    this.deviceId = opt.id;
    this.ccid = opt.ccid;
    this.buletooth();

  },
  methods: {
    closeSocket(){
      ecBLE.onBLEConnectionStateChange(() => {})
      ecBLE.onBLECharacteristicValueChange(() => {})
    },
    recon(){
      let self = this;
      ecUI.showLoading('设备连接中')
      let blueid = uni.getStorageSync('blueid');
      ecBLE.onBLEConnectionStateChange(res => {
        ecUI.hideLoading()
        if (res.ok) {
          self.buletooth();
        } else {
          uni.removeStorageSync('blueid');
          ecUI.showModal(
              '提示',
              '连接失败,errCode=' + res.errCode + ',errMsg=' + res.errMsg
          )
        }
      })
      ecBLE.createBLEConnection(blueid);
    },
    buletooth(){
      let self = this;
      ctx = this
      isCheckScroll = true
      isCheckRevHex = false
      isCheckSendHex = false
      sendData = ''

      //on disconnect
      ecBLE.onBLEConnectionStateChange(() => {
        uni.showModal({
          title: '提示',
          content: '蓝牙断开连接',
          confirmText:"点击重连",
          showCancel:false,
          success: function (res) {
            if (res.confirm) {
              self.recon();
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      })
      //receive data
      ecBLE.onBLECharacteristicValueChange((str, strHex) => {
        isCheckRevHex = true;
        let data =
            (isCheckRevHex ? strHex.replace(/[0-9a-fA-F]{2}/g, ' $&') : str)
        // console.log(data)
        self.$modal.closeLoading();
        console.log("settting:"+data);
        //AA 67 0D 05 00 00 00 00 00 00 00 00 00 25 E2 00 80
        data = parseDataObj(data);
        self.messageCallback(data);
      })
      self.sendMainboardCmd();
    },
    messageCallback(data){
        let self = this;
        let type = data.type;
        let real_data = data.real_data;
        if(type == 103){
          self.portDetail = real_data;
          self.$modal.closeLoading();
        }
        if(type == 116){
          self.$modal.closeLoading();
        }
        if(type == 96){
          self.mainBoardInfo = real_data;
          self.formatMainboardData();
          self.$modal.closeLoading();
        }
        console.log('收到服务器内容：' + JSON.stringify(data));
    },
    formatMainboardData(){
      let mainBoardInfo = this.mainBoardInfo;
      let max_current = mainBoardInfo.max_current;
      max_current = max_current/100;
      this.setCurrent(max_current);
    },
    setCurrent(max_current){
      this.current.currenValue = max_current;
      let items = this.current.items;
      let len = items.length;
      let hasValue = false;
      this.current.custom = false;
      for (let i = 0; i < len; i++) {
        let dian = items[i];
        if(dian.value == max_current){
          hasValue = true;
          dian.style = ";  background: #0E9F9B;color:white"
        }else{
          dian.style = ";  background: rgb(227, 242, 245);color: #0E9F9B;"
        }
      }
      if(!hasValue){
        this.current.custom = true;
        items[len-1].style = ";  background: #0E9F9B;color:white"
      }
      this.current.customValue = max_current;
    },
    async checkItem(obj, item) {
      let items = obj.items;
      let len = items.length;
      for (let i = 0; i < len; i++) {
        let dian = items[i];
        dian.style = ";  background: rgb(227, 242, 245);color: #0E9F9B;"
      }
      item.style = ";  background: #0E9F9B;color:white"
      if (item.value == -1) {
        obj.custom = true;
        obj.customValue = 0;
      } else {
        obj.custom = false;
        obj.customValue = item.value;
      }
    },
    async confirm() {
      let currenValue = this.current.customValue;
      currenValue = currenValue *100;
      let deviceId = this.deviceId;
      // 发送到后端
      let self = this;
      this.$modal.loading("保存中。。");
      setCurrent(currenValue).then(res => {
        this.$modal.showToast("保存成功");
          setTimeout(function(){
            self.sendMainboardCmd();
          },1000)
      })
    },
    sendMainboardCmd() {
      // let str = "AA 60 21 01 08 F4 01 E7 03 00 D0 20 07 09 05 16 08 00 00 00 05 80 0C 00 00 FC 0D 0C 0F 12 08 07 08 07 08 07 80";
      // let data = parseDataObj(str);
      // this.messageCallback(data);
      this.$modal.loading("正在获取配置信息");
      sendMainboardCmd().then(res => {
      })
    },
    getMainboardConfig(){
      this.startTimer();
    },
    startTimer(){
      let self = this;
      this.timer = setTimeout(function (){
        getMainbordConfig({deviceId: self.deviceId,ccid:this.ccid},self.visitTime).then(res=>{
          let data = res.data;
          if(data != null){
            self.mainBoardInfo = data;
            self.formatMainboardData();
            self.$modal.closeLoading();
          }else{
            self.startTimer();
          }
        });
      },1000);
    },
    resetMainboard() {
      let deviceId = this.deviceId;
      // 恢复默认配置
      let self = this;
      this.$modal.loading("正在重置，请稍等...");
      reset().then(res => {
        setTimeout(function(){
          self.sendMainboardCmd();
        },1000)
      })
    },
    async restartMainboard() {
      let deviceId = this.deviceId;
      this.$modal.loading("正在重启中，请稍等...");
      // 重启充电桩
      let self = this;
      restart().then(res => {
        setTimeout(function(){
          self.sendMainboardCmd();
        },1000)
      })
    }
  }
}
</script>

<style>

.container {
  position: absolute;
  inset: 0;
  background: rgb(249, 252, 255);
}

.prop-item {
  padding: 2vh;
}

.prop-value {
  display: flex;
  flex-direction: row;
}

.prop-title {
  color: #252525;
  font-weight: bold;
  margin-bottom: 2.5vh;
}

.value-tag {
  background: rgb(227, 242, 245);
  color: #0E9F9B;
  width: 14vw;
  height: 4vh;
  line-height: 4vh;
  border-radius: 3vw;
  text-align: center;
  margin: 0 1vw;
  font-weight: bold;
  font-size: 12px;
}

.prop-input {
  display: flex;
  flex-direction: row;
  line-height: 4vh;
  margin: 2vh 0;
}

.input {
  background: rgb(227, 242, 245);
  border-radius: 30px;
  font-size: 12px;
  height: 4vh;
  padding: 0 2vw;
  margin: 0 1vw;
  width: 90%;
}

.bottom-area {
  position: absolute;
  bottom: 0px;
  height: 24vh;
  left: 0;
  right: 0;
}

.btn {
  background: #0E9F9B;
  text-align: center;
  color: white;
  height: 6vh;
  line-height: 6vh;
  margin: 0 5vh;
  border-radius: 1vh;
  border-style: none;
}

.btn1 {
  background: #f9fcff;
  /*  text-align: center;
    color: white;
    height:6vh;
    line-height: 6vh;
    margin:0 5vh;
    border-radius: 1vh; */
  border-color: transparent;
}

.areas {
  display: flex;
  flex-direction: row;
  text-align: center;
  margin-top: 3vh
}

.areas-item {
  width: 33%;
}

.areas-img {
  text-align: center;
}
</style>
