<template>
  <div>
    <Breadcrumb />
    <TableCard
      v-model:page-no="queryParams.pageNo"
      v-model:page-size="queryParams.pageSize"
      :data="filteredData"
      :columns="columns"
      :total="total"
      @change="handlePageChange"
      @selection-change="handleSelectionChange"
    >
      <template #toolbar-left>
        <el-button
          v-permission="'sys:user:add'"
          type="primary"
          :icon="CirclePlus"
          size="large"
          class="is-solid"
          @click="handleAdd"
          >新增用户</el-button
        >
        <el-button
          v-permission="'sys:user:delete'"
          type="primary"
          :icon="Delete"
          size="large"
          class="is-solid"
          :disabled="selectedRows.length === 0"
          @click="handleBatchDelete"
          >删除</el-button
        >
        <el-button
          type="primary"
          :icon="Refresh"
          size="large"
          class="is-solid"
          @click="handleRefresh"
          >刷新</el-button
        >
      </template>
      <template #toolbar-right>
        <el-input
          v-model="searchKeyword"
          :prefix-icon="Search"
          size="large"
          placeholder="请输入用户名或昵称搜索"
          style="width: 300px"
          clearable
        />
        <el-button :icon="Search" type="primary" class="is-solid" size="large" @click="handleSearch"
          >搜索</el-button
        >
      </template>

      <template #column-roles="{ row }">
        <el-tag v-for="role in row.roleList" :key="role" size="small" style="margin-right: 4px">
          {{ role }}
        </el-tag>
      </template>

      <template #column-status="{ row }">
        <el-tag :type="row.status === '正常' ? 'success' : 'danger'">
          {{ row.status }}
        </el-tag>
      </template>

      <template #column-operation="{ row }">
        <el-button v-permission="'sys:user:edit'" type="primary" link @click="handleEdit(row)"
          >编辑</el-button
        >
        <el-button v-permission="'sys:user:delete'" type="danger" link @click="handleDelete(row)"
          >删除</el-button
        >
      </template>
    </TableCard>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '新增用户'"
      width="500px"
      destroy-on-close
    >
      <el-form ref="formRef" :model="userForm" :rules="formRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleKeys">
          <el-select
            v-model="userForm.roleKeys"
            multiple
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option label="admin" value="admin" />
            <el-option label="editor" value="editor" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="userForm.statusEnabled" active-text="正常" inactive-text="停用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import TableCard from '@/components/TableCard/index.vue'
  import { CirclePlus, Delete, Refresh, Search } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'

  // ========== 类型定义 ==========
  interface UserRow {
    id: number
    username: string
    nickname: string
    roleList: string[]
    status: string
    createTime: string
  }

  interface UserForm {
    id?: number
    username: string
    nickname: string
    password: string
    roleKeys: string[]
    statusEnabled: boolean
  }

  // ========== 表格配置 ==========
  const columns = [
    { type: 'selection' as const, width: 55 },
    { prop: 'username', label: '用户名', minWidth: 120 },
    { prop: 'nickname', label: '昵称', minWidth: 120 },
    { prop: 'roles', label: '角色', minWidth: 150 },
    { prop: 'status', label: '状态', minWidth: 80 },
    { prop: 'createTime', label: '创建时间', minWidth: 160 },
    { prop: 'operation', label: '操作', minWidth: 200, isAction: true },
  ]

  // ========== Mock 数据 ==========
  const tableData = ref<UserRow[]>([
    {
      id: 1,
      username: 'admin',
      nickname: '超级管理员',
      roleList: ['admin'],
      status: '正常',
      createTime: '2024-01-01 10:00:00',
    },
    {
      id: 2,
      username: 'editor',
      nickname: '内容编辑',
      roleList: ['editor'],
      status: '正常',
      createTime: '2024-01-15 14:30:00',
    },
    {
      id: 3,
      username: 'zhangsan',
      nickname: '张三',
      roleList: ['editor'],
      status: '正常',
      createTime: '2024-02-01 09:00:00',
    },
    {
      id: 4,
      username: 'lisi',
      nickname: '李四',
      roleList: ['admin', 'editor'],
      status: '正常',
      createTime: '2024-02-20 11:15:00',
    },
    {
      id: 5,
      username: 'wangwu',
      nickname: '王五',
      roleList: [],
      status: '停用',
      createTime: '2024-03-01 16:45:00',
    },
  ])

  // ========== 搜索 & 分页 ==========
  const searchKeyword = ref('')
  const selectedRows = ref<UserRow[]>([])

  const queryParams = reactive({
    pageNo: 1,
    pageSize: 10,
  })

  const filteredData = computed(() => {
    if (!searchKeyword.value) return tableData.value
    const keyword = searchKeyword.value.toLowerCase()
    return tableData.value.filter(
      (row) =>
        row.username.toLowerCase().includes(keyword) || row.nickname.toLowerCase().includes(keyword)
    )
  })

  const total = computed(() => filteredData.value.length)

  function handlePageChange(page: number, size: number) {
    queryParams.pageNo = page
    queryParams.pageSize = size
  }

  function handleSelectionChange(selection: UserRow[]) {
    selectedRows.value = selection
  }

  function handleRefresh() {
    searchKeyword.value = ''
    queryParams.pageNo = 1
    ElMessage.success('刷新成功')
  }

  function handleSearch() {
    queryParams.pageNo = 1
  }

  // ========== 新增/编辑 ==========
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const formRef = ref<FormInstance>()

  const createDefaultForm = (): UserForm => ({
    username: '',
    nickname: '',
    password: '',
    roleKeys: [],
    statusEnabled: true,
  })

  const userForm = reactive<UserForm>(createDefaultForm())

  const formRules = reactive<FormRules>({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    roleKeys: [{ required: true, type: 'array', message: '请选择角色', trigger: 'change' }],
  })

  function handleAdd() {
    isEdit.value = false
    Object.assign(userForm, createDefaultForm())
    dialogVisible.value = true
  }

  function handleEdit(row: UserRow) {
    isEdit.value = true
    Object.assign(userForm, {
      id: row.id,
      username: row.username,
      nickname: row.nickname,
      password: '',
      roleKeys: [...row.roleList],
      statusEnabled: row.status === '正常',
    })
    dialogVisible.value = true
  }

  function handleSubmit() {
    formRef.value?.validate((valid) => {
      if (!valid) return

      const statusText = userForm.statusEnabled ? '正常' : '停用'

      if (isEdit.value && userForm.id) {
        const index = tableData.value.findIndex((r) => r.id === userForm.id)
        if (index !== -1) {
          tableData.value[index] = {
            ...tableData.value[index],
            nickname: userForm.nickname,
            roleList: [...userForm.roleKeys],
            status: statusText,
          }
        }
        ElMessage.success('修改成功')
      } else {
        const newId = Math.max(...tableData.value.map((r) => r.id)) + 1
        tableData.value.push({
          id: newId,
          username: userForm.username,
          nickname: userForm.nickname,
          roleList: [...userForm.roleKeys],
          status: statusText,
          createTime: new Date()
            .toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false,
            })
            .replace(/\//g, '-'),
        })
        ElMessage.success('新增成功')
      }

      dialogVisible.value = false
    })
  }

  // ========== 删除 ==========
  function handleDelete(row: UserRow) {
    ElMessageBox.confirm(`确认删除用户「${row.nickname}」？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        const index = tableData.value.findIndex((r) => r.id === row.id)
        if (index !== -1) {
          tableData.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      })
      .catch(() => {})
  }

  function handleBatchDelete() {
    ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 个用户？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        const ids = new Set(selectedRows.value.map((r) => r.id))
        tableData.value = tableData.value.filter((r) => !ids.has(r.id))
        selectedRows.value = []
        ElMessage.success('删除成功')
      })
      .catch(() => {})
  }
</script>

<style lang="scss" scoped></style>
