<script setup lang="ts">
// #ifdef WEB
import clickCaptcha from '../click-captcha/click-captcha'
// #endif
import { reactive, ref, watch } from 'vue'
import { getCaptchaCodeApi, sendSmsCode } from '@/api/common'
import { uuid } from '@/utils/common'

const props = defineProps<{
  // 手机号码
  phone: string
  // 短信模板标识
  template_code: string
  // 短信验证码
  sms_captcha: string
  // 用户名
  username?: string
  // 密码
  password?: string
  // 表单配置项
  options?: any
  // 点击前事件
  beforeSend?: () => boolean
}>()

const form = reactive({
  captcha_id: uuid(),
  captcha_info: '',
  sms_captcha: props.sms_captcha,
  send_count_down: 0,
  phone: props.phone,
  click_captcha: false,
  username: props.username,
  password: props.password,
  captcha: '',
})

// #ifdef MP-WEIXIN
const captchaPopup = ref()
const dialogPopup = ref()

const getCaptchaImg = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    form.captcha_id = uuid()
    getCaptchaCodeApi(form.captcha_id)
      .then((res: any) => {
        // 图片转base64
        const base64String = uni.arrayBufferToBase64(res)
        form.captcha = 'data:image/png;base64,' + base64String
        resolve()
      })
      .catch((error) => {
        console.log('验证码获取失败', error)
        reject(error)
      })
  })
}

// #endif

const emits = defineEmits(['update:sms_captcha'])

const onBeforeSendSmsCode = () => {
  if (props.beforeSend) {
    const beforeSendResult = props.beforeSend()
    if (beforeSendResult === false) {
      return
    }
  }

  if (form.send_count_down > 0) return

  if (!/^(1[3-9])\d{9}$/.test(props.phone.toString())) {
    return uni.showToast({
      title: '手机号码格式不正确',
      icon: 'none',
    })
  }

  // #ifdef WEB
  clickCaptcha(form.captcha_id, (captchaInfo: string) => onSendSmsCode(captchaInfo))
  form.click_captcha = true
  // #endif

  // #ifdef MP-WEIXIN
  form.captcha_info = ''
  form.click_captcha = false
  getCaptchaImg().then(() => {
    captchaPopup.value.open()
  })
  // #endif
}

const onSendSmsCode = async (captchaInfo: string) => {
  // #ifdef MP-WEIXIN
  if (!captchaInfo) {
    return uni.showToast({
      title: '验证码不能为空',
      icon: 'none',
    })
  }
  captchaPopup.value.close()
  // #endif

  form.captcha_info = captchaInfo

  console.log(props.username, form.username)

  try {
    const params = {
      mobile: props.phone,
      template_code: props.template_code,
      captcha_id: form.captcha_id,
      captcha_info: form.captcha_info,
      click: form.click_captcha,
      password: form.password,
    }
    if (form.username) {
      Object.assign(params, { username: form.username })
    }

    const res = await sendSmsCode(params)

    // 发送成功
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })

    let countDown = 60
    form.send_count_down = countDown
    let timer = setInterval(() => {
      countDown--
      form.send_count_down = countDown
      if (countDown === 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (err: any) {
    console.log(err)
    uni.showToast({
      title: err.data.msg,
      icon: 'none',
    })
  }
}

watch(
  () => form.sms_captcha,
  (newVal) => {
    emits('update:sms_captcha', newVal)
  },
)
watch(
  () => props.username,
  (newVal) => {
    form.username = newVal
  },
)
watch(
  () => props.password,
  (newVal) => {
    form.password = newVal
  },
)
</script>
<template>
  <view>
    <!-- 短信验证码 -->
    <uni-forms-item v-bind="props.options" name="sms_captcha_code" class="input">
      <view style="display: flex; align-items: center">
        <uni-easyinput v-model="form.sms_captcha" placeholder="请输入短信验证码" />
        <text
          class="send-button"
          @tap="onBeforeSendSmsCode"
          style="margin-left: 40rpx; width: 210rpx"
        >
          <text v-if="!form.send_count_down">发送短信验证码</text>
          <text v-else>
            <text style="color: red">{{ form.send_count_down }}</text> 秒后可重新发送</text
          >
        </text>
      </view>
    </uni-forms-item>
  </view>

  <!-- #ifdef MP-WEIXIN -->
  <uni-popup ref="captchaPopup" type="dialog">
    <uni-popup-dialog
      ref="dialogPopup"
      mode="base"
      title="验证码"
      :before-close="true"
      @confirm="onSendSmsCode(form.captcha_info)"
      @close="dialogPopup.close()"
    >
      <view class="captcha-container">
        <image :src="form.captcha" mode="scaleToFill" class="captcha-img" @tap="getCaptchaImg()" />
        <uni-forms-item required>
          <uni-easyinput
            v-model="form.captcha_info"
            placeholder="请输入验证码"
            :clearable="false"
          />
        </uni-forms-item>
      </view>
    </uni-popup-dialog>
  </uni-popup>
  <!-- #endif -->
</template>
<style lang="scss" scoped>
.send-button {
  right: 0;
  top: 0;
  width: 6.875rem;
  text-align: center;
  font-size: 12px;
  font-size: 24rpx;
}

.captcha-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
}

.captcha-img {
  width: 300rpx;
  height: 120rpx;
  padding-bottom: 30rpx;
}
</style>
