<script setup lang="ts">
import { getConfigByName, openApiLogic } from '@af-mobile-client-vue3/services/api/common'
import { useSettingStore } from '@af-mobile-client-vue3/stores/modules/setting'
import useUserStore from '@af-mobile-client-vue3/stores/modules/user'
import {
  showFailToast,
  showSuccessToast,
  showToast,
  Button as VanButton,
  Empty as VanEmpty,
  Field as VanField,
  Form as VanForm,
  Icon as VanIcon,
  Loading as VanLoading,
  NavBar as VanNavBar,
  Popup as VanPopup,
  Radio as VanRadio,
  RadioGroup as VanRadioGroup,
} from 'vant'

import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
// 定义配置接口
interface RegisterConfig {
  info?: {
    show?: boolean
    name?: { show?: boolean, validate?: boolean }
    phone?: { show?: boolean, validate?: boolean }
    gender?: { show?: boolean, validate?: boolean }
    code?: { show?: boolean, validate?: boolean, placeholder?: string }
    email?: { show?: boolean, validate?: boolean }
  }
  organization?: {
    show?: boolean
    roles?: { show?: boolean }
    dept_name?: { show?: boolean }
    org_name?: { show?: boolean }
  }
}
interface FormData {
  name: string
  phone: string
  gender: string
  code: string
  email: string
  username: string
  password: string
  confirmPassword: string
  roles: string
  dept_name: string
  org_name: string
  strategyId: string
  openId: string
}
interface Errors {
  [key: string]: string | undefined
  name?: string
  phone?: string
  gender?: string
  email?: string
  username?: string
  password?: string
  confirmPassword?: string
}

interface OrganizationInfo {
  roles: string
  dept_name: string
  org_name: string
}

type UsernameStatus = 'initial' | 'checking' | 'available' | 'unavailable'

const route = useRoute()
const router = useRouter()
const setting = useSettingStore()

// 表单数据
const formData = ref<FormData>({
  name: '',
  phone: '',
  gender: '',
  code: '',
  email: '',
  username: '',
  password: '',
  confirmPassword: '',
  roles: '',
  dept_name: '',
  org_name: '',
  strategyId: '',
  openId: '',
})
const initSuccess = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const openId = ref('')
// 错误信息
const errors = ref<Errors>({})

const registerConfig = ref<RegisterConfig>({})

// 状态管理
const isSubmitting = ref<boolean>(false)
const showSuccess = ref<boolean>(false)
const usernameStatus = ref<UsernameStatus>('initial')

// 组织信息（从策略获取）
const organizationInfo = ref<OrganizationInfo>({
  roles: '',
  dept_name: '',
  org_name: '',
})
// 防抖检查用户名
let usernameCheckTimeout = null

// 验证函数
function validateName(): boolean {
  if (!registerConfig.value?.info?.name?.validate)
    return true
  if (!formData.value.name.trim()) {
    errors.value.name = '员工姓名不能为空'
    return false
  }
  if (formData.value.name.length < 2) {
    errors.value.name = '员工姓名至少2个字符'
    return false
  }
  delete errors.value.name
  return true
}
function validateCode(): boolean {
  if (!registerConfig.value?.info?.code?.validate)
    return true
  if (!formData.value.code.trim()) {
    errors.value.code = '员工编号不能为空'
    return false
  }
  delete errors.value.code
  return true
}

function validatePhone(): boolean {
  if (!registerConfig.value?.info?.phone?.validate)
    return true
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!formData.value.phone.trim()) {
    errors.value.phone = '手机号码不能为空'
    return false
  }
  if (!phoneRegex.test(formData.value.phone)) {
    errors.value.phone = '请输入正确的手机号码'
    return false
  }
  delete errors.value.phone
  return true
}

function validateEmail(): boolean {
  if (!registerConfig.value?.info?.email?.validate)
    return true
  if (formData.value.email.trim()) {
    const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
    if (!emailRegex.test(formData.value.email)) {
      errors.value.email = '请输入正确的邮箱地址'
      return false
    }
  }
  delete errors.value.email
  return true
}

function validateUsername(): boolean {
  if (!formData.value.username.trim()) {
    errors.value.username = '登录名不能为空'
    return false
  }
  if (formData.value.username.length < 3) {
    errors.value.username = '登录名至少3个字符'
    return false
  }
  if (!/^\w+$/.test(formData.value.username)) {
    errors.value.username = '登录名只能包含字母、数字和下划线'
    return false
  }

  if (usernameStatus.value === 'unavailable') {
    errors.value.username = '该登录名已被使用，请选择其他登录名'
    return false
  }

  if (usernameStatus.value === 'checking') {
    errors.value.username = '正在检查登录名可用性，请稍候'
    return false
  }

  if (usernameStatus.value === 'initial') {
    checkUsernameAvailability()
    errors.value.username = '正在检查登录名可用性，请稍候'
    return false
  }

  delete errors.value.username
  return true
}

