<template>
  <app-view class="register g-form g-layout">
    <template #header>
      <app-navbar :title="t('user.register.title')" :show-back-button="showBackButton" />
    </template>
    <app-switch-tab class="g-layout-block" v-model="selectedMethod" :options="openMethodList" @change="changeMethod"
      v-if="openMethodList.length > 1" />
    <Form ref="formRef" class="g-form__container g-layout-block" @submit="formSubmit">
      <CellGroup :inset="insetStyle" v-if="selectedMethod === 1">
        <Field :label="t('user.register.area')" right-icon="arrow" v-if="codeList.length">
          <template #input>
            <app-select v-model="selectedCode" :options="codeList">
              <span>+{{ selectedCode }}</span>
              <template #option="{ row }">
                +{{ row.value }}
              </template>
            </app-select>
          </template>
        </Field>
        <Field v-model="formData.mobilephone" type="digit" name="mobilephone" :label="t('user.register.mobile')"
          :placeholder="t('common.required')" :rules="formRules.mobilephone" />
        <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" :disabled="loading" @click="sendVerifyCode">
              <span v-if="isCountdown">{{ t('user.register.sendagain') }}({{ currentTime }})</span>
              <span v-else>{{ t('user.register.getsmscode') }}</span>
            </Button>
          </template>
        </Field>
      </CellGroup>
      <CellGroup :inset="insetStyle" v-if="selectedMethod === 2">
        <Field name="email" :label="t('user.register.emailregister')" v-model="formData.mobilephone"
          :placeholder="t('common.required')" :rules="formRules.email" />
        <Field v-model="formData.vcode" type="digit" name="vcode" :label="t('user.register.vscode')"
          :placeholder="t('common.required')" :rules="formRules.vcode">
          <template #button>
            <Button size="small" :disabled="loading" @click="sendVerifyCode">
              <span v-if="isCountdown">{{ t('user.register.sendagain') }}({{ currentTime }})</span>
              <span v-else>{{ t('user.register.getsmscode') }}</span>
            </Button>
          </template>
        </Field>
      </CellGroup>
      <CellGroup :inset="insetStyle">
        <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="insetStyle">
        <Cell>
          <template #title>
            <div style="display: flex;align-items: center;font-size: 13px;">
              <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>
    <div class="g-form__footer inset">
      <Button type="primary" @click="formRef?.submit" :round="insetStyle" block>
        {{ t('user.register.freeregister') }}
      </Button>
    </div>
    <app-reward :show="showReward" :value="redEnvelope" :title="t('user.register.registersuccess')"
      @click="routerAction" />
  </app-view>
</template>

<script lang="ts" setup>
import { reactive, shallowRef, ref, computed, onMounted, useAttrs } from 'vue'
import { CellGroup, Cell, Button, Field, Form, FormInstance, Checkbox, showFailToast, showToast, FieldRule, showSuccessToast } from 'vant'
import { useCountDown } from '@vant/use'
import { fullloading, dialog } from '@/utils/vant'
import { validateRules } from '@/constants/regex'
import { useFacebook } from '@/hooks/facebook'
import { useAppsFlyer } from '@/hooks/appsflyer'
import { useNavigation } from '@mobile/router/navigation'
import { userRegister, sendRegisterVerifyCode2, queryMyRegisterMoney } from '@/services/api/common'
import { i18n, useUserStore, useErrorInfoStore } from '@/stores'
import { getCountryCodeList } from '@/constants/unit'
import { getOpenMethodList } from '@/constants/common'
import service from '@/services'
import cryptojs from 'crypto-js'
import plus from '@/utils/h5plus'
import AppSwitchTab from '@mobile/components/base/switch-tab/index.vue'
import AppReward from '@mobile/components/modules/reward/index.vue'
import AppSelect from '@mobile/components/base/select/index.vue'
// import AppQrcodeScan from '@mobile/components/base/qrcode-scan/index.vue'

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

const emit = defineEmits<{ (event: string, ...args: unknown[]): void }>()

