<template>
  <div class="role-management">
    <!-- 操作栏 -->
    <el-card class="toolbar">
      <div class="toolbar-actions">
        <el-button type="primary" :icon="Plus" @click="handleCreate">
          新建角色
        </el-button>
      </div>
    </el-card>

    <!-- 角色列表 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column prop="roleCode" label="角色编码" width="200" />
        <el-table-column prop="roleName" label="角色名称" width="200" />
        <el-table-column prop="description" label="角色描述" min-width="250" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userCount" label="用户数" width="100" />
        <el-table-column prop="sortOrder" label="排序" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="primary" @click="handleViewPermissions(row)">
              查看权限
            </el-button>
            <el-popconfirm
              title="确定删除该角色吗？"
              @confirm="handleDelete(row.id)"
            >
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新建/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @closed="handleDialogClosed"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="角色编码" prop="roleCode">
          <el-input
            v-model="formData.roleCode"
            placeholder="请输入角色编码（如：ASSET_ADMIN）"
            :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="formData.roleName"
            placeholder="请输入角色名称"
          />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>

        <el-form-item label="权限配置" prop="permissionIds">
          <div class="permission-tree-container">
            <el-tree
              ref="permissionTreeRef"
              :data="permissionTree"
              show-checkbox
              node-key="id"
              :props="treeProps"
              :default-checked-keys="formData.permissionIds"
              @check="handlePermissionCheck"
            >
              <template #default="{ node, data }">
                <span class="tree-node">
                  <i class="node-icon"></i>
                  <span>{{ data.permissionName || data.moduleName }}</span>
                </span>
              </template>
            </el-tree>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看权限对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="角色权限"
      width="600px"
    >
      <div class="permission-view">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="角色编码">
            {{ currentRole?.roleCode }}
          </el-descriptions-item>
          <el-descriptions-item label="角色名称">
            {{ currentRole?.roleName }}
          </el-descriptions-item>
          <el-descriptions-item label="角色描述">
            {{ currentRole?.description || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="permission-list">
          <h4>权限列表</h4>
          <el-tree
            :data="currentRole?.permissions"
            :props="treeProps"
            node-key="id"
            default-expand-all
          >
            <template #default="{ node, data }">
              <span class="tree-node">
                <el-tag size="small" type="info">{{ data.moduleName || '权限' }}</el-tag>
                <span>{{ data.permissionName }}</span>
                <el-tag size="small" style="margin-left: 8px">{{ data.permissionCode }}</el-tag>
              </span>
            </template>
          </el-tree>
        </div>
      </div>

      <template #footer>
        <el-button @click="permissionDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  getRoleList,
  createRole,
  updateRole,
  deleteRole,
  getPermissionTree
} from '@/api/roles'
import type { Role, Permission } from '@/types'

// 响应式数据
const loading = ref(false)
const tableData = ref<Role[]>([])
const permissionTree = ref<Permission[]>([])

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = computed(() => isEdit.value ? '编辑角色' : '新建角色')
const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const permissionTreeRef = ref()

const formData = reactive({
  roleCode: '',
  roleName: '',
  description: '',
  permissionIds: [] as number[]
})

const formRules: FormRules = {
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ]
}

// 查看权限对话框
const permissionDialogVisible = ref(false)
const currentRole = ref<Role>()

// Tree组件配置
const treeProps = {
  children: 'children',
  label: 'permissionName'
}

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const { data } = await getRoleList()
    tableData.value = data
  } finally {
    loading.value = false
  }
}

// 获取权限树
const fetchPermissionTree = async () => {
  try {
    const { data } = await getPermissionTree()
    permissionTree.value = data
  } catch (error) {
    console.error('获取权限树失败:', error)
  }
}

// 新建角色
const handleCreate = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row: Role) => {
  isEdit.value = true
  Object.assign(formData, {
    roleCode: row.roleCode,
    roleName: row.roleName,
    description: row.description || '',
    permissionIds: row.permissions?.map(p => p.id) || []
  })
  dialogVisible.value = true

  // 等待dialog渲染完成后设置选中状态
  setTimeout(() => {
    permissionTreeRef.value?.setCheckedKeys(formData.permissionIds)
  }, 100)
}

// 查看权限
const handleViewPermissions = async (row: Role) => {
  // 获取完整的角色信息（包括权限）
  try {
    // const { data } = await getRoleById(row.id)
    // currentRole.value = data
    currentRole.value = row
    permissionDialogVisible.value = true
  } catch (error) {
    console.error('获取角色详情失败:', error)
  }
}

// 权限树勾选变化
const handlePermissionCheck = () => {
  // 获取所有选中的节点（包括半选中的父节点）
  const checkedKeys = permissionTreeRef.value?.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value?.getHalfCheckedKeys()
  formData.permissionIds = [...checkedKeys, ...halfCheckedKeys]
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate()

  submitLoading.value = true
  try {
    if (isEdit.value) {
      // 编辑模式
      await updateRole(currentRole.value!.id, {
        roleName: formData.roleName,
        description: formData.description,
        permissionIds: formData.permissionIds
      })
      ElMessage.success('更新成功')
    } else {
      // 新建模式
      await createRole(formData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchRoleList()
  } finally {
    submitLoading.value = false
  }
}

// 对话框关闭
const handleDialogClosed = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    roleCode: '',
    roleName: '',
    description: '',
    permissionIds: []
  })
  permissionTreeRef.value?.setCheckedKeys([])
}

// 删除角色
const handleDelete = async (id: number) => {
  try {
    await deleteRole(id)
    ElMessage.success('删除成功')
    fetchRoleList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

onMounted(() => {
  fetchRoleList()
  fetchPermissionTree()
})
</script>

<style scoped lang="scss">
.role-management {
  .toolbar {
    margin-bottom: 16px;
  }

  .table-card {
    .pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 16px;
    }
  }

  .permission-tree-container {
    width: 100%;
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;

    .tree-node {
      display: flex;
      align-items: center;
      gap: 8px;

      .node-icon {
        width: 16px;
        height: 16px;
        background-color: #475569;
        border-radius: 2px;
      }
    }
  }

  .permission-view {
    .permission-list {
      margin-top: 20px;

      h4 {
        margin-bottom: 12px;
        color: #475569;
      }

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