<template>
  <div class="users-page">
    <a-card class="mb-4">
      <template #title>用户管理</template>
      <template #extra>
        <a-button v-permission="'user:create'" type="primary" @click="handleAdd">新增用户</a-button>
      </template>
    </a-card>
    <a-table :columns="columns" :data-source="dataSource" :loading="loading" :pagination="pagination"
      @change="handleTableChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'email'">
          <span>{{ record.email || '-' }}</span>
        </template>
        <template v-if="column.key === 'roles'">
          <a-tag v-for="userRole in record.roles" :key="userRole.id" class="mr-1">
            {{ userRole.role.name }}
          </a-tag>
          <span v-if="!record.roles || record.roles.length === 0">-</span>
        </template>
        <template v-if="column.key === 'validState'">
          <a-tag :color="record.validState === 1 ? 'green' : 'red'">
            {{ record.validState === 1 ? '有效' : '失效' }}
          </a-tag>
        </template>
        <template v-if="column.key === 'createTime'">
          <span>{{ formatDate(record.createTime) }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button v-permission="'user:update'" type="link" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <a-button v-permission.hide="'user:password:update'" type="link" size="small"
              @click="handleChangePassword(record)">
              修改密码
            </a-button>
            <a-button v-permission.hide="'user:delete'" type="link" size="small" danger @click="handleDelete(record)">
              删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑用户弹窗 -->
    <a-modal v-model:open="modalVisible" :title="modalTitle" :confirm-loading="submitLoading" @ok="handleSubmit"
      @cancel="handleCancel" width="600px" :loading="detailLoading">
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="form.username" placeholder="请输入用户名" :maxlength="50" :disabled="!!editingId" />
        </a-form-item>
        <!-- 只在新增时显示密码字段 -->
        <template v-if="!editingId">
          <a-form-item label="密码" name="password">
            <a-input-password v-model:value="form.password" placeholder="请输入密码" :maxlength="100" />
          </a-form-item>
          <a-form-item label="确认密码" name="confirmPassword">
            <a-input-password v-model:value="form.confirmPassword" placeholder="请再次输入密码" :maxlength="100" />
          </a-form-item>
        </template>
        <a-form-item label="昵称" name="nickname">
          <a-input v-model:value="form.nickname" placeholder="请输入昵称" :maxlength="50" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="form.email" placeholder="请输入邮箱" :maxlength="100" />
        </a-form-item>
        <a-form-item label="头像" name="avatar">
          <a-input v-model:value="form.avatar" placeholder="请输入头像URL" :maxlength="500" />
        </a-form-item>
        <a-form-item label="角色" name="roleIds">
          <a-select v-model:value="form.roleIds" mode="multiple" placeholder="请选择角色" :options="roleOptions"
            :loading="rolesLoading" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改密码弹窗 -->
    <a-modal v-model:open="passwordModalVisible" title="修改密码" :confirm-loading="passwordSubmitLoading"
      @ok="handlePasswordSubmit" @cancel="handlePasswordCancel" width="500px">
      <a-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }">
        <a-form-item label="新密码" name="newPassword">
          <a-input-password v-model:value="passwordForm.newPassword" placeholder="请输入新密码" :maxlength="100" />
        </a-form-item>
        <a-form-item label="确认密码" name="confirmPassword">
          <a-input-password v-model:value="passwordForm.confirmPassword" placeholder="请再次输入新密码" :maxlength="100" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { TableColumnsType, FormInstance } from 'ant-design-vue'
import { usersApi, type User, type CreateUserForm, type UpdateUserForm } from '@/api/users'
import { rolesApi, type Role } from '@/api/roles'
import { useListRequest } from '@/composables/useListRequest'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

const submitLoading = ref(false)
const detailLoading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref('新增用户')
const formRef = ref<FormInstance>()
const editingId = ref<number | null>(null)

// 角色相关
const rolesLoading = ref(false)
const roleOptions = ref<Array<{ label: string; value: number }>>([])

// 修改密码相关
const passwordModalVisible = ref(false)
const passwordSubmitLoading = ref(false)
const passwordFormRef = ref<FormInstance>()
const changingPasswordUserId = ref<number | null>(null)

// 使用列表请求组合函数
const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  refresh: refreshList,
} = useListRequest<User>({
  requestFn: usersApi.getList,
  errorMessage: '获取用户列表失败',
})

const form = reactive<CreateUserForm & { confirmPassword?: string }>({
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  email: '',
  avatar: '',
  roleIds: [],
})