function validatePassword(): boolean {
  if (!formData.value.password) {
    errors.value.password = '登录密码不能为空'
    return false
  }
  if (formData.value.password.length < 6) {
    errors.value.password = '登录密码至少6个字符'
    return false
  }
  delete errors.value.password
  return true
}

function validateConfirmPassword(): boolean {
  if (!formData.value.confirmPassword) {
    errors.value.confirmPassword = '确认密码不能为空'
    return false
  }
  if (formData.value.password !== formData.value.confirmPassword) {
    errors.value.confirmPassword = '两次输入的密码不一致'
    return false
  }
  delete errors.value.confirmPassword
  return true
}

function validateGender(): boolean {
  if (!registerConfig.value?.info?.gender?.validate)
    return true
  if (!formData.value.gender) {
    errors.value.gender = '请选择性别'
    return false
  }
  delete errors.value.gender
  return true
}

function validateAll(): boolean {
  const validations = [
    validateName(),
    validateCode(),
    validatePhone(),
    validateEmail(),
    validateUsername(),
    validatePassword(),
    validateConfirmPassword(),
    validateGender(),
  ]
  return validations.every(v => v)
}

// 检查用户名可用性
async function checkUsernameAvailability(): Promise<void> {
  usernameStatus.value = 'checking'

  try {
    const response = await openApiLogic({ username: formData.value.username }, 'checkUserName', 'af-system')
    console.log('response', response)
    if (response.success) {
      usernameStatus.value = 'available'
      delete errors.value.username
    }
    else {
      errors.value.username = '该登录名已被使用，请选择其他登录名'
      usernameStatus.value = 'unavailable'
    }
  }
  catch (error) {
    // 模拟检查逻辑
    const existingUsernames = ['admin', 'user001', 'zhangsan', 'lisi', 'wangwu']
    if (existingUsernames.includes(formData.value.username.toLowerCase())) {
      errors.value.username = '该登录名已被使用，请选择其他登录名'
      usernameStatus.value = 'unavailable'
    }
    else {
      usernameStatus.value = 'available'
      delete errors.value.username
    }
  }
}

// 获取组织信息
async function fetchOrganizationInfo(strategyId: any): Promise<void> {
  try {
    const response = await openApiLogic({ strategyId }, 'getOrganizationInfo', 'af-system')
    if (response.success) {
      initSuccess.value = true
      Object.assign(organizationInfo.value, response.data)
      // 更新表单数据
      formData.value.roles = organizationInfo.value.roles
      formData.value.dept_name = organizationInfo.value.dept_name
      formData.value.org_name = organizationInfo.value.org_name
      formData.value.strategyId = strategyId
    }
    else {
      showFailToast(response.msg)
    }
  }
  catch (error) {
    console.error('获取组织信息失败:', error)
    showToast('获取组织信息失败')
  }
}

async function initConfig(): Promise<void> {
  try {
    getConfigByName('registerConfig', (res: any) => {
      console.log('res', res)
      registerConfig.value = res
    }, 'af-system')
  }
  catch (error) {
    console.error('获取组织信息失败:', error)
    showToast('获取组织信息失败')
  }
}

// 提交注册
async function submitRegistration(): Promise<void> {
  if (usernameStatus.value === 'checking') {
    showToast('请等待登录名检查完成')
    return
  }

  if (!validateAll()) {
    showToast('请填写必填信息！')
    return
  }

  isSubmitting.value = true

  try {
    console.log('formData', formData.value)
    const response = await openApiLogic(formData.value, 'registrationUser', 'af-system')
    if (response.success) {
      showSuccess.value = true
      showSuccessToast('注册成功')
      await useUserStore().registerClean()
    }
    else {
      showSuccessToast(`注册失败,${response.msg}!`)
    }
    isSubmitting.value = false
  }
  catch (error) {
    isSubmitting.value = false
    showToast('注册失败，请重试')
  }
}

// 重置表单
function resetForm(): void {
  Object.assign(formData.value, {
    name: '',
    phone: '',
    gender: '',
    code: '',
    email: '',
    username: '',
    password: '',
    confirmPassword: '',
  })
  Object.keys(errors.value).forEach(key => delete errors.value[key])
  showPassword.value = false
  showConfirmPassword.value = false
  showSuccess.value = false
  usernameStatus.value = 'initial'
}

