<template>
  <div class="security-settings">
    <div v-if="status === 0" class="security-unverified">
      <img
        src="@/assets/personal_images/security-settings.png"
        class="security-image"
      />
      <p class="unverified-title">当前未开启二次验证</p>
      <p class="tips">开启二次验证，提升系统安全性</p>
      <div class="security-verified-button">
        <el-button type="primary" @click="openVerification">开启</el-button>
      </div>
    </div>
    <div v-if="status === 1" class="security-verified">
      <div class="verified-title">绑定中</div>
      <div class="security-verified-content">
        <div class="security-verified-qrcode">
          <canvas id="QRCode"></canvas>
        </div>
        <div class="security-verified-text">
          <div>
            <ul>
              <li>
                <span>username:</span>
                <span>{{ twoVerifyInfo.username }}</span>
              </li>
              <li>
                <span>host:</span>
                <span>{{ twoVerifyInfo.host }}</span>
              </li>
              <li>
                <span>secret:</span>
                <span>{{ twoVerifyInfo.secret }}</span>
              </li>
            </ul>
          </div>
          <div>
            <p class="security-verified-title">请输入手机app中的六位数验证码</p>
            <p class="security-verified-tips">
              使用app扫描左侧二维码，app将会生成验证码
            </p>
            <el-input
              v-model="verificationCode"
              maxlength="6"
              width="288px"
              placeholder="请输入验证码"
            />
          </div>
        </div>
      </div>
      <div class="security-verified-button">
        <el-button key="验证" type="primary" @click="toVerification">
          验证
        </el-button>
        <el-button plain @click="cancel">取消</el-button>
      </div>
    </div>
    <div v-if="status === 2" class="security-settting">
      <div class="verified-title">
        <i class="icon-bangdingchenggong" style="color: #50ab47"></i>
        恭喜您绑定成功！
      </div>
      <p class="security-settting-tips">
        以下为一次性验证码，可在紧急情况下进行验证登录，每个验证码仅可使用一次，建议下载至本地保存。
      </p>
      <div>
        <ul class="security-settting-list">
          <li v-for="(item, index) in verificationCodelist" :key="index">
            {{ item.code }}
          </li>
        </ul>
      </div>
      <div class="security-verified-button">
        <el-button type="primary" @click="complete">完成</el-button>
        <el-button
          plain
          class="cancel"
          style="width: 160px"
          :loading="downloadLoading"
          @click="handleDownload"
        >
          下载一次性验证码
        </el-button>
      </div>
    </div>
    <div v-if="status === 3" class="security-verified">
      <div class="verified-title">
        <i class="icon-yikaiqi" style="color: #0080fe"></i>
        二次验证已开启
      </div>
      <img
        src="@/assets/personal_images/security-open.png"
        class="security-open-image"
      />
      <div>
        <el-button type="primary" @click="rebind">重新绑定</el-button>
        <el-button plain style="width: 132px" @click="close">
          关闭二次验证
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import uc from '@/api/uc.js'
import QRCode from 'qrcode'
import {mapState} from 'vuex'
export default {
  name: 'SecuritySetting',
  data() {
    return {
      status: 0, // 0: 未开启 1: 绑定中 2:绑定完成 3：已开启
      verificationCode: '',
      verificationCodelist: [],
      twoVerifyInfo: {},
      isTwoStepVerifyAndBind: false,
      isOpen: false,
      width: '240',
      height: '240',
      downloadLoading: false
    }
  },
  computed: {
    ...mapState('tenant', ['tenantId'])
  },
  mounted() {
    this.isTwoStepVerifyAndBind =
      this.$route.query.isTwoStepVerifyAndBind || false
    if (this.isTwoStepVerifyAndBind) {
      const loginData = localStorage.getItem('loginData')
      this.twoVerifyInfo = JSON.parse(loginData)
      this.status = 1
      this.$nextTick(() => {
        this.foundQRCode()
      })
    } else {
      this.fetchTwoVerifyInfo()
    }
  },
  beforeDestroy() {
    localStorage.removeItem('loginData')
  },
  methods: {
    //开启验证
    openVerification() {
      this.init()
      this.status = 1
    },
    toVerification() {
      if (!this.verificationCode) {
        this.$message.warning('请输入验证码！')
        return
      }
      if (this.isTwoStepVerifyAndBind) {
        const formData = new FormData()
        formData.append('code', this.verificationCode)
        formData.append('token', this.twoVerifyInfo.tempToken)
        let tenantId = this.tenantId
        uc.twoStepVerifyAndBind(formData, tenantId)
          .then(res => {
            this.verificationCodelist = res.data.value
            this.status = 2
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        const formData = new FormData()
        formData.append('code', this.verificationCode)
        formData.append('secret', this.twoVerifyInfo.secret)
        uc.bindTwoStepVerifySecret(formData)
          .then(res => {
            this.verificationCodelist = res.data.value
            this.status = 2
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    complete() {
      if (this.isTwoStepVerifyAndBind) {
        this.$router.push('/login')
      } else {
        this.init()
        this.status = 3
        this.isOpen = true
      }
    },
    cancel() {
      if (this.isTwoStepVerifyAndBind) {
        this.$router.push('/login')
      } else if (this.isOpen) {
        this.status = 3
      } else {
        this.status = 0
      }
    },
    // 用户获取初始化双因素认证信息（个人设置）
    async init() {
      let {
        data: {value}
      } = await uc.initTwoVerifyInfo()
      this.twoVerifyInfo = value
      this.foundQRCode()
    },

    // 用户获取自己绑定的双因素认证信息（个人设置）
    async fetchTwoVerifyInfo() {
      let {data} = await uc.getTwoVerifyInfo()
      if (data && data.errorCode == '2003') {
        this.status = 0
        this.isOpen = false
      } else {
        this.twoVerifyInfo = data.value
        this.status = 3
        this.isOpen = true
      }
    },
    //生成二维码
    foundQRCode() {
      let width = this.width
      let height = this.height
      QRCode.toCanvas(
        document.getElementById('QRCode'),
        this.twoVerifyInfo.bindLink,
        {width, height, toSJISFunc: QRCode.toSJIS},
        error => {}
      )
    },
    close() {
      this.$confirm('确定关闭二次验证？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        uc.closeTwoStepVerify()
          .then(res => {
            this.$message.success(res.data.value)
            this.status = 0
            this.isOpen = false
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    rebind() {
      this.init()
      this.verificationCode = ''
      this.status = 1
    },
    //纯前端生成并下载Excel
    handleDownload() {
      if (this.verificationCodelist.length) {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['一次性验证码']
          const filterVal = ['code']
          const list = this.verificationCodelist
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: `一次性验证码_${new Date()}`
          })
          this.downloadLoading = false
        })
      } else {
        this.$message({
          message: '下载一次性验证码失败',
          type: 'warning'
        })
      }
    },
    //过滤生成Excel的数据
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
}
</script>

<style lang="scss" scoped>
.security-settings {
  // width: calc(100% - 340px);
  height: 100%;
  overflow-y: auto;
  background: linear-gradient(180deg, #fff 0%, #fff 100%);
  .security-unverified,
  .security-verified,
  .security-settting {
    display: flex;
    align-items: center;
    flex-direction: column;
    margin-top: 128px;
    .unverified-title {
      font-size: 32px;
      font-family: Source Han Sans SC;
      font-weight: bold;
      color: #222222;
      margin: 32px 0 20px;
    }
    .tips {
      color: #333;
      font-size: 16px;
      font-family: Source Han Sans SC;
      font-weight: 400;
    }
    .security-image {
      width: 520px;
      height: 250px;
    }
    .security-open-image {
      width: 428px;
      height: 434px;
    }
  }
  .security-verified-button {
    margin-top: 64px;
  }
  .security-verified {
    .verified-title {
      font-size: 32px;
      font-family: Source Han Sans SC;
      font-weight: bold;
      color: #222;
    }
    .security-verified-content {
      margin-top: 56px;
      width: 974px;
      height: 368px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgb(252, 252, 252);
      border: 1px solid #eeeeee;
      .security-verified-qrcode {
        background: rgb(255, 255, 255);
        border: 1px solid #e6e6e6;
      }
      .security-verified-text {
        margin-left: 57px;
        ul {
          li {
            font-family: Source Han Sans SC;
            line-height: 23px;

            &:nth-child(2) {
              margin: 16px 0;
            }
            span {
              &:first-child {
                display: inline-block;
                width: 91px;
                font-weight: 400;
                color: #888;
              }
            }
          }
        }
        .security-verified-title {
          font-size: 18px;
          margin-top: 24px;
          font-family: Source Han Sans SC;
          font-weight: bold;
        }
        .security-verified-tips {
          margin: 12px 0 19px;
          font-size: 14px;
        }
      }
    }
  }
  .security-settting {
    .security-settting-tips {
      font-family: Source Han Sans SC;
      font-weight: 400;
      color: #e55555;
      margin: 56px 0 32px;
    }
    .verified-title {
      font-size: 32px;
      font-family: Source Han Sans SC;
      font-weight: bold;
      color: #222;
    }
    .security-settting-list {
      width: 1004px;
      border: 1px solid #ebebeb;
      overflow: hidden;
      border-radius: 4px;
      list-style: none;
      li {
        float: left;
        width: 20%;
        text-align: center;
        height: 80px;
        line-height: 80px;
        color: #666;
        border-right: 1px solid #ebebeb;
        border-bottom: 1px solid #ebebeb;
        margin-right: -1px;
        margin-bottom: -1px;
      }
    }
  }
}
.security-settings ::v-deep.el-button {
  width: 108px;
}
</style>
