<template>
  <app-view class="g-form register">
    <template #header>
      <app-navbar :title="$t('user.register.title')" />
    </template>
    <Form ref="formRef" class="g-form__container register__form" @submit="formSubmit">
      <CellGroup inset>
        <Field v-model="formData.mobilephone" type="digit" name="mobilephone" :placeholder="$t('common.required')" :rules="formRules.mobilephone">
          <template #label>
            <span>{{ $t('user.register.mobile') }}</span>
            <span style="margin-left: 10px;" @click="show = true">
                {{ countryCode }}
            </span>
            <Popup v-model:show="show" position="bottom" teleport="body" round>
                <Picker :columns="datalist" @cancel="onCancel" @confirm="onConfirm" :confirm-button-text="$t('operation.confirm')" :cancel-button-text="$t('operation.cancel')">
                    <template #option="{ text, index }">
                        <slot name="option" :row="datalist[index]" :index="index">
                            {{ text }}
                        </slot>
                    </template>
                </Picker>
            </Popup>
          </template>
        </Field>
        <Field v-model="formData.vcode" type="digit" name="vcode" :label="$t('user.register.vcode')"
          :placeholder="$t('common.required')" :rules="formRules.vcode">
          <template #button>
            <Button size="small" type="danger" :disabled="loading" @click="sendVerifyCode">
              <span v-if="isCountdown">{{ $t('user.register.sendagain') }}({{ currentTime.seconds }})</span>
              <span v-else>{{ $t('user.register.getsmscode') }}</span>
            </Button>
          </template>
        </Field>
      </CellGroup>
      <CellGroup inset>
        <Field v-model="formData.loginpwd" name="loginpwd" type="password" :label="$t('user.register.logipwd')"
          :placeholder="$t('common.required')" :rules="formRules.loginpwd" />
        <Field v-model="confirmpassword" name="confirmpassword" type="password" :label="$t('user.register.confirmpwd')"
          :placeholder="$t('common.required')" :rules="formRules.confirmpassword" />
        <Field v-model="formData.refernum" name="refernum" :label="$t('user.register.registercode')"
          :placeholder="registrationCodeRule ? $t('common.required') : $t('common.optional')"
          :rules="formRules.refernum" v-if="registrationCodeRule > -1">
          <!-- <template #button>
            <app-qrcode-scan @success="onScanSuccess">
              <Button size="small" type="danger">扫码</Button>
            </app-qrcode-scan>
          </template> -->
        </Field>
      </CellGroup>
      <CellGroup inset>
        <Cell>
          <template #title>
            <div style="display: flex;align-items: center;font-size: 12px;">
              <Checkbox shape="square" icon-size="16px" v-model="checked">
                {{ $t('user.register.checked') }}
              </Checkbox>
              <span @click="routerTo('rules-zcxy')" style="color:#E92020">
                {{ $t('user.register.ruleszcxy') }}
              </span>
              <span @click="routerTo('rules-yhkhfxgzs')" style="color:#E92020" v-if="showYhkhfxgzs">
                {{ $t('user.register.rulesfxgzs') }}
              </span>
            </div>
          </template>
        </Cell>
      </CellGroup>
    </Form>
    <template #footer>
      <div class="g-form__footer inset">
        <Button type="danger" @click="formRef?.submit" round block>{{ $t('user.register.freeregister') }}</Button>
      </div>
      <app-reward :show="showReward" :value="redEnvelope" :title="$t('user.register.registersuccess')"
        @click="router.back()" />
    </template>
  </app-view>
</template>

<script lang="ts" setup>
import { reactive, shallowRef, ref, computed, onMounted } from 'vue'
import { CellGroup, Cell, Button, Field, Form, FormInstance, Checkbox, showFailToast, showToast, FieldRule, Popup, Picker, PickerConfirmEventParams } from 'vant'
import { useCountDown } from '@vant/use'
import { fullloading, dialog } from '@/utils/vant'
import { validateRules } from '@/constants/regex'
import { useNavigation } from '@mobile/router/navigation'
import { userRegister, sendRegisterVerifyCode, queryMyRegisterMoney } from '@/services/api/common'
import { i18n, useGlobalStore, useUserStore } from '@/stores'
import { getCountryCodeList } from '@/constants/unit'
import cryptojs from 'crypto-js'
import plus from '@/utils/h5plus'
import AppReward from '@mobile/components/modules/reward/index.vue'
// import AppQrcodeScan from '@mobile/components/base/qrcode-scan/index.vue'