function debounceUsernameCheck() {
  if (usernameCheckTimeout) {
    clearTimeout(usernameCheckTimeout)
  }

  // 重置状态
  usernameStatus.value = 'initial'
  delete errors.value.username

  // 基本验证
  if (!formData.value.username.trim()) {
    return
  }
  if (formData.value.username.length < 3) {
    return
  }
  if (!/^\w+$/.test(formData.value.username)) {
    return
  }

  // 设置新的定时器
  usernameCheckTimeout = setTimeout(() => {
    checkUsernameAvailability()
  }, 500) // 500ms 防抖延迟
}

// 提交注册
async function handleSubmit() {
  if (usernameStatus.value === 'checking') {
    showToast('请等待登录名检查完成')
    return
  }

  await submitRegistration()
}

// 返回上一页
function goBack() {
  router.push('/login')
}

// 组件挂载时获取组织信息
onMounted(async () => {
  console.log('route.query', route.query)
  console.log('route.params', route.params)
  const strategyId = route.query.strategyId || route.params.strategyId
  openId.value = route.query.openId as string || route.params.openId as string
  formData.value.openId = openId.value
  if (strategyId) {
    await initConfig()
    await fetchOrganizationInfo(strategyId)
  }
  else {
    if (setting.getSetting()?.registerRequire) {
      showFailToast('缺少组织信息，请确二维码准确性')
    }
  }
})
</script>

