<template>
  <div class="es-retrial-auth" v-loading.fullscreen.lock="submit">
    <es-qr-code
      :width="200"
      :height="200"
      :content="uuid"
      :logo="qrImg"
      v-if="active === 'SCANCODE'"
    ></es-qr-code>
    <el-form ref="auth" class="es-retrial-auth-form" :model="formData" v-else>
      <el-form-item>
        <div>
          验证码将发送至{{
            active == 'WEB_SMS' ? `手机号：${phoneText}` : `邮箱：${emailText}`
          }}
        </div>
      </el-form-item>
      <el-form-item
        size="large"
        prop="verificationCode"
        :rules="[
          { required: true, message: '验证码不能为空', trigger: 'change' }
        ]"
      >
        <el-input
          size="large"
          name="verificationCode"
          type="text"
          v-model="formData.verificationCode"
          placeholder="请输入验证码"
          autocomplete="off"
          class="es-label-image-code"
        >
          <template slot="suffix">
            <el-button
              class="es-get-code"
              type="primary"
              :disabled="disabled"
              @click.stop="getCode"
              >{{ btnText }}</el-button
            >
          </template>
        </el-input>
      </el-form-item>
      <el-button class="es-button-submit" type="primary" @click="handleAuth"
        >提交验证</el-button
      >
    </el-form>
    <div v-if="type && type.length > 1" class="es-login-switchs">
      <i
        v-for="(item, index) in icons"
        @click="handleSwitch(index)"
        :key="index"
        :class="[item, 'es-icon', { 'es-active': active == index }]"
      ></i>
    </div>
  </div>
</template>
<script>
import util from 'eoss-ui/src/utils/util';
import {
  initRetrialAuth,
  getRetrialAuthCode,
  scanCodeRetrialAuth,
  codeRetrialAuth
} from 'eoss-ui/src/config/api.js';
export default {
  name: 'EsRetrialAuth',
  inheritAttrs: false,
  props: {
    reload: Boolean,
    group: String,
    type: Array,
    msgBox: {}
  },
  computed: {
    icons() {
      let icons = {};
      for (let i in this.fonts) {
        if (this.type.includes(i)) {
          icons[i] = this.fonts[i];
        }
      }
      return icons;
    }
  },
  watch: {
    active: {
      handler(val) {
        if (val === 'SCANCODE' && this.uuid) {
          this.$nextTick(() => {
            this.handleScanCodeRetrialAuth();
          });
        }
      }
    }
  },
  data() {
    return {
      userModel: {},
      active: this.type[0],
      formData: {
        verificationCode: ''
      },
      fonts: {
        SCANCODE: 'es-icon-saoma',
        WEB_SMS: 'es-icon-solid-duanxin',
        WEB_EMAIL: 'es-icon-youxiang'
      },
      uuid: '',
      qrImg: '',
      emailText: null,
      phoneText: null,
      disabled: false,
      btnText: '获取验证码',
      countdown: 0,
      timer: null,
      scanCode: null,
      submit: false
    };
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      let mainConfig = util.getStorage('mainConfig');
      mainConfig && (this.userModel = JSON.parse(mainConfig).userModel);
      util
        .ajax({
          url: initRetrialAuth
        })
        .then((res) => {
          let { rCode, results } = res;
          if (rCode == 0) {
            this.uuid = results.uuid;
            this.qrImg = results.qrImg;
            this.emailText = results.emailText;
            this.phoneText = results.phoneText;
            if (this.active === 'SCANCODE') {
              this.handleScanCodeRetrialAuth();
            }
          }
        })
        .catch();
    },
    handleAuth() {
      if (this.submit) {
        return false;
      }
      this.$refs['auth'].validate((valid) => {
        if (valid) {
          this.submit = true;
          let params = {
            retrialAuthGroupIds: this.group,
            targetType: this.active === 'WEB_SMS' ? 'SMS' : 'EMAIL',
            verificationCode: this.formData.verificationCode
          };
          util
            .ajax({
              url: codeRetrialAuth,
              method: 'post',
              data: params
            })
            .then((res) => {
              let { rCode, msg } = res;
              if (rCode == 0) {
                this.$message({
                  message: '认证成功',
                  type: 'success'
                });
                this.msgBox.handleClose();
                const topWin = util.getWinTop();
                try {
                  if (this.reload) {
                    topWin.location.reload();
                  }
                } catch (error) {
                  console.warn('Failed to reload page:', error);
                  try {
                    this.reload && topWin.postMessage({ type: 3 }, '*');
                  } catch (postMessageError) {
                    console.warn(
                      'Failed to send postMessage:',
                      postMessageError
                    );
                  }
                }
              } else {
                this.$message({
                  message: msg,
                  type: 'error'
                });
                this.submit = false;
              }
            })
            .catch();
        }
      });
    },
    handleSwitch(res) {
      clearTimeout(this.scanCode);
      this.active = res;
    },
    getCode() {
      if (this.countdown) {
        return false;
      }
      let params = { targetType: this.active === 'WEB_SMS' ? 'SMS' : 'EMAIL' };
      this.countdown = 60;
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
          this.disabled = true;
          this.btnText = '重新获取' + this.countdown + 's';
        } else {
          this.btnText = '重新获取';
          this.disabled = false;
          this.submit = false;
        }
      }, 1000);
      util
        .ajax({
          url: getRetrialAuthCode,
          method: 'post',
          data: params,
          params: params
        })
        .then((res) => {
          let { rCode } = res;
          if (rCode == 0) {
            this.$message({
              message:
                '验证码已发送至' +
                (this.active === 'WEB_SMS' ? '手机' : '邮箱') +
                '，请注意查收！',
              type: 'success'
            });
          }
        })
        .catch();
    },
    handleScanCodeRetrialAuth() {
      clearTimeout(this.scanCode);
      let params = {
        phone: this.userModel.phone,
        retrialAuthGroupIds: this.group,
        uuid: this.uuid
      };
      util
        .ajax({
          url: scanCodeRetrialAuth,
          method: 'post',
          data: params,
          params: params
        })
        .then((res) => {
          let { rCode, results } = res;
          if (rCode == 0) {
            if (results.authPass) {
              this.$message({
                message: '认证成功',
                type: 'success'
              });
              this.msgBox.handleClose();
              const topWin = util.getWinTop();
              try {
                if (this.reload) {
                  topWin.location.reload();
                }
              } catch (error) {
                console.warn('Failed to reload page:', error);
                try {
                  this.reload && topWin.postMessage({ type: 3 }, '*');
                } catch (postMessageError) {
                  console.warn('Failed to send postMessage:', postMessageError);
                }
              }
            } else {
              this.scanCode = setTimeout(() => {
                this.handleScanCodeRetrialAuth();
              }, 1000);
            }
          }
        })
        .catch();
    },
    clearTimeouts() {
      clearTimeout(this.scanCode);
      clearTimeout(this.timer);
    }
  },
  beforeDestroy() {
    clearTimeout(this.scanCode);
    clearTimeout(this.timer);
  }
};
</script>
