<!-- 获取验证码 -->
<template>
  <view class="code as-gravity-center" :class="bg ? 'bg' : 'noBg'">
    <text class="code-btn" @click="sendSmsCode">
      {{ data.codeDuration ? data.codeDuration + "s" : "获取验证码" }}
    </text>
  </view>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { checkStr, msg } from "@/utils/utils";
import { request } from "@/utils/network/request";
import { sendCode } from "@/utils/network/api";

const props = defineProps({
  //手机号
  mobile: {
    type: String,
    default: "",
  },

  //短信模板编码
  templateCode: {
    type: String,
    default: "",
  },

  //有没有背景色
  bg: {
    type: Boolean,
    default: () => {
      return true;
    },
  },
});

let interval = null;
const data = reactive({
  //倒计时时长
  codeDuration: 0,
});

/*发送验证码*/
const sendSmsCode = async () => {
  // 有倒计时，则已发送
  if (data.codeDuration) {
    uni.showModal({
      content: `请在${data.codeDuration}秒后重试`,
      showCancel: false,
    });
    return;
  }

  if (!props.mobile) {
    msg("请输入手机号！");
    return;
  }

  if (!checkStr(props.mobile, "mobile")) {
    msg("手机号码格式不正确！");
    return;
  }
  const options = {
    type: 2,
    data: { mobile: props.mobile },
    method: "POST",
    showLoading: true,
  };
  request(sendCode, options).then((res) => {
    msg("验证码发送成功！");
    countdown();
  });
};

/* 倒计时 */
const countdown = () => {
  data.codeDuration = 60;
  interval = setInterval(() => {
    data.codeDuration--;
    if (data.codeDuration === 0) {
      if (interval) {
        clearInterval(interval);
        interval = null;
      }
    }
  }, 1000);
};
</script>

<style lang="scss">
.code {
  width: 180rpx;
  height: 50rpx;
  text-align: right;
}

.bg {
  background-color: #2ce242;
  border-radius: 10rpx;
  color: #ffffff;
  font-size: 24rpx;
}

.noBg {
  color: #00b38b;
  background-color: transparent;
  font-size: 28rpx;
}

.code-btn {
  line-height: 50rpx;
  text-align: right;
}
</style>