<template>
  <div class="employee-registration">
    <!-- 顶部导航栏 -->
    <VanNavBar
      title="员工注册"

      placeholder fixed
    />
    <div v-show="!initSuccess">
      <VanEmpty image="error" description="推广码无效/已过期" />
    </div>
    <!-- 主要内容区域 -->
    <div v-show="initSuccess" class="main-content">
      <div class="form-container">
        <!-- 表单标题 -->
        <div class="form-header">
          <h2 class="form-title">
            员工信息录入
          </h2>
          <p class="form-subtitle">
            请填写员工基本信息完成账号注册
          </p>
        </div>

        <!-- 注册表单 -->
        <VanForm @submit="submitRegistration">
          <!-- 基本信息 -->
          <div v-show="registerConfig?.info?.show" class="form-section">
            <div class="section-header">
              <span class="section-title">基本信息</span>
            </div>

            <!-- 员工姓名 -->
            <VanField
              v-show="registerConfig?.info?.name?.show"
              v-model="formData.name"
              label="员工姓名"
              placeholder="请输入员工姓名"
              :error="!!errors.name"
              :error-message="errors.name"
              label-align="top"
              :border="true"
              @blur="validateName"
            >
              <template #label>
                <i class="i-material-symbols-person text-blue-500" />
                员工姓名 <span class="required">*</span>
              </template>
            </VanField>

            <!-- 手机号码 -->
            <VanField
              v-show="registerConfig?.info?.phone?.show"
              v-model="formData.phone"
              label="手机号码"
              type="tel"
              placeholder="请输入手机号码"
              :error="!!errors.phone"
              :error-message="errors.phone"
              label-align="top"
              @blur="validatePhone"
            >
              <template #label>
                <i class="i-flowbite-mobile-phone-solid text-green-500" />
                手机号码 <span class="required">*</span>
              </template>
            </VanField>

            <!-- 性别 -->
            <VanField
              v-show="registerConfig?.info?.gender?.show"
              label="性别"
              :error="!!errors.gender"
              :error-message="errors.gender"
              label-align="top"
            >
              <template #label>
                <i class="i-fa6-solid-venus-mars text-pink-500" />
                性别 <span class="required">*</span>
              </template>
              <template #input>
                <VanRadioGroup v-model="formData.gender" @change="validateGender">
                  <VanRadio name="男">
                    男
                  </VanRadio>
                  <VanRadio name="女">
                    女
                  </VanRadio>
                </VanRadioGroup>
              </template>
            </VanField>
            <!-- 员工编号 -->
            <VanField
              v-show="registerConfig?.info?.code?.show"
              v-model="formData.code"
              label="员工编号"
              :placeholder="registerConfig?.info?.code?.placeholder || '请输入员工编号'"
              :error="!!errors.code"
              :error-message="errors.code"
              label-align="top"
              @blur="validateCode"
            >
              <template #label>
                <i class="i-solar-user-id-bold text-purple-500" />
                员工编号 <span v-show="registerConfig?.info?.code?.validate" class="required">*</span>
              </template>
            </VanField>
            <!-- 邮箱 -->
            <VanField
              v-show="registerConfig?.info?.email?.show"
              v-model="formData.email"
              label="邮箱"
              type="email"
              placeholder="请输入邮箱地址（可选）"
              :error="!!errors.email"
              :error-message="errors.email"
              label-align="top"
              @blur="validateEmail"
            >
              <template #label>
                <i class="i-material-symbols-mail text-purple-500" />
                邮箱
              </template>
            </VanField>
          </div>

          <!-- 账号信息 -->
          <div class="form-section">
            <div class="section-header">
              <span class="section-title">账号信息</span>
            </div>

            <!-- 登录名 -->
            <VanField
              v-model="formData.username"
              label="登录名"
              placeholder="请输入登录名"
              :error="!!errors.username"
              :error-message="errors.username"
              label-align="top"
              @blur="validateUsername"
              @input="debounceUsernameCheck"
            >
              <template #label>
                <i class="i-material-symbols-id-card text-indigo-500" />
                登录名 <span class="required">*</span>
              </template>
              <template #right-icon>
                <!-- 检查中状态 -->
                <VanLoading v-if="usernameStatus === 'checking'" size="16px" />
                <!-- 可用状态 -->
                <i v-else-if="usernameStatus === 'available'" class="i-material-symbols-check-circle text-green-500" />
                <i v-else-if="usernameStatus === 'unavailable'" class="i-iconamoon-sign-times-circle text-red-500" />
              </template>
            </VanField>

            <!-- 登录密码 -->
            <VanField
              v-model="formData.password"
              label="登录密码"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入登录密码"
              :error="!!errors.password"
              :error-message="errors.password"
              label-align="top"
              @blur="validatePassword"
            >
              <template #label>
                <i class="i-material-symbols-lock text-orange-500" />
                登录密码 <span class="required">*</span>
              </template>
              <template #right-icon>
                <VanIcon
                  :name="showPassword ? 'eye-o' : 'closed-eye'"
                  @click="showPassword = !showPassword"
                />
              </template>
            </VanField>

            <!-- 确认密码 -->
            <VanField
              v-model="formData.confirmPassword"
              label="确认密码"
              :type="showConfirmPassword ? 'text' : 'password'"
              placeholder="请再次输入登录密码"
              :error="!!errors.confirmPassword"
              :error-message="errors.confirmPassword"
              label-align="top"
              @blur="validateConfirmPassword"
            >
              <template #label>
                <i class="i-bxs-shield-alt-2 text-teal-500" />
                确认密码 <span class="required">*</span>
              </template>
              <template #right-icon>
                <VanIcon
                  :name="showConfirmPassword ? 'eye-o' : 'closed-eye'"
                  @click="showConfirmPassword = !showConfirmPassword"
                />
              </template>
            </VanField>
          </div>

          <!-- 组织信息 -->
          <div v-show="registerConfig?.organization?.show" class="form-section">
            <div class="section-header">
              <span class="section-title">组织信息</span>
            </div>

            <!-- 所属角色 -->
            <VanField
              v-show="registerConfig?.organization?.roles?.show"
              v-model="formData.roles"
              label="所属角色"
              readonly
              disabled
              label-align="top"
            >
              <template #label>
                <i class="i-fa6-solid-user-tag text-blue-600" />
                所属角色
              </template>
            </VanField>
            <div class="field-hint">
              系统默认分配，不可修改
            </div>

            <!-- 所属部门 -->
            <VanField
              v-show="registerConfig?.organization?.dept_name?.show"
              v-model="formData.dept_name"
              label="所属部门"
              readonly
              disabled
              label-align="top"
            >
              <template #label>
                <i class="i-material-symbols-home-work text-gray-600" />
                所属部门
              </template>
            </VanField>
            <div class="field-hint">
              系统默认分配，不可修改
            </div>

            <!-- 所属分公司 -->
            <VanField
              v-show="registerConfig?.organization?.org_name?.show"
              v-model="formData.org_name"
              label="所属分公司"
              readonly
              disabled
              label-align="top"
            >
              <template #label>
                <i class="i-line-md-map-marker-alt-filled text-red-500" />
                所属分公司
              </template>
            </VanField>
            <div class="field-hint">
              系统默认分配，不可修改
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="form-actions">
            <VanButton
              type="default"
              size="large"
              :disabled="isSubmitting"
              class="reset-btn"
              @click="resetForm"
            >
              <i class="i-hugeicons-redo" />
              重置
            </VanButton>
            <VanButton
              type="primary"
              size="large"
              native-type="submit"
              :loading="isSubmitting"
              :disabled="isSubmitting"
              class="submit-btn"
              @click="handleSubmit"
            >
              <i class="i-iconoir-user-plus" />
              {{ isSubmitting ? '注册中...' : '提交注册' }}
            </VanButton>
          </div>
        </VanForm>
      </div>
    </div>

    <!-- 注册成功弹窗 -->
    <VanPopup
      v-model:show="showSuccess"
      round
      closeable
      class="success-popup"
    >
      <div class="success-content">
        <VanIcon name="success" class="success-icon" />
        <h3 class="success-title">
          注册成功
        </h3>
        <p class="success-message">
          员工账号已成功创建，请等待管理员审核。
        </p>
        <div class="success-info">
          <p><strong>员工姓名：</strong>{{ formData.name }}</p>
          <p><strong>登录名：</strong>{{ formData.username }}</p>
          <p><strong>手机号码：</strong>{{ formData.phone }}</p>
        </div>
        <div class="success-actions">
          <!--          <VanButton type="default" @click="resetForm"> -->
          <!--            继续注册 -->
          <!--          </VanButton> -->
          <!--          <VanButton type="primary" @click="goBack"> -->
          <!--            去登录 -->
          <!--          </VanButton> -->
        </div>
      </div>
    </VanPopup>
  </div>
