<template>
  <div class="relation">
    <van-nav-bar title="设备使用者角色" left-arrow @click-left="onBack" />
    <div class="title">
      <div class="role-user-container">
        <div class="radio-box" v-for="(item, index) in radios" :key="item.id">
          <span class="radio" :class="{ on: item.isChecked }" @click="onChooseRole(item.value, index)"></span>
          <input
            v-model="roleRadio"
            :value="item.value"
            class="input-radio"
            :checked="item.isChecked"
            type="radio"
          /><label>{{ item.label }}</label>
        </div>
      </div>
      <p class="main">您是设备使用者的：</p>
    </div>
    <div class="content">
      <div class="item" v-show="roleRadio === '1'">
        <div
          class="list"
          v-for="(item, index) in listData"
          :key="`relation_${index}`"
          @click="listClick(index, item.name, item.className)"
        >
          <div :class="[item.className, 'img', { active: active == index }]"></div>
          <span>{{ item.name }}</span>
        </div>
      </div>
      <div class="item" v-show="roleRadio === '2'">
        <div
          class="list"
          v-for="(item, index) in newListData"
          :key="`relation_${index}`"
          @click="newListClick(index, item.name, item.className)"
        >
          <div :class="[item.className, 'img', { active: active == index }]"></div>
          <span>{{ item.name }}</span>
        </div>
      </div>
    </div>

    <div class="submit" @click="submit">确定</div>

    <van-dialog
      v-model="selectConfirm"
      :show-cancel-button="true"
      :close-on-click-overlay="true"
      overlay-class="mask_device"
      @confirm="confirm"
      @cancel="cancel"
      @closed="onClosedDialog"
    >
      <div class="device_confirm">
        <div class="title">请输入身份</div>
        <div class="dialog-container">
          <label>
            <input type="text" v-model.trim="value" maxlength="8" />
          </label>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import ToastService from '@/services/toast-service';