// 修改密码表单
const passwordForm = reactive<{
  newPassword: string
  confirmPassword: string
}>({
  newPassword: '',
  confirmPassword: '',
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { max: 50, message: '用户名不能超过50个字符', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
      message: '用户名只能包含字母、数字和下划线，且必须以字母开头',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
    {
      min: 6,
      message: '密码长度不能少于6位',
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: 'blur',
    },
    {
      validator: (_rule: any, value: string) => {
        if (value !== form.password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur',
    },
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { max: 50, message: '昵称不能超过50个字符', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  avatar: [
    { max: 500, message: '头像URL不能超过500个字符', trigger: 'blur' },
  ],
}

const columns: TableColumnsType = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '用户名', dataIndex: 'username', key: 'username' },
  { title: '昵称', dataIndex: 'nickname', key: 'nickname' },
  { title: '邮箱', dataIndex: 'email', key: 'email' },
  { title: '角色', dataIndex: 'roles', key: 'roles' },
  { title: '状态', dataIndex: 'validState', key: 'validState', width: 80 },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
  { title: '操作', key: 'action', width: 220, fixed: 'right' },
]

// 修改密码验证规则
const passwordRules = {
  newPassword: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur',
    },
    {
      min: 6,
      message: '密码长度不能少于6位',
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: '请再次输入新密码',
      trigger: 'blur',
    },
    {
      validator: (_rule: any, value: string) => {
        if (value !== passwordForm.newPassword) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur',
    },
  ],
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// 加载角色列表
const fetchRoles = async () => {
  rolesLoading.value = true
  try {
    const response = await rolesApi.getList({ page: 1, pageSize: 100 })
    roleOptions.value = response.list.map((role: Role) => ({
      label: role.name,
      value: role.id,
    }))
  } catch (error) {
    message.error('获取角色列表失败')
  } finally {
    rolesLoading.value = false
  }
}

// 新增用户
const handleAdd = () => {
  // 权限检查
  if (!authStore.hasPermission('user:create')) {
    message.error('您没有创建用户的权限')
    return
  }

  modalTitle.value = '新增用户'
  editingId.value = null
  modalVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
    form.username = ''
    form.password = ''
    form.confirmPassword = ''
    form.nickname = ''
    form.email = ''
    form.avatar = ''
    form.roleIds = []
  })
}

// 编辑用户
const handleEdit = async (record: User) => {
  modalTitle.value = '编辑用户'
  editingId.value = record.id
  modalVisible.value = true
  detailLoading.value = true

  try {
    const detail = await usersApi.getDetail(record.id)
    form.username = detail.username
    form.nickname = detail.nickname
    form.email = detail.email || ''
    form.avatar = detail.avatar || ''
    // 回显角色
    form.roleIds = detail.roles?.map((userRole) => userRole.role.id) || []
  } catch (error) {
    message.error('获取用户详情失败')
    modalVisible.value = false
  } finally {
    detailLoading.value = false
  }
}

// 修改密码
const handleChangePassword = (record: User) => {
  // 权限校验
  if (!authStore.hasPermission('user:password:update')) {
    message.error('您没有修改密码的权限')
    return
  }

  changingPasswordUserId.value = record.id
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordModalVisible.value = true
  nextTick(() => {
    passwordFormRef.value?.resetFields()
  })
}

// 删除用户
const handleDelete = (record: User) => {
  // 权限校验
  if (!authStore.hasPermission('user:delete')) {
    message.error('您没有删除用户的权限')
    return
  }

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户 "${record.username}" 吗？删除后无法恢复。`,
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await usersApi.delete(record.id)
        message.success('删除成功')
        refreshList()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || '删除失败'
        message.error(errorMessage)
      }
    },
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (editingId.value) {
      // 编辑（不包含密码）
      const updateData: UpdateUserForm = {
        nickname: form.nickname,
        email: form.email || undefined,
        avatar: form.avatar || undefined,
        roleIds: form.roleIds || [],
      }
      await usersApi.update(editingId.value, updateData)
      message.success('编辑成功')
    } else {
      // 新增
      const createData: CreateUserForm = {
        username: form.username,
        password: form.password!,
        nickname: form.nickname,
        email: form.email || undefined,
        avatar: form.avatar || undefined,
        roleIds: form.roleIds || [],
      }
      await usersApi.create(createData)
      message.success('新增成功')
    }

    modalVisible.value = false
    refreshList()
  } catch (error: any) {
    if (error?.errorFields) {
      // 表单验证错误
      return
    }
    const errorMessage =
      error?.response?.data?.message ||
      (editingId.value ? '编辑失败' : '新增失败')
    message.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

// 提交密码修改
const handlePasswordSubmit = async () => {
  // 权限校验
  if (!authStore.hasPermission('user:password:update')) {
    message.error('您没有修改密码的权限')
    passwordModalVisible.value = false
    return
  }

  try {
    await passwordFormRef.value?.validate()
    passwordSubmitLoading.value = true

    if (!changingPasswordUserId.value) {
      message.error('用户ID不存在')
      return
    }

    await usersApi.update(changingPasswordUserId.value, {
      password: passwordForm.newPassword,
    })
    message.success('密码修改成功')
    passwordModalVisible.value = false
  } catch (error: any) {
    if (error?.errorFields) {
      // 表单验证错误
      return
    }
    const errorMessage = error?.response?.data?.message || '密码修改失败'
    message.error(errorMessage)
  } finally {
    passwordSubmitLoading.value = false
  }
}

// 取消密码修改
const handlePasswordCancel = () => {
  passwordModalVisible.value = false
  passwordFormRef.value?.resetFields()
}

// 取消表单
const handleCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 初始化加载角色列表
onMounted(() => {
  fetchRoles()
})
</script>