const { t } = i18n.global
const { trackEvent } = useFacebook()
const { logEvent } = useAppsFlyer()

const attrs = useAttrs()

const { router, routerTo, getQueryString } = useNavigation()
const errorInfoStore = useErrorInfoStore()
const registrationCodeRule = service.getAppConfig('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 openMethodList = getOpenMethodList() // 开户方式
const selectedMethod = shallowRef(1) // 选中的开户方式

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

const codeList = getCountryCodeList()
const selectedCode = shallowRef(codeList[0]?.value) // 选中的区号

// 用户名
const accountName = computed(() => {
  const prefix = selectedMethod.value === 1 ? (selectedCode.value ?? '') : ''
  return prefix + formData.mobilephone
})

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

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

// 倒计时剩余时间
const currentTime = computed(() => {
  const { total } = countdown.current.value
  return (total / 1000).toFixed(0)
})

// 表单数据
const formData = reactive<Model.RegisterReq>({
  mobilephone: '',
  loginpwd: '',
  vcode: '',
  refernum: getQueryString('code') ?? '',
  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
      }
    }
  }],
  email: [{
    required: true,
    message: t('user.register.tips12'),
    validator: (val) => {
      if (validateRules.email.validate(val)) {
        return true
      }
      return validateRules.email.message
    }
  }],
  loginpwd: [{
    required: true,
    message: t('user.register.tips2'),
    validator: (val) => {
      if (service.getAppConfig('strongPassword')) {
        if (validateRules.password.validate(val)) {
          return true
        }
        return validateRules.password.message
      }
      return val?.length < 6 ? t('user.register.tips13') : true
    }
  }],
  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 changeMethod = (value: number) => {
  formData.mobilephone = ''
  formData.vcode = ''
  selectedMethod.value = value
}

// 路由跳转
const routerAction = () => {
  // 追踪注册结果
  trackEvent('CompleteRegistration')

  logEvent('af_complete_registration', {
    af_registration_method: 'Mobile'
  })

  if (attrs.onRouterAction) {
    emit('routerAction')
  } else {
    router.back()
  }
}

// 清除数据
const resetData = () => {
  formData.mobilephone = ''
  formData.vcode = ''
  formData.loginpwd = ''
  confirmpassword.value = ''
  formData.refernum = ''
  checked.value = false
}

// 发送验证码
const sendVerifyCode = () => {
  const field = selectedMethod.value === 1 ? 'mobilephone' : 'email'

  formRef.value?.validate(field).then(() => {
    loading.value = true
    sendRegisterVerifyCode2({
      data: {
        param: accountName.value
      }
    }).then(() => {
      isCountdown.value = true
      countdown.start()
    }).catch(() => {
      loading.value = false
      showFailToast(t('user.register.tips7'))
    })
  })
}

// 获取注册红包
const getRegisterMoney = (accountid: number) => {
  const toggleDialog = () => {
    dialog({
      message: t('user.register.tips8'),
      confirmButtonText: t('operation.confirm')
    }).then(() => {
      routerAction()
    })
  }
  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))

      userRegister({
        data: {
          ...formData,
          mobilephone: accountName.value,
          loginpwd
        }
      }).then((res) => {
        if (res.code === 0) {
          if (res.taaccount != undefined) {
            // 等待3秒后查询注册红包
            setTimeout(() => {
              getRegisterMoney(res.taaccount[0].accountid).finally(() => {
                hideLoading()
              })
            }, 3000)
          } else {
            // 清除数据
            resetData()
            showSuccessToast(t('user.register.tips11'))
          }
        } else {
          const msg = errorInfoStore.getErrorInfoByCode(res.message)
          showFailToast(msg ?? res.message)
        }
      }).catch((err) => {
        const msg = errorInfoStore.getErrorInfoByCode(err)
        showFailToast(msg ?? 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
  }

  if (openMethodList.length) {
    selectedMethod.value = openMethodList[0].value
  }
})
</script>