<script setup lang="ts">
/**
 * 个人中心
 *
 * 三个模块：
 *   - 左卡片：头像 + 登录信息（用户名 / 角色 / 最近登录时间 / IP / 创建时间）
 *   - 右卡片：修改资料（昵称 / 邮箱 / 手机号），保存后同步 userStore.adminInfo
 *   - 右卡片：修改密码（原密码 / 新密码 / 确认密码）
 *
 * 后端接口：
 *   GET  /api/admin/info                      当前管理员信息
 *   PUT  /api/admin/profile                   更新自己的资料
 *   PUT  /api/admin/password                  修改自己的密码
 *   POST /api/admin/avatar/upload             上传头像（bizType=admin-avatar）
 */
import { computed, reactive, ref, watch } from 'vue'
import { Check, Lock, User as UserIcon } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  changePasswordApi,
  updateAdminProfileApi,
  type AdminProfilePayload
} from '@/api/admin'
import { useUserStore } from '@/stores/modules/user'
import { formatDate } from '@/utils/date'
import ImageUploader from '@/components/business/ImageUploader.vue'

const userStore = useUserStore()

const ROLE_LABELS: Record<string, { text: string; type: 'danger' | 'warning' | 'info' }> = {
  super_admin: { text: '超级管理员', type: 'danger' },
  admin: { text: '管理员', type: 'warning' },
  operator: { text: '运营', type: 'info' }
}

const info = computed(() => userStore.adminInfo)
const roleLabel = computed(() => {
  const r = info.value?.role
  return r ? (ROLE_LABELS[r] ?? { text: r, type: 'info' as const }) : { text: '-', type: 'info' as const }
})

// ============================================================
// 修改资料
// ============================================================
const profileFormRef = ref<FormInstance>()
const profileSubmitting = ref(false)

interface ProfileFormState {
  nickname: string
  email: string
  phone: string
}

function emptyProfileForm(): ProfileFormState {
  return { nickname: '', email: '', phone: '' }
}

const profileForm = reactive<ProfileFormState>(emptyProfileForm())

// 资料表单随管理员信息变化回填
watch(
  info,
  (v) => {
    profileForm.nickname = v?.nickname ?? ''
    profileForm.email = v?.email ?? ''
    profileForm.phone = v?.phone ?? ''
  },
  { immediate: true }
)

const profileRules: FormRules<ProfileFormState> = {
  email: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
  phone: [
    {
      pattern: /^$|^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
      trigger: 'blur'
    }
  ]
}

async function handleSaveProfile() {
  if (!profileFormRef.value) return
  await profileFormRef.value.validate(async (valid) => {
    if (!valid) return
    profileSubmitting.value = true
    try {
      const payload: AdminProfilePayload = {
        nickname: profileForm.nickname.trim(),
        email: profileForm.email.trim() || undefined,
        phone: profileForm.phone.trim() || undefined
      }
      await updateAdminProfileApi(payload)
      ElMessage.success('保存成功')
      // 同步 store 里的管理员信息，顶栏昵称/头像即时更新
      if (userStore.adminInfo) {
        userStore.adminInfo = {
          ...userStore.adminInfo,
          nickname: payload.nickname ?? '',
          email: payload.email ?? '',
          phone: payload.phone ?? ''
        }
      }
    } catch {
      /* 拦截器已提示 */
    } finally {
      profileSubmitting.value = false
    }
  })
}

// ============================================================
// 头像上传
// ============================================================
const avatarSaving = ref(false)

// 头像 v-model：getter 读 store，setter 写回 store 并触发持久化
const avatar = computed({
  get: () => userStore.adminInfo?.avatar ?? '',
  set: (val: string | undefined) => {
    if (userStore.adminInfo) userStore.adminInfo.avatar = val ?? ''
  }
})

watch(
  () => userStore.adminInfo?.avatar,
  async (newVal, oldVal) => {
    // 仅在上传后触发（值有变化），避免初始化时误调
    if (!newVal || newVal === oldVal) return
    avatarSaving.value = true
    try {
      await updateAdminProfileApi({ avatar: newVal })
      ElMessage.success('头像已更新')
    } catch {
      /* 拦截器已提示 */
    } finally {
      avatarSaving.value = false
    }
  }
)

// ============================================================
// 修改密码
// ============================================================
const pwdFormRef = ref<FormInstance>()
const pwdSubmitting = ref(false)

const pwdForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const pwdRules: FormRules = {
  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: (_r, val, cb) => {
        if (!val) return cb(new Error('请再次输入新密码'))
        if (val !== pwdForm.newPassword) return cb(new Error('两次输入的密码不一致'))
        cb()
      },
      trigger: 'blur'
    }
  ]
}

