<!--  -->
<template>
  <div class="bind">
    <NavBar title="绑定设备" @on-click-left="onNavBack" :leftArrow="false" leftText=""></NavBar>
    <div class="main">
      <div class="top">
        <van-button size="small" round type="default" class="btn-def" @click="onNotBind">暂不绑定</van-button>
      </div>
      <div class="bind-con">
        <div class="scan">
          <p>申请获取并验证你的手机号</p>
          <img :src="scanImg" alt="" @click="onScanQRCodeSubmit" />
        </div>
        <div class="cut-line">
          <span>----------或手动填写绑定----------</span>
        </div>
        <div class="input">
          <van-field v-model="inputVal" placeholder="请填写设备码" input-align="right">
            <template #label>
              <p class="input-label">设备码</p>
            </template>
          </van-field>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="btn">
        <van-button size="large" round @click="onNext" :color="$green" class="next-text">下一步</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import NavBar from '@/components/NavBar.vue';
import DialogService from '@/services/dialog-service';
import AppId from '@/config/appId';
import ToastService from '@/services/toast-service';
import APIWx from '@/api/wx';
import APIDevice from '@/api/device';
import APICommand from '@/api/command';
import { isComma } from '@/services/utils-service';
let wx = require('weixin-js-sdk');
export default {
  components: { NavBar },
  data() {
    return {
      scanImg: require('@/assets/com-imges/55_10.png'),
      active: 0,
      inputVal: '',
      isAdmin: false,
      canScan: false,
      serialNo: '', //提取扫码url里面的serialNo
      code: '', //提取扫码url里面的密文
      iccid: '', //提取扫码url里面的iccid
      issue: '', //分期数
      params: {}
    };
  },
  created() {
    this.loadParams();
    this.getWxAutograph();
  },
  mounted() {},
  methods: {
    loadParams() {
      let params = this.$route.query;
      if (params) {
        this.params = { ...params };
      }
    },
    onNavBack() {
      this.$router.back();
    },
    onNext() {
      // 验证输入框或者微信扫码得到的设备信息，再通过这些信息判断跳转到哪些页面
      // 1.首先判断输入框
      // 2. 再判断微信扫码
      this.$router.push({
        name: 'Index'
      });
      /* if (this.inputVal != '') {
        this.CheckImei();
      } else {
        DialogService.confirm({ message: '输入的值不能空，请不要输入空格' });
      } */
    },
    onScanQRCodeSubmit() {
      if (!this.canScan) {
        DialogService.confirm({ message: '扫一扫功能加载中，请稍等或者重新进入' });
        return;
      }
      let that = this;
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果
        scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          console.log('微信扫码返回的结果::', res.resultStr);
          var url = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
          that.compatibleDevice(url);
        },
        fail: function (err) {
          alert(`扫码请求失败，请重新打开应用。\n${err.errMsg}`);
          console.log('wx.scanQRCode fail:::', err);
        }
      });
    },
    getWxAutograph() {
      let that = this;
      return new Promise((resolve, reject) => {
        APIWx.createJSSDK({
          sUrl: window.location.href.split('#')[0],
          userId: this.$store.getters.userId,
          appId: AppId
        })
          .then(res => {
            let item = res.data.data;
            wx.config({
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: item.appId, // 必填，公众号的唯一标识
              timestamp: item.timeStamp, // 必填，生成签名的时间戳
              nonceStr: item.nonceStr, // 必填，生成签名的随机串
              signature: item.signature, // 必填，签名
              jsApiList: ['scanQRCode'] // 必填，需要使用的JS接口列表
            });

            wx.ready(() => {
              resolve(true);
              that.canScan = true;
            });
          })
          .catch(err => {
            reject(false);
            console.log(err);
          });
      });
    },
    CheckImei() {
      let reqBody = {
        imei: this.serialNo || this.inputVal.trim(),
        iccid: this.iccid || ''
      };
      APICommand.CheckImei(reqBody)
        .then(res => {
          let data = res.data;
          this.issue = data.title === '富康通' ? 60 : 0;
          // 2023.05.25,取消！---接口新增加一个 isActive 参数来判断是否需要调用激活接口， 0，不需要直接绑定，1 需要
          if (data.stateCode === 1 && data.rule === 1 && data.isRecharge === false && data.iccid !== null) {
            // stateCode = 1 ,title = '直播' 并且isRecharge 是false才可以进入到充值界面
            this.$router.push({
              name: 'topup',
              query: {
                isCanTopup: true,
                iccid: this.iccid,
                isAdmin: this.isAdmin,
                serialNo: this.serialNo
              }
            });
          } else if (
            data.stateCode === 1 &&
            data.message === 'ok' &&
            data.isRecharge === false &&
            data.iccid === null &&
            this.inputVal !== ''
          ) {
            // 手动输入是直播基地的设备
            DialogService.confirm({
              message: '请您通过扫码方式激活绑定!'
            });
          } else if (
            data.stateCode === 1 &&
            data.message === 'ok' &&
            data.isRecharge === true &&
            data.iccid === null &&
            this.inputVal !== ''
          ) {
            DialogService.confirm({
              message: '请您通过扫码方式激活绑定!'
            });
          } else if (
            data.stateCode === 0 &&
            data.message === '请插入正确的电话卡进行设备激活' &&
            data.iccid === null &&
            this.inputVal !== ''
          ) {
            DialogService.confirm({
              message: '请您通过扫码方式激活绑定!'
            });
          } else if (
            data.stateCode === 0 &&
            data.message === '请插入正确的电话卡进行设备激活' &&
            data.iccid !== null &&
            this.inputVal === ''
          ) {
            DialogService.confirm({
              message: '为了更好地为您服务，请务必使用我司提供的电话卡。有疑问请来电400 002 3393咨询。'
            });
          } else if (
            data.stateCode === 0 &&
            data.message === '请插入正确的电话卡进行设备激活' &&
            data.iccid === null &&
            this.inputVal === ''
          ) {
            DialogService.confirm({
              message: '为了更好地为您服务，请务必使用我司提供的电话卡。有疑问请来电400 002 3393咨询。'
            });
          } else if (
            data.stateCode === 1 &&
            data.rule === 1 &&
            data.message === 'ok' &&
            data.isRecharge === true &&
            this.iccid !== null
          ) {
            // 扫码时是直播基地的设备并且已经支付完成的
            this.getAdminOfIdByScan(this.serialNo, this.iccid);
          } else if (
            data.stateCode === 1 &&
            data.rule === 2 &&
            !this.isCanEffective(data.title) &&
            this.inputVal === ''
          ) {
            this.getAdminOfIdByScan(this.serialNo, this.iccid);
          } else if (data.stateCode === 1 && data.rule === 2 && this.isCanEffective(data.title)) {
            // 中亿/联通的卡不走激活接口，直接绑定
            this.getAdminOfIdByScan(this.serialNo);
          } else if (data.stateCode === 0 && data.rule === 0 && this.inputVal === '') {
            this.getAdminOfIdByScan(this.serialNo);
          } else if (data.stateCode === 0 && data.rule === 0 && this.inputVal !== '') {
            this.getAdminOfIdByScan(this.inputVal);
          } else {
            if (this.inputVal != '') {
              //this.getAdminByInput();
              this.getAdminOfIdByScan(this.inputVal);
            } else {
              this.getAdminOfIdByScan(this.serialNo);
            }
          }
        })
        .catch(() => {});
    },
    /**
     * 扫码
     * 参数为明文的cid/serialNo
     */
    getAdminOfIdByScan(serialNo, iccid) {
      /* let reqUrl = '/api/Device/BindingScan';
                let reqBody = { url }; */
      ToastService.loading();
      /*  this.$axios
                    .post(reqUrl, reqBody) */
      let url = `?id=${serialNo}`;
      APIDevice.bindingScan({ url })
        .then(res => {
          let data = res.data.data;
          if (res.data.stateCode === 1) {
            this.isAdmin = data.isAdmin;
            this.$store.commit('isAdmin', data.isAdmin);
            this.$router.push({
              // 2022 03. 19 需求变更 取消向设备发送安全码
              /* name: data.isAdmin ? "safetyCode" : "relation", */
              // 2022. 4. 6 需求变更 增加一个中间页
              /* name: "relation", */
              name: 'bindingCheck',
              query: {
                serialNo: data.serialNo,
                isAdmin: data.isAdmin,
                iccid: iccid || '',
                issue: this.issue
              }
            });
          } else {
            DialogService.confirm({ message: res.data.message });
          }
        })
        .catch(e => console.log(e))
        .finally(() => ToastService.clear());
    },
    /**
     * 扫码
     * 使用新设备的接口，参数为加密的cid
     */
    getAdminOfCidByScan(code) {
      /* let reqUrl = '/api/Device/BindingScan';
                let reqBody = { url }; */
      ToastService.loading();
      /*  this.$axios
                    .post(reqUrl, reqBody) */
      let url = `?cid=${code}`;
      APIDevice.bindingScan({ url })
        .then(res => {
          let data = res.data.data;
          if (res.data.stateCode === 1) {
            // TODO isAdmin true:该请求为管理员，false:该请求为家属（需要提示用户等待管理员的通过）
            // TODO 新旧设备标记：useSafeCode = 0 | 1
            this.isAdmin = data.isAdmin;
            this.$store.commit('isAdmin', data.isAdmin);
            this.$router.push({
              name: 'relation',
              query: {
                serialNo: data.serialNo,
                isAdmin: data.isAdmin
              }
            });
          } else {
            DialogService.confirm({ message: res.data.message });
          }
        })
        .catch(e => console.log(e))
        .finally(() => ToastService.clear());
    },
    /**
     * 扫码后，返回的数据是一个 url，参数为 id | cid，新设备为 cid，旧设备为 id
     * 新设备使用新的加密方式，获取的非明文 imei/serialNo，故省略了发送验证码步骤
     */ compatibleDevice(url) {
      console.log('url', url);
      let res = /\?cid=/.test(url);
      let isId = /\?id=/.test(url);
      let idCallBack = isComma(url);
      console.log('idCallBack', idCallBack);
      // 如果 二维码url存在 Unknown 增加 提示， 并且不允许进行下一步操作
      // eslint-disable-next-line no-useless-escape
      if (/\Unknown/.test(url)) {
        return DialogService.confirm({
          title: 'SIM卡识别失败',
          message: '请在设备操作[返回]，再按[确定]显示绑定二维码。'
        });
      }
      // 旧设备
      if (isId) {
        // 根据返回类型获取想要的数据
        if (typeof idCallBack === 'object') {
          let newSerialNo = idCallBack.imei.split('?id=')[1];
          this.serialNo = newSerialNo;
          this.iccid = idCallBack.data;
          console.log('newSerialNo', newSerialNo, 'iccid', idCallBack.data);
          this.CheckImei();
          /* this.getAdminOfIdByScan(this.serialNo); */
        } else if (typeof idCallBack === 'string') {
          this.serialNo = url.split('?id=')[1];
          this.CheckImei();
          //this.getAdminOfIdByScan(this.serialNo);
        }
      } else if (idCallBack.type === 'rfIdAndiccId') {
        // 明文没有url 只有imei,rfid,iccid
        let newSerialNo = idCallBack.imei;
        this.serialNo = newSerialNo;
        this.iccid = idCallBack.data;
        console.log('newSerialNo', newSerialNo, 'iccid', idCallBack.data);
        this.CheckImei();
      } else if (res) {
        // 新设备
        if (typeof idCallBack === 'object') {
          let newCode = idCallBack.imei.split('?cid=')[1];
          this.code = newCode;
          this.iccid = idCallBack.data;
          this.decodeSerialNo(newCode);
          this.getAdminOfCidByScan(newCode);
        } else if (typeof idCallBack === 'string') {
          let newCode = url.split('?cid=')[1];
          this.code = newCode;
          this.decodeSerialNo(newCode);
          this.getAdminOfCidByScan(newCode);
        }
        // 无id或者cid时
      } else {
        if (typeof idCallBack === 'object') {
          let newSerialNo = idCallBack.imei;
          this.serialNo = newSerialNo;
          this.getAdminOfIdByScan(this.serialNo);
        } else if (typeof idCallBack === 'string') {
          this.serialNo = url;
          this.getAdminOfIdByScan(this.serialNo);
        }
      }
      // 2022/3/17 为了兼容新的扫码方式特意注释
      /* if (res) { // 新设备
                    this.getAdminOfCidByScan(url);
                } else { // 旧设备
                    this.getAdminOfIdByScan(url);
                } */
    },
    // 通过密文解析获取imei
    decodeSerialNo() {
      APIDevice.decodeSerialNo({ code: this.code })
        .then(res => {
          let data = res.data;
          if (data.stateCode === 1) {
            let newData = isComma(data.data);
            console.log('newData', newData);
            this.serialNo = newData.imei || data.data;
            console.log('this.serialNo', this.serialNo);
            // 如果返回的数据有逗号, 根据类型放到store里面
            // todo 一期这个需求暂时不用做
            /* if (newData) {
                                if(newData.type === "iccId") {
                                    this.$store.commit("iccId", newData.data);
                                } else if (newData.type === "rfId") {
                                    this.$store.commit("rfId", newData.data);
                                }
                            } */
          }
        })
        .catch(error => {
          console.log('error', error);
        });
    },
    // 是否可以走激活接口
    isCanEffective(title) {
      let manufacturerArray = ['中亿', '联通', '中亿/联通'];
      let isEffective = manufacturerArray.some(item => {
        return item.includes(title);
      });
      return isEffective;
    },
    // 暂不绑定
    onNotBind() {
      this.$router.push({
        name: 'Index'
      });
    }
  }
};
</script>
<style scoped lang="scss">
.bind {
  height: 100vh;
  overflow: hidden;
  .main {
    position: relative;
    overflow: scroll;
    padding: 100px 40px;
    .top {
      height: 60px;
      padding: 20px 0;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      .btn-def {
        height: 40px;
        padding: 10px;
        border: 1px solid $green;
      }
    }
    .bind-con {
      position: relative;
      .scan {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 34px;
        padding: 20px 0;
        p {
          font-size: 36px;
          font-weight: bold;
        }
        img {
          height: 60px;
          width: 60px;
          object-fit: contain;
        }
      }
      .cut-line {
        padding: 20px;
        font-size: 28px;
        color: $border_color;
        @include center();
      }
      .input {
        padding: 40px 0;
        .van-cell {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 !important;
          .input-label {
            @include colorAndFont(#333, 18);
            font-weight: bold;
          }
        }
      }
    }
  }
  .bottom {
    height: 120px;
    width: 100%;
    position: absolute;
    bottom: 10px;
    left: 0;
    @include center();
    .btn {
      width: 100%;
      padding: 40px;
      .next-text {
        font-size: 48px;
      }
    }
  }
}
/* @import url(); 引入css类 */
</style>
