<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="search-section">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名或邮箱"
              clearable
              style="width: 300px"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
          </div>
          <el-button
            type="primary"
            @click="handleAdd"
          >
            新增用户
          </el-button>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="dataSource"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          sortable="custom"
        />
        <el-table-column
          prop="username"
          label="用户名"
          sortable="custom"
        />
        <el-table-column
          prop="nickname"
          label="昵称"
          sortable="custom"
        />
        <el-table-column
          prop="email"
          label="邮箱"
          sortable="custom"
        />
        <el-table-column
          prop="phone"
          label="手机号"
          sortable="custom"
        />
        <el-table-column
          label="状态"
          width="100"
        >
          <template #default="{ row }">
            <el-tag 
              :type="row.status === 1 ? 'success' : 'danger'"
              effect="dark"
              style="font-weight: 500; font-size: 14px;"
            >
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdAt"
          label="创建时间"
          sortable="custom"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="250"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              link
              @click="handleAssignRoles(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 16px; justify-content: flex-end"
        @current-change="handleTableChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <el-dialog
      v-model="modalVisible"
      :title="modalTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item
          label="用户名"
          prop="username"
          required
        >
          <el-input
            v-model="formState.username"
            :disabled="!!formState.id"
          />
        </el-form-item>
        <el-form-item
          v-if="!formState.id"
          label="密码"
          prop="password"
          required
        >
          <el-input
            v-model="formState.password"
            type="password"
          />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="formState.nickname" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="formState.email" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="formState.phone" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formState.status">
            <el-option
              :value="UserStatus.ACTIVE"
              label="正常"
            />
            <el-option
              :value="UserStatus.INACTIVE"
              label="禁用"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleModalCancel">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleModalOk"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="500px"
    >
      <el-transfer
        v-model="selectedRoles"
        :data="allRoles"
        :titles="['可选角色', '已分配角色']"
      />
      <template #footer>
        <el-button @click="roleDialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleAssignRolesOk"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { userApi, type User, type CreateUserRequest, type UpdateUserRequest } from '@/api/user.api'
import { roleApi, type Role } from '@/api/role.api'
import { handleApiError } from '@/utils/errorHandler'
import { UserStatus, StatusHelper } from '@/constants/status'
import { formatDateTime } from '@/utils/dateFormat'

const loading = ref(false)
const dataSource = ref<User[]>([])
const searchKeyword = ref('')
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const sortInfo = reactive({
  sortBy: 'id',
  sortOrder: 'asc' as 'asc' | 'desc'
})

const modalVisible = ref(false)
const modalTitle = ref('')
const formRef = ref()
const formState = reactive<CreateUserRequest & { id?: number; status?: UserStatus }>({
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  roles: [],
  status: UserStatus.ACTIVE
})

const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '用户名只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度在 8 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    { max: 100, message: '邮箱长度不能超过100个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const roleDialogVisible = ref(false)
const selectedRoles = ref<number[]>([])
const allRoles = ref<{ key: number; label: string }[]>([])
const currentUserId = ref<number | null>(null)

const fetchData = async () => {
  loading.value = true
  try {
    const res = await userApi.getPage({
      page: pagination.current - 1,
      size: pagination.pageSize,
      sortBy: sortInfo.sortBy,
      sortOrder: sortInfo.sortOrder,
      username: searchKeyword.value || undefined
    })
    dataSource.value = res.content
    pagination.total = res.totalElements
  } catch (error) {
    handleApiError(error)
  } finally {
    loading.value = false
  }
}

const handleTableChange = () => {
  fetchData()
}

const handleSizeChange = () => {
  pagination.current = 1
  fetchData()
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const handleSortChange = ({ prop, order }: any) => {
  sortInfo.sortBy = prop
  sortInfo.sortOrder = order === 'ascending' ? 'asc' : 'desc'
  fetchData()
}

const handleAdd = () => {
  modalTitle.value = '新增用户'
  Object.assign(formState, {
    id: undefined,
    username: '',
    password: '',
    nickname: '',
    email: '',
    phone: '',
    roles: [],
    status: 'ACTIVE'
  })
  modalVisible.value = true
}

const handleEdit = (row: User) => {
  modalTitle.value = '编辑用户'
  Object.assign(formState, {
    id: row.id,
    username: row.username,
    nickname: row.nickname,
    email: row.email,
    phone: row.phone,
    status: row.status,
    roles: []
  })
  modalVisible.value = true
}

const handleDelete = async (row: User) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await userApi.delete(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      handleApiError(error)
    }
  }
}

const handleModalOk = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (formState.id) {
      const updateData: UpdateUserRequest = {
        nickname: formState.nickname,
        email: formState.email,
        phone: formState.phone,
        status: formState.status
      }
      await userApi.update(formState.id, updateData)
      ElMessage.success('更新成功')
    } else {
      const createData: CreateUserRequest = {
        username: formState.username,
        password: formState.password,
        nickname: formState.nickname,
        email: formState.email,
        phone: formState.phone,
        roles: formState.roles
      }
      await userApi.create(createData)
      ElMessage.success('创建成功')
    }
    modalVisible.value = false
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      handleApiError(error)
    }
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
}

const handleAssignRoles = async (row: User) => {
  currentUserId.value = row.id
  try {
    const roles = await roleApi.getAll()
    allRoles.value = roles.map((role: Role) => ({
      key: role.id,
      label: role.roleName
    }))
    selectedRoles.value = row.roles || []
    roleDialogVisible.value = true
  } catch (error) {
    handleApiError(error)
  }
}

const handleAssignRolesOk = async () => {
  if (!currentUserId.value) return
  
  try {
    await userApi.assignRoles(currentUserId.value, selectedRoles.value)
    ElMessage.success('角色分配成功')
    roleDialogVisible.value = false
    fetchData()
  } catch (error) {
    handleApiError(error)
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="css">
.user-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;

    .search-section {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }
}
</style>
