<template>
  <Modal
    v-model="phoneModal"
    :closable="false"
    :mask-closable="false"
    title="请验证预留手机号"
    :footer-hide="true"
  >
    <div
      style="display: grid; grid-template-rows: 40px 40px 40px; font-size: 20px"
    >
      <p>
        预留手机号: &nbsp;&nbsp;{{
          user.phoneNumber
        }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      </p>
      <p>
        输入验证码: &nbsp;&nbsp;<input
          v-model="code"
          size="6"
          placeholder="验证码"
          type="number"
        />
        &nbsp;&nbsp;
      </p>
      <div>
        <i-button
          style="margin: 0; margin-right: 5px"
          class="qm-primary-button"
          :disabled="remainTime > 0"
          @click="getCode"
          >{{ btnText }} {{ remainTime > 0 ? "(" + remainTime + "秒)" : "" }}
        </i-button>
        <i-button
          style="margin: 0; margin-right: 5px"
          class="qm-primary-button"
          :disabled="!code"
          @click="verify"
        >
          验证
        </i-button>
        <i-button
          style="margin: 0; margin-right: 5px"
          class="qm-primary-button"
          @click="() => logout('?LogoutReason=验证预留手机号')"
        >
          退出系统
        </i-button>
      </div>
    </div>
  </Modal>
</template>

<script>
import { mapState as globalMapState } from "vuex";

export default {
  name: "PhoneVerifyForDD",
  data() {
    return {
      courses: [],
      phoneModal: false,
      step: "1",
      code: "",
      remainTime: 0,
      btnText: "发送验证码",
    };
  },
  computed: {
    ...globalMapState(["user"]),
  },
  async mounted() {
    if (
      ["cugr.ecs.qmth.com.cn", "test.cugr.qmth.com.cn"].includes(
        localStorage.getItem("domain")
      ) &&
      !localStorage.getItem("phoneVerified")
    ) {
      this.phoneModal = true;
    }
  },
  methods: {
    async getCode() {
      try {
        await this.$http.post("/api/ecs_oe_student/sms/sendSmsCodeToStudent");
      } catch (error) {
        this.$Message.error({
          content: "发送验证码失败，请重试！",
          duration: 15,
          closable: true,
        });
        return;
      }

      this.remainTime = 90;
      let interval = setInterval(() => {
        this.remainTime--;
        if (this.remainTime <= 0) {
          clearInterval(interval);
        }
      }, 1000);
    },
    async verify() {
      try {
        await this.$http.post(
          `/api/ecs_oe_student/sms/checkSmsCode?phoneNumber=${this.user.phoneNumber}&code=${this.code}`
        );
        this.phoneModal = false;
        localStorage.setItem("phoneVerified", "true");
      } catch (error) {
        this.$Message.error({
          content: "验证手机号接口失败，请重试！",
          duration: 15,
          closable: true,
        });
      }
    },
  },
};
</script>

<style scoped>
.home {
  margin: 20px;
}
</style>
