<template>
  <el-form v-show="getShow" ref="formLogin" :model="registerData.registerForm" :rules="registerRules" class="login-form"
    label-position="top" label-width="120px" size="large">
    <el-row style="margin-right: -10px; margin-left: -10px">
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item prop="name">
          <el-input v-model="registerData.registerForm.name" placeholder="租户名称" :prefix-icon="iconHouse" />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item prop="contactName">
          <el-input v-model="registerData.registerForm.contactName" placeholder="联系人" :prefix-icon="iconAvatar" />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item prop="contactMobile">
          <el-input v-model="registerData.registerForm.contactMobile" placeholder="联系手机" :prefix-icon="iconMobile" />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item prop="username">
          <el-input v-model="registerData.registerForm.username" :placeholder="t('login.username')"
            :prefix-icon="iconAvatar" />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item prop="password">
          <el-input v-model="registerData.registerForm.password" type="password" auto-complete="off"
            :placeholder="t('login.password')" :prefix-icon="iconLock" show-password />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item prop="confirmPassword">
          <el-input v-model="registerData.registerForm.confirmPassword" type="password" auto-complete="off"
            :placeholder="t('login.checkPassword')" :prefix-icon="iconLock" show-password />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item>
          <XButton :loading="loginLoading" :title="t('login.register')" class="w-[100%]" type="primary"
            @click="getCode()" />
        </el-form-item>
      </el-col>
      <el-col v-if="registerData.captchaEnable === 'true'" :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item>
          <div id="turnstile-container" class="w-[100%] flex justify-center"></div>
        </el-form-item>
      </el-col>
    </el-row>
    <XButton :title="t('login.hasUser')" class="w-[100%]" @click="handleBackLogin()" />
  </el-form>
</template>
<script lang="ts" setup>
import { ElLoading } from 'element-plus'
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { useIcon } from '@/hooks/web/useIcon'
import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
import { LoginStateEnum, useLoginState } from './useLogin'

declare global {
  interface Window {
    turnstile: any
  }
}

defineOptions({ name: 'TenantRegisterForm' })

const { t } = useI18n()
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })
const iconMobile = useIcon({ icon: 'ep:iphone' })
const formLogin = ref()
const { handleBackLogin, getLoginState } = useLoginState()
const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()
const redirect = ref<string>('')
const loginLoading = ref(false)
// const verify = ref()
// const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.TENANT_REGISTER)

