<template>
  <van-popup v-model="showImgCode" class="imgCodePopup" :close-on-click-overlay="false" @close="onClose" closeable close-icon="close">
    <div class="imgCode">
      <p class="codeTitle">输入图形验证码</p>
      <van-row type="flex">
        <van-col span="14">
          <van-field placeholder="请输入验证码" v-model="code" style="background: #f4f4f4; padding: 0.12rem 0.16rem" :maxlength="4" autocomplete="off" />
        </van-col>
        <van-col span="10" class="img">
          <van-image :src="identifyingCode" @click="updateIdentifyingCode(true)">
            <template v-slot:loading>
              <van-loading type="spinner" size="20" />
            </template>
          </van-image>
        </van-col>
      </van-row>
      <van-row>
        <van-col span="14"></van-col>
        <van-col span="10">
          <span class="imgChange" @click="updateIdentifyingCode(true)">看不清？换一换</span>
        </van-col>
      </van-row>
    </div>
  </van-popup>
</template>

<script>
import { sendSmsCode } from "@/api/app";
export default {
  name: "imgCode",
  props: {
    value: Boolean,
    phone: String || Number,
  },
  data() {
    let origin = window.location.origin;
    return {
      showImgCode: this.value,
      identifyingCode: origin + "/api-teacher/code/getLoginImage?phone=" + this.phone,
      code: null,
    };
  },
  async mounted() {
    // let res = await getLoginImage({ phone: 15907121013 })
    // this.img = res.data
  },
  methods: {
    async updateIdentifyingCode() {
      // 刷新token
      let origin = window.location.origin;
      this.identifyingCode = `${origin}/api-teacher/code/getLoginImage?phone=${this.phone}&token=${Math.random()}`;
    },
    async checkVerifyLoginImage() {
      try {
        if (this.code.length < 4) {
          return;
        }
        // await verifyLoginImage({ phone: this.phone, code: this.code })
        await sendSmsCode({ mobile: this.phone, code: this.code });
        this.$toast("验证码已发送");
        this.$emit("input", false);
        this.$emit("onCodeSend", true);
      } catch {
        //
        this.updateIdentifyingCode();
      }
    },
    onClose() {
      this.$emit("input", false);
    },
  },
  watch: {
    code(newVal) {
      // 图形验证码位数大于4位时
      if (newVal.length >= 4) {
        this.checkVerifyLoginImage();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.imgCode {
  padding: 0.16rem;
  .codeTitle {
    text-align: center;
    font-size: 0.16rem;
    color: #4f4f4f;
    padding-bottom: 0.16rem;
  }
  .img {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .imgChange {
    display: block;
    color: #aaaaaa;
    font-size: 0.12rem;
    text-align: center;
    padding-top: 0.05rem;
  }
}

.imgCodePopup {
  width: 90%;
  border-radius: 0.05rem;
  overflow: inherit;
  /deep/.van-popup__close-icon {
    top: -37px !important;
    right: 0 !important;
    font-size: 0.25rem;
    color: #fff;
  }
}
</style>
