<script setup lang="ts">
import { openApiLogic } from '@af-mobile-client-vue3/services/api/common'
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,
  NavBar as VanNavBar,
  Popup as VanPopup,
} from 'vant'
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

interface FormData {
  name: string // 姓名
  username: string // 登录账号
  platformUserId: string // 唯一标识
  platformType: string
}

interface Errors {
  name?: string
  username?: string
}

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const userInfo = computed(() => userStore.getUserInfo())
// 表单数据
const formData = ref<FormData>({
  name: '',
  username: '',
  platformUserId: '',
  platformType: '',
})

// 是否已初始化（检查openId有效性）
const initValid = ref(false)
// 绑定状态
const isBinding = ref<boolean>(false)
const showSuccess = ref<boolean>(false)

// 错误信息
const errors = ref<Errors>({})

// 验证函数
function validateName(): boolean {
  if (!formData.value.name.trim()) {
    errors.value.name = '姓名不能为空'
    return false
  }
  delete errors.value.name
  return true
}

function validateUsername(): boolean {
  if (!formData.value.username.trim()) {
    errors.value.username = '登录账号不能为空'
    return false
  }
  delete errors.value.username
  return true
}

function validateAll(): boolean {
  return validateName() && validateUsername()
}

// 执行绑定
async function bindUser(): Promise<void> {
  if (!validateAll()) {
    showToast('请填写完整信息')
    return
  }

  if (!initValid.value) {
    showFailToast('链接无效，缺少必要参数')
    return
  }

  isBinding.value = true

  try {
    const response = await openApiLogic(
      {
        username: formData.value.username,
        name: formData.value.name,
        platformUserId: formData.value.platformUserId,
        platformType: formData.value.platformType,
      },
      'bindExistUser',
      'af-system',
    )

    if (response.success) {
      showSuccess.value = true
      showSuccessToast('绑定成功')
      await useUserStore().registerClean()
      resetForm()
    }
    else {
      // 后端返回错误信息（如用户不存在、已被绑定等）
      showFailToast(response.msg || '绑定失败')
    }
  }
  catch (error: any) {
    console.error('绑定失败:', error)
    showFailToast(error?.msg || '绑定失败，请重试')
  }
  finally {
    isBinding.value = false
  }
}

// 重置表单
function resetForm(): void {
  formData.value.name = ''
  formData.value.username = ''
  Object.keys(errors.value).forEach(key => delete errors.value[key])
}

onMounted(async () => {
  if (userStore.isExternalUser()) {
    if (userInfo.value?.platformUserId && userInfo.value?.platformType) {
      formData.value.platformUserId = userInfo.value?.platformUserId
      formData.value.platformType = userInfo.value?.platformType
      initValid.value = true
    }
    else {
      initValid.value = false
      showFailToast('当前登录用户缺少用户标识')
    }
  }
  else {
    if (userInfo.value?.platformUserId && userInfo.value?.platformType) {
      showFailToast(' 该账号已关联当前平台')
      initValid.value = false
    }
    else {
      initValid.value = false
      showFailToast('当前登录用户缺少用户标识')
    }
  }
})
</script>

<template>
  <div class="user-bind">
    <!-- 顶部导航栏 -->
    <VanNavBar title="用户绑定" placeholder fixed />

    <!-- 无效链接提示 -->
    <div v-if="!initValid" class="main-content">
      <VanEmpty image="error" description="当前登录用户缺少用户标识" />
    </div>

    <!-- 绑定表单 -->
    <div v-else class="main-content">
      <div class="form-container">
        <div class="form-header">
          <h2 class="form-title">
            账号绑定
          </h2>
          <p class="form-subtitle">
            请输入系统账号和姓名完成绑定
          </p>
        </div>

        <VanForm @submit="bindUser">
          <!-- 姓名 -->
          <VanField
            v-model="formData.name"
            label="姓名"
            placeholder="请输入系统预留的姓名"
            :error="!!errors.name"
            :error-message="errors.name"
            label-align="top"
            @blur="validateName"
          >
            <template #label>
              <i class="i-material-symbols-person text-blue-500" />
              姓名 <span class="required">*</span>
            </template>
          </VanField>

          <!-- 登录账号 -->
          <VanField
            v-model="formData.username"
            label="登录账号"
            placeholder="请输入系统登录账号"
            :error="!!errors.username"
            :error-message="errors.username"
            label-align="top"
            @blur="validateUsername"
          >
            <template #label>
              <i class="i-material-symbols-id-card text-indigo-500" />
              登录账号 <span class="required">*</span>
            </template>
          </VanField>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <VanButton
              type="default"
              size="large"
              :disabled="isBinding"
              class="reset-btn"
              @click="resetForm"
            >
              <i class="i-hugeicons-redo" />
              重置
            </VanButton>
            <VanButton
              type="primary"
              size="large"
              native-type="submit"
              :loading="isBinding"
              :disabled="isBinding"
              class="submit-btn"
              @click="bindUser"
            >
              <i class="i-iconoir-user-plus" />
              {{ isBinding ? '绑定中...' : '立即绑定' }}
            </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>
        </div>
      </div>
    </VanPopup>
  </div>
</template>

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

.main-content {
  padding: 16px;
  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;
}

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

.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;
}

:deep(.van-field__label) {
  display: flex;
  align-items: center;
  font-weight: 500;
}

:deep(.van-field__body) {
  margin: 10px 0;
  padding: 10px 15px;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  font-size: 100%;
}

:deep(.van-nav-bar) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

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