<template>
  <div class="container" v-show="isPageShow">
    <NavBar title="绑定设备" @on-click-left="onBack"></NavBar>
    <div class="content">
      <p class="tips">设备号码：</p>
      <p class="text">{{ isNewDevice ? decodedSerialNo || '正在解码...' : serialNo }}</p>
      <p class="tips" v-show="isShow">ICCID：</p>
      <p class="text" v-show="isShow">{{ iccid }}</p>
      <p class="iccid-text" v-show="iccidShow">
        <span class="span-red"
          >SIM卡激活成功，请确认在线图标标志<img
            src="@/assets/myself/online.png"
          />，如没有看到，请重启设备或者等1分钟之后再进入绑定界面。</span
        ><br />
        <span class="span-red">确认设备在线，再点击【下一步】。</span>
      </p>
      <p class="iccid-text" v-show="!iccidShow">
        <span class="span-red">{{ errorText }}</span>
      </p>
      <div class="submit-button">
        <van-button
          round
          type="info"
          :disabled="!canSubmit || !canNext || !isFail"
          :loading="loading"
          @click="onSubmit"
        >
          {{ submitText }}
        </van-button>
      </div>
      <!-- <div class="cancel-button" v-show="false">
        <van-button round plain @click="onCancel"> 取消 </van-button>
      </div> -->
    </div>
  </div>
</template>