import DialogService from '@/services/dialog-service';
import APIDevice from '@/api/device';
import APICommand from '@/api/command';
export default {
  data() {
    return {
      value: '',
      selectConfirm: false,
      listData: [
        { name: '爸爸', className: 'father' },
        { name: '妈妈', className: 'monther' },
        { name: '爷爷', className: 'grandpa' },
        { name: '奶奶', className: 'grandma' },
        { name: '姥爷', className: 'grandfather' },
        { name: '姥姥', className: 'grandmonther' },
        { name: '其他', className: 'other' }
      ],
      newListData: [
        { name: '儿子', className: 'father' },
        { name: '女儿', className: 'monther' },
        { name: '侄子', className: 'grandpa' },
        { name: '侄女', className: 'grandma' },
        { name: '孙子', className: 'grandfather' },
        { name: '孙女', className: 'grandmonther' },
        { name: '其他', className: 'other' }
      ],
      roleRadio: '1',
      radios: [
        {
          label: '学生',
          value: '1',
          isChecked: false
        },
        {
          label: '长辈',
          value: '2',
          isChecked: false
        }
      ],
      active: -1,
      second: 5,
      navigate: {
        timer: null,
        second: 10
      },
      isFromInfos: null, //是否从用户信息页面跳转过来
      infosData: null, //用户信息
      isHasOtherName: null //是否有“其他"
    };
  },
  created() {
    this.checkRoute();
  },
  mounted() {
    /* this.checkEffective(); */
  },
  methods: {
    countDown(codeTime, isSubmit) {
      let codeInterval = window.setInterval(() => {
        if (--codeTime <= 0) {
          window.clearInterval(codeInterval);
        }
        ToastService.loading({
          message: `设备初始化，请在${codeTime}秒后再操作绑定\n`
        });
        if (codeTime <= 0) {
          ToastService.clear();
          if (isSubmit) {
            setTimeout(() => {
              this.submit();
            }, 800);
          }
        }
      }, 1000);
    },
    checkRoute() {
      let params = this.$route.query;
      console.log('params', params);
      if (params) {
        if (params.fromRoute === 'infos') {
          this.isFromInfos = true;
          this.getInfos();
        } else {
          this.radios[0].isChecked = true;
        }
      }
    },
    // 获取用户信息
    getInfos() {
      APIDevice.getPersonInfo({ userId: this.$store.getters.userId, deviceId: this.$store.getters.deviceId }).then(
        res => {
          if (res.data.stateCode === 1) {
            this.infosData = res.data;
            this.initRelation();
          } else {
            DialogService.confirm({
              title: res.data.message
            }).then(() => {
              this.$router.push({ name: 'infos' });
            });
          }
        }
      );
    },
    // 初始化用户选择列表
    initRelation() {
      const infosData = this.infosData;
      // 1. 初始化 学生 老人单选按钮
      this.roleRadio = String(infosData.userRole);
      let radiosIndex = this.radios.findIndex(item => {
        return item.value === String(infosData.userRole);
      });
      this.radios[radiosIndex].isChecked = true;
      // 2. 初始化 家长身份列表以及已经设置好的身份名字
      let relationName = infosData.relationName;
      console.log('infosData', infosData);
      let currentList = String(infosData.userRole) === '1' ? this.listData : this.newListData;
      this.isHasOtherName = currentList.some(item => {
        return item.name === relationName;
      });
      if (relationName === '其他' || !this.isHasOtherName) {
        // 存在其他或者不属于指定的家长身份
        currentList = currentList.filter(item => {
          return item.name !== '其他';
        });
        this.active = 6;
        this.selectConfirm = true;
        this.value = relationName;
        console.log('1', currentList, relationName, currentList.includes(relationName));
      } else {
        currentList = currentList.filter(item => {
          return item.name !== '其他';
        });
        this.active = currentList.findIndex(item => {
          return item.name === relationName;
        });
        this.value = relationName;
        console.log('2', currentList, currentList.includes(relationName));
      }
    },
    //   返回
    onBack() {
      if (this.isFromInfos) {
        this.$router.push({ name: 'infos' });
      } else {
        this.$router.push({ name: 'deviceBinding' });
      }
    },
    //   判断是否需要显示中亿的自动激活功能
    checkEffective() {
      if (this.$own.isNotNull(this.$route.query.iccid)) {
        this.effective();
      }
    },
    // 中亿物联联通卡 SIM自动激活
    async effective() {
      let reqBody = {
        imei: this.$route.query.serialNo,
        iccid: this.$route.query.iccid,
        issue: 0
      };
      APICommand.Effective(reqBody)
        .then(res => {
          console.log('res', res);
          let data = res.data;
          if (data.stateCode === 0) {
            DialogService.confirm({ title: 'SIM卡激活失败', message: '请进行实名认证与绑定SIM卡' });
          } else if (data.stateCode === 1 && data.message !== 'ok') {
            DialogService.confirm({ title: 'SIM卡激活成功', message: '卡激活成功，5分钟后则可正常使用。' });
          }
        })
        .catch(error => {
          console.log('出错了:;', error);
        });
    },
    listClick(index, name, className) {
      this.active = index;
      if (className == 'other') {
        if (this.isFromInfos) {
          // 如果是从用户信息页面过来的，点击列表的时候如果是其他，value 则为relationName，否则为空
          this.value = this.isHasOtherName ? '' : this.infosData.relationName;
        } else {
          this.value = '';
        }
        this.selectConfirm = !this.selectConfirm;
      } else {
        this.value = name;
      }
    },
    newListClick(index, name, className) {
      this.active = index;
      if (className == 'other') {
        if (this.isFromInfos) {
          // 如果是从用户信息页面过来的，点击列表的时候如果是其他，value 则为relationName，否则为空
          this.value = this.isHasOtherName ? '' : this.infosData.relationName;
        } else {
          this.value = '';
        }
        this.selectConfirm = !this.selectConfirm;
      } else {
        this.value = name;
      }
    },
    confirm() {},
    cancel() {
      if (!this.isFromInfos) {
        this.value = '';
      }
    },
    onClosedDialog() {
      let iconRule =
        // eslint-disable-next-line no-misleading-character-class, no-useless-escape
        /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;
      if (iconRule.test(this.value)) {
        DialogService.confirm({ title: '不能输入表情字符哦' }).then(() => (this.selectConfirm = true));
      }
    },
    onChooseRole(value, index) {
      console.log('选中的是', value);
      // 先取消所有选中项
      this.radios.forEach(item => {
        item.isChecked = false;
      });
      //再设置当前点击项选中
      this.roleRadio = this.radios[index].value;
      // 设置值，以供传递
      this.radios[index].isChecked = true;
      this.value = '';
      this.active = -1;
    },
    submit() {
      if (this.value == '') {
        DialogService.confirm({ title: '请选择家长身份', message: '若选择【其他】身份请不要留空' });
      } else {
        // this.bindDevice();
        // this.bindDeviceNew();
        if (this.isFromInfos) {
          // 调取保存用户信息接口
          this.updateInfos();
        } else {
          //正常绑定设备
          this.bindDevice();
        }
        /* if(process.env.NODE_ENV === 'production'){
                  this.bindDevice();
              } else {
                  this.bindDeviceNew();
                  // 修改 测试环境的接口调用
                  this.bindDevice();
              } */
      }
    },
    updateInfos() {
      let jsonData = this.infosData;
      jsonData.userRole = Number(this.roleRadio);
      jsonData['userId'] = this.$store.getters.userId;
      jsonData['relationName'] = this.value;
      console.log('请求的参数', jsonData);
      APIDevice.updatePersonInfo(jsonData)
        .then(res => {
          ToastService.clear();
          console.log(res.data);
          if (res.data.stateCode == 1) {
            ToastService.success({
              message: '保存成功',
              onClose: () => this.onBack()
            });
          } else {
            DialogService.confirm({
              title: res.data.message
            });
          }
        })
        .catch(() => {})
        .finally(() => {
          //ToastService.clear();
        });
    },
    bindDevice() {
      /* const url = '/api/Device/BindDevice';
              const headers = { headers: { AuthToken: this.$store.getters.authToken } };
              const body = {
                  userId: this.$store.getters.userId,
                  serialNo: this.$route.query.serialNo,
                  relationName: this.value,
                  requestMessage: ``
              }; */
      ToastService.loading({});
      /* this.$axios.post(url, body, headers) */
      APIDevice.bindDevice({
        headers: { AuthToken: this.$store.getters.authToken },
        body: {
          userId: this.$store.getters.userId,
          serialNo: this.$route.query.serialNo,
          relationName: this.value,
          roleUser: Number(this.roleRadio),
          requestMessage: ``
        }
      })
        .then(res => {
          //                ToastService.clear();
          if (res.data.stateCode === 1) {
            if (this.$route.query.isAdmin) {
              // 该申请为管理员，直接提示绑定成功，缓存serialNo
              this.$store.commit('serialNo', this.$route.query.serialNo);
              this.$store.commit('bindSerialNo', this.$route.query.serialNo);
              DialogService.confirm({
                title: '绑定成功'
              }).then(() => {
                this.$router.push({
                  name: 'Index',
                  query: { isBinding: true, bindSerialNo: this.$route.query.serialNo }
                });
              });
              this.navigator(true);
            } else {
              // 该申请为家属，需要提示用户等待管理员的通过，不可缓存serialNo
              DialogService.confirm({
                title: '申请成功',
                message: '设备管理员同意通过便可查看宝贝信息，请耐心等待'
              }).then(() => {
                this.$router.push({ name: 'Index' });
              });
              this.navigator(false);
            }
          } else if (res.data.stateCode === 2) {
            DialogService.confirm({ title: '绑定成功', message: res.data.message }).then(() => {
              this.$router.push({ name: 'Index' });
            });
            this.navigator(false);
          } else if (res.data.message.indexOf('设备不在线') > -1) {
            DialogService.confirm({ title: '绑定失败', message: '设备不在线！请重新关机再开机，设备联网后再重试。' });
            return;
          } else if (
            res.data.stateCode === 0 &&
            res.data.message.indexOf('您已经绑定了宝贝信息，请勿重复绑定！') > -1
          ) {
            // 2022 04 25 修改重复绑定文案
            DialogService.confirm({
              title: '绑定失败',
              message: '您已绑定了随手精灵设备，请勿重复绑定！如设备显示未激活，请重启设备！',
              messageAlign: 'left'
            });
            return;
          } else if (res.data.stateCode === 3) {
            // 2023.11.26 绑定需求变更，返回状态码为3时进行以下操作
            let countdown = res.data.data;
            if (countdown > 5) {
              // 倒计时大于5秒，不需要倒计时完成后继续提交
              this.countDown(countdown, false);
            } else {
              // 小于5秒，倒计时完成后立即提交
              this.countDown(countdown, true);
            }
          } else {
            DialogService.confirm({ title: '绑定失败', message: res.data.message });
          }
        })
        .catch(e => {
          console.log(e);
        })
        .finally(() => ToastService.clear());
    },
    bindDeviceNew() {
      this.clearNaviagtor();

      //            const url = `/api/Device/BindDevice`;
      /* const url = `/api/Device/BindDeviceSsjl`;
              const headers = { headers: { AuthToken: this.$store.getters.authToken } };
              const body = {
                  userId: this.$store.getters.userId,
                  serialNo: this.$route.query.serialNo,
                  relationName: this.value,
                  requestMessage: ``
              }; */
      const toast = ToastService.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true
        //                message: `下发中请稍后`,
      });
      /* this.$axios.post(url, body, headers) */
      APIDevice.bindDeviceSsjl({
        headers: { AuthToken: this.$store.getters.authToken },
        body: {
          userId: this.$store.getters.userId,
          serialNo: this.$route.query.serialNo,
          relationName: this.value,
          requestMessage: ``
        }
      })
        .then(res => {
          if (res.data.stateCode === 1) {
            // ok
            const timer = setInterval(() => {
              this.second--;
              if (this.second >= 0) {
                toast.message = this.second ? `设备搜索中(${this.second})` : `设备搜索中`;
              } else {
                clearInterval(timer);
                ToastService.clear();
                // 5 秒后调取查询结果
                this.bindDeviceResult();
                this.second = 5;
              }
            }, 1000);
          } else if (
            res.data.stateCode === 0 &&
            res.data.message.indexOf('您已经绑定了宝贝信息，请勿重复绑定！') > -1
          ) {
            // 2022 04 25 修改重复绑定文案
            DialogService.confirm({
              title: '绑定失败',
              message: '您已绑定了随手精灵设备，请勿重复绑定！如设备显示未激活，请重启设备！',
              messageAlign: 'left'
            });
            return;
          } else {
            ToastService.clear();
            DialogService.confirm({ title: '绑定失败', message: res.data.message });
          }
        })
        .catch(e => {
          console.log(e);
          ToastService.clear();
        });
    },
    bindDeviceResult() {
      /* const url = `/api/Device/BindDeviceResult`;
              const headers = { headers: { AuthToken: this.$store.getters.authToken } };
              const body = {
                  userId: this.$store.getters.userId,
                  serialNo: this.$route.query.serialNo,
                  relationName: this.value,
                  requestMessage: ``
              }; */
      ToastService.loading({
        duration: 0, // 持续展示 toast
        message: `激活中，请稍侯`
      });
      /* this.$axios
                  .post(url, body, headers) */
      APIDevice.bindDeviceResult({
        headers: { AuthToken: this.$store.getters.authToken },
        body: {
          userId: this.$store.getters.userId,
          serialNo: this.$route.query.serialNo,
          relationName: this.value,
          requestMessage: ``
        }
      })
        .then(res => {
          if (res.data.stateCode === 1) {
            if (this.$route.query.isAdmin) {
              // 该申请为管理员，直接提示绑定成功，缓存serialNo
              this.$store.commit('serialNo', this.$route.query.serialNo);
              this.$store.commit('bindSerialNo', this.$route.query.serialNo);
              DialogService.confirm({
                title: '绑定成功'
              }).then(() => {
                this.$router.push({
                  name: 'Index',
                  query: { isBinding: true, bindSerialNo: this.$route.query.serialNo }
                });
                this.clearNaviagtor();
              });
              this.navigator(true);
            } else {
              // 该申请为家属，需要提示用户等待管理员的通过，不可缓存serialNo
              DialogService.confirm({
                title: '申请成功',
                message: '设备管理员同意通过便可查看宝贝信息，请耐心等待'
              }).then(() => {
                this.$router.push({ name: 'Index' });
                this.clearNaviagtor();
              });
              this.navigator(false);
            }
          } else if (res.data.stateCode === 2) {
            DialogService.confirm({ title: '绑定成功', message: res.data.message }).then(() => {
              this.$router.push({ name: 'Index' });
              this.clearNaviagtor();
            });
            this.navigator(false);
          } else if (
            res.data.stateCode === 0 &&
            res.data.message.indexOf('您已经绑定了宝贝信息，请勿重复绑定！') > -1
          ) {
            // 2022 04 25 修改重复绑定文案
            DialogService.confirm({
              title: '绑定失败',
              message: '您已绑定了随手精灵设备，请勿重复绑定！如设备显示未激活，请重启设备！',
              messageAlign: 'left'
            });
            return;
          } else {
            DialogService.confirm({ title: '绑定失败', message: res.data.message });
          }
        })
        .finally(() => ToastService.clear());
    },
    navigator(isBinding) {
      this.navigate.timer = setTimeout(() => {
        console.log('timer work');
        DialogService.close();
        this.$router.push({ name: 'Index', query: { isBinding: isBinding || false } });
      }, this.navigate.second * 1000);
    },
    clearNaviagtor() {
      clearTimeout(this.navigate.timer);
    }
  }
};
</script>
<style scoped lang="scss">
.relation {
  background: #fff !important;

  .title {
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    flex-direction: column;
    height: auto;
    margin: 40px 0 5px 0;
    padding: 0 40px;
    p {
      @include center();
      @include colorAndFont(#999, 35);

      &.main {
        margin: 30px 0 0 60px;
        @include colorAndFont(#333, 32);
      }
    }

    .role-user-container {
      display: flex;
      justify-content: flex-start;
      margin-left: 40px;

      .radio-box {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        height: 60px;
        margin-right: 10px;
        margin-left: 20px;

        .radio {
          display: inline-block;
          width: 20px;
          height: 20px;
          border-radius: 30px;
          border: gray solid 2px;

          &.on {
            border: #2599ff solid 15px;
          }
        }

        .input-radio {
          display: inline-block;
          position: absolute;
          /* opacity: 0; */
          width: 30px;
          height: 30px;
          left: 0px;
        }

        label {
          @include colorAndFont(#333, 32);
          margin-left: 15px;
        }
      }
    }
  }

  .content {
    .item {
      padding: 0 80px;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;

      .list {
        width: 140px;
        display: flex;
        align-items: center;
        flex-flow: column;
        margin: 0 85px 50px 0;

        &:nth-child(3n) {
          margin-right: 0;
        }

        .img {
          position: relative;
          width: 140px;
          height: 140px;
          background: #f1f5f9;
          border: 2px solid transparent;
          border-radius: 50%;
          box-sizing: border-box;
          @include center();

          &.active {
            border-color: #2599ff;
            background: #e0f0ff;

            &:after {
              content: ' ';
              position: absolute;
              right: -6px;
              bottom: 14px;
              width: 38px;
              height: 38px;
              border-radius: 50%;
              @include icon;
              @include icon_position(38, 38, 306, 56);
            }
          }

          &:before {
            content: '';
            width: 80px;
            height: 80px;
            @include head();
          }

          &.father:before {
            @include head_position(0, 0);
          }

          &.monther:before {
            @include head_position(100, 0);
          }

          &.grandpa:before {
            @include head_position(0, 85);
          }

          &.grandma:before {
            @include head_position(100, 85);
          }

          &.grandfather:before {
            @include head_position(0, 170);
          }

          &.grandmonther:before {
            @include head_position(100, 170);
          }

          &.other:before {
            @include head_position(0, 250);
          }
        }

        span {
          line-height: 1;
          @include colorAndFont(#333, 32);
          margin-top: 20px;
        }
      }
    }
  }

  .submit {
    @include center();
    margin: 20px auto;
    width: 578px;
    height: 88px;
    background: $blue;
    color: #fff;
    font-size: 34px;
    border-radius: 10px;
  }
  .device_confirm {
    .title {
      @include center();
      @include colorAndFont(#333, 34);
      padding: 40px px2rem(60);
    }

    .dialog-container {
      padding: 10px 40px 50px;
      @include colorAndFont(#666, 30);

      label {
        @include center();

        input {
          // width: 100%;
          display: flex;
          height: 72px;
          background: #e8ecef;
          border-radius: 10px;
          text-indent: 15px;
        }
      }

      &.phone {
        padding: 0 40px;
        text-align: center;
        box-sizing: border-box;

        .tit {
          padding: 30px 0 4px;
          @include colorAndFont(#333, 34);
          font-weight: 500;
          line-height: 100px;
        }

        p {
          padding: 0 50px;
          @include colorAndFont(#999, 28);
          margin-bottom: 40px;
        }

        input {
          display: flex;
          width: 100%;
          height: 70px;
          border-radius: 10px;
          background-color: #e8ecef;
          margin-bottom: 30px;
          text-align: center;
        }
      }
    }
  }
}
</style>
