<template>
  <div class="p-6">
    <div class="max-w-4xl mx-auto">
      <h1 class="text-2xl font-bold mb-6">个人中心</h1>

      <!-- 优先提醒：实名认证 -->
      <el-alert
        v-if="!isAuthenticated"
        type="warning"
        :closable="false"
        class="mb-6"
        show-icon
      >
        <template #title>
          <span class="font-semibold">请先完成实名认证</span>
        </template>
        <div class="mt-2">
          <p class="text-sm mb-3">您尚未完成实名认证或令牌已过期，部分功能可能无法使用。</p>
          <el-button
            type="warning"
            size="small"
            :loading="authLoading"
            @click="handleAuth"
          >
            立即认证
          </el-button>
          <el-button
            type="primary"
            size="small"
            :loading="authLoading"
            @click="handleHadAuth"
          >
            已实名认证
          </el-button>
        </div>
      </el-alert>

      <!-- 其次提醒：修改默认密码 -->
      <el-alert
        v-else-if="userInfo.defaultPwd === 1"
        type="info"
        :closable="false"
        class="mb-6"
        show-icon
      >
        <template #title>
          <span class="font-semibold">请修改默认密码</span>
        </template>
        <div class="mt-2">
          <p class="text-sm mb-3">您正在使用默认密码，为了账户安全，请尽快修改密码。</p>
          <el-button
            type="primary"
            size="small"
            @click="scrollToPasswordForm"
          >
            立即修改
          </el-button>
        </div>
      </el-alert>

      <!-- 用户信息卡片 -->
      <el-card class="mb-6">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-lg font-semibold">基本信息</span>
            <el-button type="primary" @click="refreshUserInfo">刷新状态</el-button>
          </div>
        </template>
        <div class="space-y-4">
          <div class="flex items-center">
            <span class="text-gray-600 w-24">工号：</span>
            <span class="font-medium">{{ userInfo.jobNumber }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-600 w-24">姓名：</span>
            <span class="font-medium">{{ userInfo.name || '未设置' }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-600 w-24">账号状态：</span>
            <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
              {{ userInfo.status === 1 ? '正常' : '已禁用' }}
            </el-tag>
          </div>
          <div class="flex items-center">
            <span class="text-gray-600 w-24">是否默认密码：</span>
            <el-tag :type="userInfo.defaultPwd === 1 ? 'warning' : 'success'">
              {{ userInfo.defaultPwd === 1 ? '是（请尽快修改）' : '否' }}
            </el-tag>
          </div>
        </div>
      </el-card>

      <!-- 实名认证状态卡片 -->
      <el-card class="mb-6">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-lg font-semibold">实名认证状态</span>
            <el-button
              type="primary"
              size="small"
              :loading="authLoading"
              @click="handleAuth"
            >
              {{ isAuthenticated ? '重新认证' : '去认证' }}
            </el-button>
          </div>
        </template>
        <div class="space-y-4">
          <div class="flex items-center">
            <span class="text-gray-600 w-32">认证状态：</span>
            <el-tag :type="getAuthStatusType(userInfo.userStatus)">
              {{ getAuthStatusText(userInfo.userStatus) }}
            </el-tag>
          </div>
          <div v-if="userInfo.userToken" class="flex items-center">
            <span class="text-gray-600 w-32">令牌：</span>
            <span class="font-mono text-sm">{{ userInfo.userToken.substring(0, 20) }}...</span>
          </div>
          <div v-if="userInfo.userTokenExpiresAt" class="flex items-center">
            <span class="text-gray-600 w-32">令牌过期时间：</span>
            <span :class="isTokenExpired ? 'text-red-500' : 'text-green-600'">
              {{ formatDate(userInfo.userTokenExpiresAt) }}
              <el-tag v-if="isTokenExpired" type="danger" size="small" class="ml-2">已过期</el-tag>
            </span>
          </div>
        </div>
      </el-card>

      <!-- 修改密码卡片 -->
      <el-card ref="passwordCardRef">
        <template #header>
          <span class="text-lg font-semibold">修改密码</span>
        </template>
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
          class="max-w-md"
        >
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入旧密码"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码（至少6位）"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="passwordLoading"
              @click="handleChangePassword"
            >
              确认修改
            </el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 实名认证弹窗 -->
      <el-dialog
        v-model="authDialogVisible"
        title="实名认证"
        width="600px"
        :close-on-click-modal="false"
      >
        <div class="text-center py-4">
          <el-icon :size="60" color="#409eff" class="mb-4">
            <Avatar />
          </el-icon>
          <p class="text-lg mb-4">请使用微信扫描下方二维码完成实名认证</p>
          <div v-if="authUrl" class="mb-4">
            <div class="bg-gray-100 p-4 rounded inline-block">
              <p class="text-sm text-gray-600 mb-2">认证链接：</p>
              <a :href="authUrl" target="_blank" class="text-blue-500 hover:underline break-all">
                {{ authUrl }}
              </a>
            </div>
            <p class="text-sm text-gray-500 mt-4">点击链接或在浏览器中打开进行认证</p>
          </div>
          
          <div class="text-sm text-gray-600 space-y-2">
            <p>认证步骤：</p>
            <ol class="text-left inline-block">
              <li>1. 点击上方链接</li>
              <li>2. 使用微信扫码登录</li>
              <li>3. 完成实名认证流程</li>
              <li>4. 认证成功后系统会自动更新状态</li>
            </ol>
          </div>
        </div>
        <template #footer>
          <el-button @click="authDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="refreshUserInfo">刷新状态</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
defineOptions({
  name: 'Profile'
})

import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { WarningFilled, Avatar } from '@element-plus/icons-vue'
import { getUserAuthUrl, checkTokenValid, changePassword, getUserInfo } from '@/api/user'

// 用户信息
const userInfo = ref({
  jobNumber: '',
  name: '',
  status: 1,
  defaultPwd: 0,
  userStatus: 0,
  userToken: '',
  userTokenExpiresAt: null
})

// 卡片引用
const passwordCardRef = ref(null)

// 滚动到修改密码表单
const scrollToPasswordForm = () => {
  if (passwordCardRef.value) {
    passwordCardRef.value.$el.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}

// 加载用户信息
const loadUserInfo = () => {
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
  }
}

// 刷新用户信息
const refreshUserInfo = async () => {
  try {
    const res = await getUserInfo({ id: userInfo.value.id })
    if (res.success) {
      userInfo.value = res.data
      localStorage.setItem('userInfo', JSON.stringify(res.data))
      ElMessage.success('信息已刷新')
      // 关闭弹窗
      authDialogVisible.value = false
    }
  } catch (error) {
    console.error('刷新用户信息失败:', error)
    ElMessage.error('刷新失败')
  }
}

// 是否已认证
const isAuthenticated = computed(() => {
  if (userInfo.value.userStatus !== 2) return false
  if (!userInfo.value.userToken) return false
  if (!userInfo.value.userTokenExpiresAt) return false
  
  const expiresAt = new Date(userInfo.value.userTokenExpiresAt)
  return expiresAt > new Date()
})

// 令牌是否过期
const isTokenExpired = computed(() => {
  if (!userInfo.value.userTokenExpiresAt) return false
  const expiresAt = new Date(userInfo.value.userTokenExpiresAt)
  return expiresAt <= new Date()
})

// 认证状态类型
const getAuthStatusType = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'warning'
    case 2: return isTokenExpired.value ? 'danger' : 'success'
    default: return 'info'
  }
}

