<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:role:add'"
          type="primary"
          :icon="CirclePlus"
          size="large"
          class="is-solid"
          @click="handleAdd"
        >
          新增
        </el-button>
        <el-button
          v-permission="'sys:role: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
        />
      </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:role:edit'" type="primary" link @click="handleEdit(row)">
          编辑
        </el-button>
        <el-button v-permission="'sys:role:delete'" type="danger" link @click="handleDelete(row)">
          删除
        </el-button>
        <el-button v-permission="'sys:role:assign'" type="primary" link @click="handleAssign(row)">
          分配权限
        </el-button>
      </template>
    </TableCard>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="500px"
      destroy-on-close
    >
      <el-form ref="formRef" :model="roleForm" :rules="formRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="roleForm.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="roleForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="roleForm.status" active-text="正常" inactive-text="停用" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="roleForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog v-model="assignDialogVisible" title="分配权限" width="500px" destroy-on-close>
      <el-tree
        ref="treeRef"
        :data="menuTree"
        show-checkbox
        check-strictly
        node-key="id"
        default-expand-all
        :props="{ label: 'label', children: 'children' }"
      />
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAssignSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

  // ========== 类型定义 ==========
  interface RoleRow {
    id: number
    roleName: string
    roleKey: string
    sort: number
    status: string
    remark: string
    createTime: string
    menuIds: number[]
  }

  interface RoleForm {
    id?: number
    roleName: string
    roleKey: string
    sort: number
    status: boolean
    remark: string
  }

  interface MenuItem {
    id: number
    label: string
    children?: MenuItem[]
  }

  // ========== 表格配置 ==========
  const columns = [
    { type: 'selection' as const, width: 55 },
    { prop: 'roleName', label: '角色名称', minWidth: 120 },
    { prop: 'roleKey', label: '权限字符', minWidth: 120 },
    { prop: 'sort', label: '排序', minWidth: 80 },
    { prop: 'status', label: '状态', minWidth: 80 },
    { prop: 'createTime', label: '创建时间', minWidth: 160 },
    { prop: 'operation', label: '操作', minWidth: 280, isAction: true },
  ]

  // ========== Mock 数据 ==========
  const tableData = ref<RoleRow[]>([
    {
      id: 1,
      roleName: '超级管理员',
      roleKey: 'admin',
      sort: 1,
      status: '正常',
      remark: '拥有所有权限',
      createTime: '2024-01-01 10:00:00',
      menuIds: [
        1, 100, 101, 1011, 1012, 1013, 102, 1021, 1022, 1023, 1024, 103, 1031, 1032, 1033, 200, 300,
        301,
      ],
    },
    {
      id: 2,
      roleName: '内容编辑',
      roleKey: 'editor',
      sort: 2,
      status: '正常',
      remark: '内容管理权限',
      createTime: '2024-01-15 14:30:00',
      menuIds: [1, 200, 300, 301],
    },
    {
      id: 3,
      roleName: '运营人员',
      roleKey: 'operator',
      sort: 3,
      status: '正常',
      remark: '运营相关权限',
      createTime: '2024-02-01 09:00:00',
      menuIds: [1, 300, 301],
    },
    {
      id: 4,
      roleName: '普通用户',
      roleKey: 'user',
      sort: 4,
      status: '正常',
      remark: '基本查看权限',
      createTime: '2024-02-20 11:15:00',
      menuIds: [1],
    },
    {
      id: 5,
      roleName: '已禁用角色',
      roleKey: 'disabled',
      sort: 5,
      status: '停用',
      remark: '已禁用的测试角色',
      createTime: '2024-03-01 16:45:00',
      menuIds: [],
    },
  ])

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

  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.roleName.toLowerCase().includes(keyword) || row.roleKey.toLowerCase().includes(keyword)
    )
  })

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

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

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

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

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

  const createDefaultForm = (): RoleForm => ({
    roleName: '',
    roleKey: '',
    sort: 0,
    status: true,
    remark: '',
  })

  const roleForm = reactive<RoleForm>(createDefaultForm())

  const formRules = reactive<FormRules>({
    roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    roleKey: [{ required: true, message: '请输入权限字符', trigger: 'blur' }],
  })

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

  function handleEdit(row: RoleRow) {
    isEdit.value = true
    Object.assign(roleForm, {
      id: row.id,
      roleName: row.roleName,
      roleKey: row.roleKey,
      sort: row.sort,
      status: row.status === '正常',
      remark: row.remark,
    })
    roleDialogVisible.value = true
  }

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

      const statusText = roleForm.status ? '正常' : '停用'
      const now = new Date()
      const pad = (n: number) => String(n).padStart(2, '0')
      const formattedDate = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`

      if (isEdit.value && roleForm.id) {
        const index = tableData.value.findIndex((r) => r.id === roleForm.id)
        if (index !== -1) {
          tableData.value[index] = {
            ...tableData.value[index],
            roleName: roleForm.roleName,
            roleKey: roleForm.roleKey,
            sort: roleForm.sort,
            status: statusText,
            remark: roleForm.remark,
          }
        }
        ElMessage.success('修改成功')
      } else {
        const newId =
          tableData.value.length > 0 ? Math.max(...tableData.value.map((r) => r.id)) + 1 : 1
        tableData.value.push({
          id: newId,
          roleName: roleForm.roleName,
          roleKey: roleForm.roleKey,
          sort: roleForm.sort,
          status: statusText,
          remark: roleForm.remark,
          createTime: formattedDate,
          menuIds: [],
        })
        ElMessage.success('新增成功')
      }

      roleDialogVisible.value = false
    })
  }

  // ========== 删除 ==========
  function handleDelete(row: RoleRow) {
    ElMessageBox.confirm(`确认删除角色「${row.roleName}」？`, '提示', {
      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(() => {})
  }

  // ========== 分配权限 ==========
  const assignDialogVisible = ref(false)
  const currentAssignRole = ref<RoleRow | null>(null)
  const treeRef = ref<{
    getCheckedKeys: () => number[]
    setCheckedKeys: (keys: number[]) => void
  }>()

  const menuTree = ref<MenuItem[]>([
    { id: 1, label: '首页', children: [] },
    {
      id: 100,
      label: '系统管理',
      children: [
        {
          id: 101,
          label: '用户管理',
          children: [
            { id: 1011, label: '新增用户' },
            { id: 1012, label: '编辑用户' },
            { id: 1013, label: '删除用户' },
          ],
        },
        {
          id: 102,
          label: '角色管理',
          children: [
            { id: 1021, label: '新增角色' },
            { id: 1022, label: '编辑角色' },
            { id: 1023, label: '删除角色' },
            { id: 1024, label: '分配权限' },
          ],
        },
        {
          id: 103,
          label: '菜单管理',
          children: [
            { id: 1031, label: '新增菜单' },
            { id: 1032, label: '编辑菜单' },
            { id: 1033, label: '删除菜单' },
          ],
        },
      ],
    },
    { id: 200, label: 'SDK管理', children: [] },
    {
      id: 300,
      label: '内容管理',
      children: [{ id: 301, label: '文章管理' }],
    },
  ])

  function handleAssign(row: RoleRow) {
    currentAssignRole.value = row
    assignDialogVisible.value = true
    nextTick(() => {
      treeRef.value?.setCheckedKeys(row.menuIds)
    })
  }

  function handleAssignSubmit() {
    if (currentAssignRole.value) {
      const checkedKeys = treeRef.value?.getCheckedKeys() ?? []
      const index = tableData.value.findIndex((r) => r.id === currentAssignRole.value!.id)
      if (index !== -1) {
        tableData.value[index].menuIds = checkedKeys
      }
      ElMessage.success('权限分配成功')
    }
    assignDialogVisible.value = false
  }
</script>

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