defineProps({
  showYhkhfxgzs: {
    type: Boolean,
    default: true
  }
})

// 是否弹出选择器
const show = shallowRef(false) 
const datalist = computed(() => {
    return  getCountryCodeList().map(e => {
        return { text: e.value, value: e.value }
    })
})
const countryCode = ref(datalist.value[0]?.value.toString())

const onCancel = () => {
    show.value = false
}

const onConfirm = ({ selectedValues: [value] }: PickerConfirmEventParams) => {
    show.value = false
    countryCode.value = value.toString()
}

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

const { getSystemParamValue } = useUserStore()
const param1010 = getSystemParamValue('1010') ?? '1'
const param1013 = getSystemParamValue('1013') ?? '30'

const { global: { t } } = i18n

const confirmpassword = ref('') // 确认密码

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

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

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

// 表单验证规则
const formRules: { [key: string]: FieldRule[] } = {
  mobilephone: [{
    required: true,
    message: t('user.register.tips1'),
    validator: (val) => {
      /// 值为”0“ 时 只校验长度20位，不限字符
      if (param1010 === '0') {
        if (val.length <= 20) {
          return true
        }
        return t('banksign.tips6')
      } else {
        if (validateRules.phone.validate(val)) {
          return true
        }
        return validateRules.phone.message
      }
    }
  }],
  loginpwd: [{
    required: true,
    message: t('user.register.tips2'),
    validator: (val) => {
      if (validateRules.password.validate(val)) {
        return true
      }
      return validateRules.password.message
    }
  }],
  confirmpassword: [{
    required: true,
    message: t('user.register.tips3'),
    validator: (val) => {
      if (formData.loginpwd === val) {
        return true
      }
      return t('user.register.tips4')
    }
  }],
  vcode: [{
    required: true,
    message: t('user.register.tips5'),
  }],
  refernum: [{
    validator: (val) => {
      if (!registrationCodeRule || val) {
        return true
      }
      return t('user.register.tips6')
    }
  }],
}

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

// 发送手机验证码
const sendVerifyCode = () => {
  formRef.value?.validate('mobilephone').then(() => {
    loading.value = true
    sendRegisterVerifyCode({
      data: {
        phonenumber: countryCode.value+formData.mobilephone
      }
    }).then(() => {
      isCountdown.value = true
      countdown.start()
    }).catch(() => {
      loading.value = false
      showFailToast(t('user.register.tips7'))
    })
  })
}

// 获取注册红包
const getRegisterMoney = (accountid: number) => {
  const toggleDialog = () => {
    dialog(t('user.register.tips8')).then(() => {
      router.back()
    })
  }
  return queryMyRegisterMoney({
    data: {
      accountid
    }
  }).then((res) => {
    // 查询成功显示获得红包
    if (res.data.length) {
      redEnvelope.value = res.data[0].amount
      showReward.value = true
    } else {
      toggleDialog()
    }
  }).catch(() => {
    // 查询失败提示注册成功后返回登录页面
    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))
      const mobilephone = countryCode.value+formData.mobilephone

      userRegister({
        data: {
          ...formData,
          loginpwd,
          mobilephone
        }
      }).then((res) => {
        if (res.code === 0) {
          // 等待3秒后查询注册红包
          setTimeout(() => {
            getRegisterMoney(res.taaccount[0].accountid).finally(() => {
              hideLoading()
            })
          }, 3000)
        } else {
          showFailToast(res.message)
        }
      }).catch((err) => {
        showFailToast(err)
      })
    }, t('user.register.tips9'))
  } else {
    showToast(t('user.register.tips10'))
  }
}

onMounted(() => {
  const os = plus.getSystemInfo('os')
  if (os === 'Android') {
    formData.openmode = 5
  }
  if (os === 'iOS') {
    formData.openmode = 6
  }
})
</script>