</template>

<style scoped lang="less">
.employee-registration {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-content {
  padding: 16px;
  padding-top: 60px;
  padding-bottom: 80px;
}

.form-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表单标题样式 */
.form-header {
  padding: 20px 16px 16px;
  border-bottom: 1px solid #e9ecef;
}

.form-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.form-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.form-section {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.section-icon {
  margin-right: 8px;
  color: #007bff;
  font-size: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.field-icon {
  margin-right: 4px;
  color: #666;
  font-size: 14px;
}

.required {
  color: #ee0a24;
  font-weight: 500;
}

/* 字段提示文字 */
.field-hint {
  font-size: 12px;
  color: #999;
  padding: 0 16px 8px;
}

/* 按钮样式 */
.form-actions {
  display: flex;
  gap: 12px;
  padding: 20px 16px;
  background-color: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.reset-btn {
  flex: 1;
  background-color: #6c757d !important;
  border-color: #6c757d !important;
  color: white !important;
}

.reset-btn:hover {
  background-color: #5a6268 !important;
}

.submit-btn {
  flex: 1;
  background-color: #007bff !important;
  border-color: #007bff !important;
  color: white !important;
}

.submit-btn:hover {
  background-color: #0056b3 !important;
}

/* 成功弹窗样式 */
.success-popup {
  width: 90%;
  max-width: 400px;
}

.success-content {
  padding: 24px;
  text-align: center;
}

.success-icon {
  font-size: 48px;
  color: #07c160;
  margin-bottom: 16px;
}

.success-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.success-message {
  color: #666;
  margin-bottom: 16px;
}

.success-info {
  text-align: left;
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.success-info p {
  margin: 4px 0;
  font-size: 14px;
}

.success-actions {
  display: flex;
  gap: 12px;
}

.success-actions .van-button {
  flex: 1;
}

/* 自定义字段样式 */
:deep(.van-field__label) {
  display: flex;
  align-items: center;
  font-weight: 500;
}

:deep(.van-field--error .van-field__control) {
  color: #ee0a24;
}

:deep(.van-field--disabled .van-field__control) {
  color: #999;
  background-color: #f5f5f5;
}

:deep(.van-field--disabled .van-field__label) {
  color: #666;
}

/* 单选按钮样式 */
:deep(.van-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.van-radio) {
  margin: 0;
}

/* 导航栏样式 */
:deep(.van-nav-bar) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

:deep(.van-nav-bar__title) {
  font-weight: 600;
  color: #333;
}

/* 错误信息样式 */
:deep(.van-field__error-message) {
  color: #ee0a24;
  font-size: 12px;
  margin-top: 4px;
}

/* 密码字段右侧图标样式 */
:deep(.van-field__right-icon) {
  color: #999;
  cursor: pointer;
}

:deep(.van-field__right-icon:hover) {
  color: #666;
}
/* 修改整个输入框容器的样式 */
:deep(.van-field__body) {
  margin: 10px 0;
  padding: 10px 15px;
  --tw-border-opacity: 1;
  border-color: rgb(209 213 219 / var(--tw-border-opacity, 1));
  border-radius: 0.375rem;
  border-width: 1px;
  font-size: 100%;
}

:deep(.van-field--disabled .van-field__control) {
  background-color: #ffffff;
}
</style>