// 认证状态文本
const getAuthStatusText = (status) => {
  switch (status) {
    case 0: return '未找到账号'
    case 1: return '未完成认证'
    case 2: return isTokenExpired.value ? '已认证（令牌已过期）' : '已完成认证'
    default: return '未知状态'
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 实名认证相关
const authLoading = ref(false)
const authDialogVisible = ref(false)
const authUrl = ref('')

const handleAuth = async () => {
  authLoading.value = true
  try {
    const res = await getUserAuthUrl({ jobNumber: userInfo.value.jobNumber })
    if (res.success) {
      authUrl.value = res.data
      window.open(authUrl.value, '_blank')
    } else {
      ElMessage.error(res.message || '获取认证链接失败')
    }
  } catch (error) {
    console.error('获取认证链接失败:', error)
    ElMessage.error('获取认证链接失败')
  } finally {
    authLoading.value = false
  }
}

const handleHadAuth = () => {
  refreshUserInfo()
}

// 修改密码相关
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const passwordFormRef = ref(null)
const passwordLoading = ref(false)

const handleChangePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (!valid) return

    passwordLoading.value = true
    try {
      const res = await changePassword({
        jobNumber: userInfo.value.jobNumber,
        oldPassword: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword
      })

      if (res.success) {
        ElMessage.success('密码修改成功')
        resetPasswordForm()
        // 更新用户信息
        await refreshUserInfo()
      } else {
        ElMessage.error(res.message || '密码修改失败')
      }
    } catch (error) {
      console.error('修改密码失败:', error)
      ElMessage.error('修改密码失败')
    } finally {
      passwordLoading.value = false
    }
  })
}

const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.clearValidate()
}

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
/* 自定义样式 */
</style>