const equalToPassword = (_rule, value, callback) => {
  if (registerData.registerForm.password !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  name: [
    { required: true, trigger: 'blur', message: '请输入租户名称' },
    { min: 2, max: 20, message: '租户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  contactName: [
    { required: true, trigger: 'blur', message: '请输入联系人' }
  ],
  contactMobile: [
    { required: true, trigger: 'blur', message: '请输入联系手机' },
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  username: [
    { required: true, trigger: 'blur', message: '请输入您的账号' },
    { min: 4, max: 30, message: '用户账号长度必须介于 4 和 30 之间', trigger: 'blur' }
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入您的密码' },
    { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
    { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, trigger: 'blur', message: '请再次输入您的密码' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
}

const registerData = reactive({
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  registerForm: {
    name: '',
    contactName: '',
    contactMobile: '',
    username: '',
    password: '',
    confirmPassword: '',
    turnstileToken: ''
  }
})

const turnstileToken = ref('')
const turnstileWidgetId = ref('')

const initTurnstile = () => {
  const waitForTurnstile = (retries = 0) => {
    if (retries > 50) {
      console.error('Turnstile SDK 加载超时')
      return
    }

    if (window.turnstile && !turnstileWidgetId.value) {
      const container = document.getElementById('turnstile-container')
      if (!container) {
        console.error('未找到 Turnstile 容器')
        return
      }

      try {
        const siteKey = import.meta.env.VITE_APP_TURNSTILE_SITE_KEY || '0x4AAAAAAAK0rP_gCjP2oJDa'
        console.log('使用 Site Key:', siteKey)

        turnstileWidgetId.value = window.turnstile.render('#turnstile-container', {
          sitekey: siteKey,
          theme: 'light',
          callback: function (token) {
            console.log('Turnstile 验证成功，token:', token)
            turnstileToken.value = token
          },
          'error-callback': function (error) {
            console.error('Turnstile 验证失败:', error)
            // 测试环境下，如果验证失败，使用测试 token
            if (siteKey === '1x00000000000000000000AA') {
              console.log('测试模式：使用模拟 token')
              turnstileToken.value = 'XXXX.DUMMY.TOKEN.XXXX'
            } else {
              turnstileToken.value = ''
            }
          },
          'expired-callback': function () {
            console.warn('Turnstile token 已过期')
            turnstileToken.value = ''
          }
        })
        console.log('Turnstile 组件已渲染，Widget ID:', turnstileWidgetId.value)
      } catch (error) {
        console.error('Turnstile 渲染错误:', error)
      }
    } else if (!window.turnstile) {
      // SDK 还未加载，100ms 后重试
      setTimeout(() => waitForTurnstile(retries + 1), 100)
    }
  }
  waitForTurnstile()
}

// 重置 Turnstile 验证码
const resetTurnstile = () => {
  if (window.turnstile && turnstileWidgetId.value) {
    window.turnstile.reset(turnstileWidgetId.value)
    turnstileToken.value = ''
    console.log('Turnstile 已重置')
  }
}

// 提交注册
const handleRegister = async () => {
  loginLoading.value = true
  try {
    const form = unref(formLogin)
    if (!form) return
    const valid = await form.validate()
    if (!valid) return

    if (registerData.captchaEnable === 'true' && !turnstileToken.value) {
      ElMessage.warning('请完成人机验证')
      return
    }

    if (registerData.captchaEnable) {
      registerData.registerForm.turnstileToken = turnstileToken.value
    }

    console.log('提交注册，turnstileToken:', turnstileToken.value)
    const res = await LoginApi.tenantRegister(registerData.registerForm)
    if (!res) {
      // 注册失败，重置验证码
      resetTurnstile()
      return
    }
    console.log(res, '注册成功返回')

    // 注册成功，保存账号和租户名到缓存，用于自动填充登录表单
    authUtil.setLoginForm({
      tenantName: registerData.registerForm.name,
      username: registerData.registerForm.username,
      password: '',
      rememberMe: true
    })

    // 提示注册成功
    ElMessage.success('注册成功，请登录')

    // 跳转回登录页
    handleBackLogin()
  } catch (error) {
    // 请求异常时也要重置验证码
    console.error('注册失败:', error)
    resetTurnstile()
  } finally {
    loginLoading.value = false
  }
}

// 获取验证码 / 提交
const getCode = async () => {
  // Just call handleRegister directly now, as Turnstile is on-page
  await handleRegister()
}

const loading = ref() // ElLoading.service 返回的实例

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

watch(
  () => getShow.value,
  (isShow) => {
    console.log('getShow 变化:', isShow)
    console.log('captchaEnable:', registerData.captchaEnable)
    console.log('环境变量 CAPTCHA_ENABLE:', import.meta.env.VITE_APP_CAPTCHA_ENABLE)
    console.log('环境变量 SITE_KEY:', import.meta.env.VITE_APP_TURNSTILE_SITE_KEY)

    if (isShow && registerData.captchaEnable === 'true') {
      console.log('准备初始化 Turnstile')
      nextTick(() => {
        console.log('nextTick 中初始化 Turnstile')
        initTurnstile()
      })
    }
  }
)

onMounted(() => {
  console.log('组件已挂载')
  console.log('getShow:', getShow.value)
  console.log('captchaEnable:', registerData.captchaEnable)
  console.log('window.turnstile:', window.turnstile)

  // Check if already visible on mount (unlikely but possible)
  if (getShow.value && registerData.captchaEnable === 'true') {
    console.log('挂载时初始化 Turnstile')
    initTurnstile()
  }
})
</script>

<style lang="scss" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.login-code {
  float: right;
  width: 100%;
  height: 38px;

  img {
    width: 100%;
    height: auto;
    max-width: 100px;
    vertical-align: middle;
    cursor: pointer;
  }
}
</style>