async function handleChangePassword() {
  if (!pwdFormRef.value) return
  await pwdFormRef.value.validate(async (valid) => {
    if (!valid) return
    pwdSubmitting.value = true
    try {
      await changePasswordApi({
        oldPassword: pwdForm.oldPassword,
        newPassword: pwdForm.newPassword
      })
      ElMessage.success('密码修改成功')
      pwdForm.oldPassword = ''
      pwdForm.newPassword = ''
      pwdForm.confirmPassword = ''
      pwdFormRef.value?.resetFields()
    } catch {
      /* 拦截器已提示 */
    } finally {
      pwdSubmitting.value = false
    }
  })
}
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <div>
        <h2>个人中心</h2>
        <p class="page-desc">管理你的账号资料、头像与登录密码</p>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 左：头像 + 登录信息 -->
      <el-col :xs="24" :md="9" :lg="8">
        <el-card shadow="never" class="info-card">
          <div class="avatar-block">
            <div class="avatar-wrap">
              <ImageUploader
                v-model="avatar"
                biz-type="admin-avatar"
                :max-size="5"
                class="avatar-uploader"
              />
            </div>
            <div class="avatar-name">{{ info?.nickname || info?.username || '管理员' }}</div>
            <div class="avatar-role">
              <el-tag :type="roleLabel.type" size="small" effect="plain">{{ roleLabel.text }}</el-tag>
            </div>
            <div v-if="avatarSaving" class="avatar-saving">
              <el-icon class="is-loading"><Check /></el-icon> 头像保存中…
            </div>
          </div>

          <el-divider />

          <div class="info-list">
            <div class="info-item">
              <span class="info-label"><el-icon><UserIcon /></el-icon> 用户名</span>
              <span class="info-value">{{ info?.username || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label"><el-icon><Lock /></el-icon> 账号状态</span>
              <span class="info-value">
                <el-tag :type="info?.status === 1 ? 'success' : 'danger'" size="small">
                  {{ info?.status === 1 ? '正常' : '已禁用' }}
                </el-tag>
              </span>
            </div>
            <div class="info-item">
              <span class="info-label"><el-icon><Lock /></el-icon> 最近登录</span>
              <span class="info-value">{{ info?.lastLoginTime ? formatDate(info.lastLoginTime) : '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label"><el-icon><Lock /></el-icon> 登录 IP</span>
              <span class="info-value">{{ info?.lastLoginIp || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label"><el-icon><Lock /></el-icon> 创建时间</span>
              <span class="info-value">{{ info?.createTime ? formatDate(info.createTime) : '-' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右：修改资料 + 修改密码 -->
      <el-col :xs="24" :md="15" :lg="16">
        <el-card shadow="never" class="form-card">
          <template #header>
            <span class="card-title">修改资料</span>
          </template>
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="90px"
            class="profile-form"
          >
            <el-form-item label="昵称">
              <el-input v-model="profileForm.nickname" placeholder="请输入昵称" maxlength="30" show-word-limit />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" placeholder="选填" maxlength="100" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="profileForm.phone" placeholder="选填" maxlength="11" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="profileSubmitting" @click="handleSaveProfile">
                保存资料
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card shadow="never" class="form-card">
          <template #header>
            <span class="card-title">修改密码</span>
          </template>
          <el-form
            ref="pwdFormRef"
            :model="pwdForm"
            :rules="pwdRules"
            label-width="90px"
            class="profile-form"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="pwdForm.oldPassword"
                type="password"
                show-password
                placeholder="请输入原密码"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="pwdForm.newPassword"
                type="password"
                show-password
                placeholder="至少 6 位"
                autocomplete="new-password"
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="pwdForm.confirmPassword"
                type="password"
                show-password
                placeholder="再次输入新密码"
                autocomplete="new-password"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="pwdSubmitting" @click="handleChangePassword">
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.info-card {
  .avatar-block {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 8px 0 4px;
  }

  .avatar-wrap {
    :deep(.image-uploader) {
      display: block;
    }
    :deep(.uploader-trigger) {
      .el-upload {
        border-radius: 50%;
        width: 96px;
        height: 96px;
        overflow: hidden;
      }
      .el-upload--picture-card {
        width: 96px;
        height: 96px;
      }
      .preview-image {
        width: 96px;
        height: 96px;
        border-radius: 50%;
        object-fit: cover;
      }
      .upload-text {
        font-size: 12px;
      }
    }
  }

  .avatar-name {
    margin-top: 10px;
    font-size: 16px;
    font-weight: 600;
    color: $color-text-primary;
  }
  .avatar-role {
    margin-top: 6px;
  }
  .avatar-saving {
    margin-top: 8px;
    font-size: 12px;
    color: $color-text-secondary;
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

.info-list {
  .info-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    font-size: 14px;
    border-bottom: 1px dashed $color-border-light;

    &:last-child {
      border-bottom: none;
    }
  }
  .info-label {
    display: flex;
    align-items: center;
    gap: 6px;
    color: $color-text-secondary;
    font-size: 13px;
  }
  .info-value {
    color: $color-text-primary;
    font-size: 13px;
    word-break: break-all;
    text-align: right;
  }
}

.form-card {
  margin-bottom: 20px;
  .card-title {
    font-weight: 600;
    color: $color-text-primary;
  }
  .profile-form {
    max-width: 460px;
  }
}
</style>