<script>
import DialogService from '@/services/dialog-service';
import ToastService from '@/services/toast-service';
import APICommand from '@/api/command';
import APIDevice from '@/api/device';
import { isComma } from '@/services/utils-service';
import NavBar from '@/components/NavBar.vue';
export default {
  components: { NavBar },
  computed: {
    canSubmit() {
      if (this.isNewDevice) {
        return this.$own.isNotNull(this.decodedSerialNo);
      } else {
        return true;
      }
    },
    submitText() {
      return '下一步';
    }
  },
  data() {
    return {
      serialNo: '',
      decodedSerialNo: '',
      isNewDevice: false,
      loading: false,
      iccid: '',
      iccidShow: false,
      errorText: '', //sim卡激活失败
      isShow: false,
      timer: null, //倒计时
      bindTime: 60, //60秒倒计时
      canNext: true,
      isPageShow: false,
      isFail: true //sim卡激活失败
    };
  },
  destroyed() {
    clearInterval(this.timer);
  },
  mounted() {
    this.serialNo = this.$route.query.serialNo;
    this.iccid = this.$route.query.iccid;
    this.isNewDevice = JSON.parse(this.$route.query.isNewDevice || false);
    if (this.isNewDevice) {
      this.decodeSerialNo();
    }
    this.checkEffective();
  },
  methods: {
    // 返回
    onBack() {
      this.$router.push({ name: 'deviceBinding' });
    },
    onSubmit() {
      if (this.isNewDevice) {
        this.getAdminOfCidByScan();
      } else this.getAdminOfIdByScan();
    },
    // 检查是否需要激活,根据iccid是否不为空判断
    checkEffective() {
      if (this.iccid !== '') {
        this.effective();
      } else {
        this.isPageShow = false;
        this.onSubmit();
      }
    },
    // sim卡自动激活
    // 中亿物联联通卡 SIM自动激活
    effective() {
      ToastService.loading({ message: '激活中,请稍候...' });
      let reqBody = {
        imei: this.serialNo,
        iccid: this.iccid,
        issue: this.$route.query.issue || 0
      };
      APICommand.Effective(reqBody)
        .then(res => {
          console.log('res', res);
          let data = res.data;
          if (data.stateCode === 0 && data.message !== null) {
            this.iccidShow = false;
            this.isShow = true;
            this.isFail = false;
            this.isPageShow = true;
            this.errorText = '电话卡激活失败！请进行实名认证与绑定SIM卡。如您已实名认证，请5分钟后，再进行设备绑定。';
            /* Dialog.confirm({ title: "SIM卡激活失败", message: data.message, className: "device_confirm", }); */
          } else if (data.stateCode === 1 && data.message !== 'ok') {
            this.isShow = true;
            this.iccidShow = true;
            this.isPageShow = true;
            this.canNext = true;
            /* this.countDown(); */
            /* Dialog.confirm({ title: "SIM卡激活成功", message: '卡激活成功，5分钟后则可正常使用。', className: "device_confirm", }); */
          } else if (data.stateCode === 1 && data.message === 'ok') {
            this.isShow = false;
            this.iccidShow = false;
            this.isPageShow = false;
            this.onSubmit();
          } else if (data.stateCode === 2) {
            // 2023/5/25 ,新增 一个条件可以直接绑定，不需要用户继续操作
            this.isShow = false;
            this.iccidShow = false;
            this.isPageShow = false;
            this.onSubmit();
          } else if (data.stateCode === 0 && data.message === null) {
            // 2022 .4 .22 还有一种情况 stateCode === 0 并且 返回的message === null 也直接跳过不调小台风激活接口
            this.isShow = false;
            this.iccidShow = false;
            this.isPageShow = false;
            this.onSubmit();
          } else if (data.stateCode === 3) {
            // 2023/7/5 ,新增 一个条件可以直接绑定，不需要用户继续操作
            this.isShow = false;
            this.iccidShow = false;
            this.isPageShow = false;
            this.onSubmit();
          } else if (
            data.stateCode === 0 &&
            data.title === '直播' &&
            data.message === '请插入正确的电话卡进行设备激活'
          ) {
            // 2022 .4 .22 还有一种情况 stateCode === 0 并且 返回的message === null 也直接跳过不调小台风激活接口
            this.isShow = false;
            this.iccidShow = false;
            this.isPageShow = false;
            DialogService.confirm({
              title: '温馨提示',
              message: '为了更好地为您服务，请务必使用我司提供的电话卡。有疑问请来电400 002 3393咨询。'
            }).then(() => {
              this.$router.push({ name: 'deviceBinding' });
            });
          }
        })
        .catch(error => {
          console.log('出错了:;', error);
        })
        .finally(() => {
          ToastService.clear();
        });
    },
    // 60秒倒计时
    countDown() {
      this.timer = setInterval(() => {
        if (this.bindTime) {
          this.bindTime--;
          if (this.bindTime === 0) {
            this.canNext = true;
          }
        } else {
          this.bindTime = 60;
          clearInterval(this.timer);
        }
      }, 1000);
    },
    decodeSerialNo() {
      let url = `/api/Device/DecodeImei`;
      let headers = { headers: { AuthKey: 'key1' } };
      let reqBody = { code: this.serialNo };
      this.$axios
        .post(url, reqBody, headers)
        .then(res => {
          let data = res.data;
          if (data.stateCode === 1) {
            let newData = isComma(data.data);
            this.decodedSerialNo = newData.imei || data.data;
            // 如果返回的数据有逗号, 根据类型放到store里面
            if (newData) {
              if (newData.type === 'iccId') {
                this.$store.commit('iccId', newData.data);
              } else if (newData.type === 'rfId') {
                this.$store.commit('rfId', newData.data);
              }
            }
          }
        })
        .catch(e => {
          console.log(e);
        });
    },
    /**
     * 使用新设备的接口，参数为加密的 cid
     */
    getAdminOfCidByScan() {
      this.loading = true;
      let reqBody = { url: `?cid=${this.serialNo}` };
      APIDevice.bindingScan(reqBody)
        .then(res => {
          let data = res.data.data;
          if (res.data.stateCode === 1) {
            // TODO isAdmin true:该请求为管理员，false:该请求为家属（需要提示用户等待管理员的通过）
            this.isAdmin = data.isAdmin;
            this.$store.commit('isAdmin', data.isAdmin);
            this.$router.push({
              name: 'relation',
              query: {
                serialNo: data.serialNo,
                isAdmin: data.isAdmin,
                iccid: this.iccid
              }
            });
          } else if (
            res.data.stateCode === 0 &&
            res.data.message.indexOf('已经有用户获取安全码，请一分钟后再试') > -1
          ) {
            this.$router.push({
              name: 'relation',
              query: {
                serialNo: data.serialNo,
                isAdmin: data.isAdmin,
                iccid: this.iccid
              }
            });
          } else {
            DialogService.confirm({ title: res.data.message });
          }
        })
        .catch(e => {
          console.log(e);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * 扫码
     * 参数为明文的 id/serialNo
     */
    getAdminOfIdByScan() {
      this.loading = true;
      let reqBody = { url: `?id=${this.serialNo}` };
      APIDevice.bindingScan(reqBody)
        .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 ? 'index' :  */ 'relation',
              query: {
                serialNo: data.serialNo,
                isAdmin: data.isAdmin,
                iccid: this.iccid
              }
            });
          } else if (
            res.data.stateCode === 0 &&
            res.data.message.indexOf('已经有用户获取安全码，请一分钟后再试') > -1
          ) {
            this.$router.push({
              name: 'relation',
              query: {
                serialNo: data.serialNo,
                isAdmin: data.isAdmin,
                iccid: this.iccid
              }
            });
          } else {
            DialogService.confirm({ title: res.data.message });
          }
        })
        .catch(e => {
          console.log(e);
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  position: relative;
  .content {
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .tips {
      font-size: 30px;
      color: #aaa;
    }
    .text {
      margin-bottom: 50px;
    }
    .iccid-text {
      font-size: 32px;
      padding: 10px 40px;
      margin: 40px;
      .span-red {
        color: red;
      }
      img {
        height: 40px;
        line-height: 80px;
        margin: 10px 10px 0 10px;
        width: 100px;
        background-repeat: no-repeat;
        background-size: cover;
      }
    }
    .van-button {
    }
    .submit-button,
    .cancel-button {
      .van-button--normal {
        width: 300px;
        height: 60px;
        line-height: 60px;
        font-size: 15px;
        .van-loading__spinner {
          width: 25px !important;
          height: 25px !important;
        }
      }
    }
    .cancel-button {
      margin-top: 20px;
    }
  }
}
</style>
