<template>
  <app-view class="g-form register">
    <template #header>
      <app-navbar title="个人用户注册" />
    </template>
    <Form ref="formRef" class="g-form__container register__form" @submit="formSubmit">
      <CellGroup inset>
        <Field v-model="formData.mobilephone" type="tel" name="mobilephone" label="手机号码" placeholder="必填"
          autocomplete="off" :rules="formRules.mobilephone" />
        <Field v-model="formData.vcode" type="digit" name="vcode" label="短信验证码" placeholder="必填" autocomplete="off"
          :rules="formRules.vcode">
          <template #button>
            <Button size="small" type="primary" :disabled="isCountdown" @click="sendVerifyCode">
              <span v-if="isCountdown">重新发送({{ currentTime.seconds }})</span>
              <span v-else>获取验证码</span>
            </Button>
          </template>
        </Field>
        <Field v-model="formData.loginpwd" name="loginpwd" type="password" label="登录密码" placeholder="必填"
          autocomplete="off" :rules="formRules.loginpwd" />
        <Field v-model="formData.refernum" name="refernum" label="推荐码" placeholder="必填" autocomplete="off"
          :rules="formRules.refernum">
          <!-- <template #button>
            <app-qrcode-scan @success="onScanSuccess">
              <Button size="small" type="primary">扫码</Button>
            </app-qrcode-scan>
          </template> -->
        </Field>
      </CellGroup>
      <CellGroup inset>
        <Cell>
          <template #title>
            <div class="agreement">
              <Checkbox shape="square" icon-size=".32rem" v-model="checked">我已阅读并同意</Checkbox>
              <span @click="routerTo('rules-zcxy')" style="color:#E92020">《用户注册协议》</span>
              <span @click="routerTo('rules-yhkhfxgzs')" style="color:#E92020">《风险告知书》</span>
            </div>
          </template>
        </Cell>
      </CellGroup>
    </Form>
    <template #footer>
      <div class="g-form__footer">
        <Button type="primary" @click="formRef?.submit" round block>免费注册</Button>
      </div>
      <app-reward :show="showReward" :value="redEnvelope" title="注册成功！" @click="router.back()" />
    </template>
  </app-view>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { CellGroup, Cell, Button, Field, Form, FormInstance, Checkbox, Toast, FieldRule } from 'vant'
import { useCountDown } from '@vant/use'
import { fullloading, dialog } from '@/utils/vant'
import { validateRules } from '@/constants/regex'
import { useNavigation } from '@/hooks/navigation'
import { userRegister, sendRegisterVerifyCode, queryMyRegisterMoney } from '@/services/api/common'
import cryptojs from 'crypto-js'
import AppReward from '@mobile/components/modules/reward/index.vue'
// import AppQrcodeScan from '@mobile/components/base/qrcode-scan/index.vue'

const { router, routerTo } = useNavigation()
const formRef = ref<FormInstance>()
const checked = ref(false) // 是否同意注册条款
const isCountdown = ref(false) // 是否正在倒计时
const showReward = ref(false) // 显示红包
const redEnvelope = ref(0) // 红包金额

// 倒计时函数
const countdown = useCountDown({
  time: 30 * 1000,
  onFinish: () => {
    countdown.reset()
    isCountdown.value = false
  }
})

// 倒计时剩余时间
const currentTime = computed(() => countdown.current.value)

// 表单数据
const formData = reactive<Model.RegisterReq>({
  mobilephone: '',
  loginpwd: '',
  vcode: '',
  refernum: '',
  isaudit: 1,
  userinfotype: 1,
  usertype: 5,
  openmode: 5,
  lsitAgreementID: []
})

// 表单验证规则
const formRules: { [key in keyof Model.RegisterReq]?: FieldRule[] } = {
  mobilephone: [{
    required: true,
    message: '请输入手机号码',
    validator: (val) => {
      if (validateRules.phone.validate(val)) {
        return true
      }
      return validateRules.phone.message
    }
  }],
  loginpwd: [{
    required: true,
    message: '请输入登录密码',
    validator: (val) => {
      if (validateRules.password.validate(val)) {
        return true
      }
      return validateRules.password.message
    }
  }],
  vcode: [{
    required: true,
    message: '请输入短信验证码',
  }],
  refernum: [{
    required: true,
    message: '请输入推荐码',
  }],
}

// 扫码成功
// const onScanSuccess = (text: string) => {
//   formData.refernum = text
// }

// 发送手机验证码
const sendVerifyCode = () => {
  formRef.value?.validate('mobilephone').then(() => {
    sendRegisterVerifyCode({
      data: formData.mobilephone,
      success: () => {
        isCountdown.value = true
        countdown.start()
      },
      fail: () => {
        Toast.fail('发送失败')
      }
    })
  })
}

// 获取注册红包
const getRegisterMoney = (accountid: number) => {
  const toggleDialog = () => {
    dialog('您的账号已成功注册。').then(() => {
      router.back()
    })
  }
  return queryMyRegisterMoney({
    data: {
      accountid
    },
    success: (res) => {
      // 查询成功显示获得红包
      if (res.data.length) {
        redEnvelope.value = res.data[0].amount
        showReward.value = true
      } else {
        toggleDialog()
      }
    },
    fail: () => {
      // 查询失败提示注册成功后返回登录页面
      toggleDialog()
    }
  })
}

// 表单提交
const formSubmit = () => {
  if (checked.value) {
    fullloading((hideLoading) => {
      const { Utf8, Base64 } = cryptojs.enc
      // 密码需进行两次base64加密
      const passwordData = Base64.stringify(Utf8.parse(formData.loginpwd))
      const loginpwd = Base64.stringify(Utf8.parse(passwordData))

      userRegister({
        data: {
          ...formData,
          loginpwd
        },
        success: (res) => {
          if (res.code === 0) {
            // 等待3秒后查询注册红包
            setTimeout(() => {
              getRegisterMoney(res.taaccount[0].accountid).finally(() => {
                hideLoading()
              })
            }, 3000)
          } else {
            Toast.fail(res.message)
          }
        },
        fail: (err) => {
          Toast.fail(err)
        }
      })
    }, '正在注册...')
  } else {
    Toast('请先同意注册条款')
  }
}
</script>

<style lang="less" scoped>
@import './index.less';
</style>