<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKey">
        <el-input v-model="queryParams.roleKey" placeholder="请输入权限字符" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="角色状态" clearable>
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="!selectedIds.length" @click="handleDelete">删除</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="角色编号" prop="role_id" width="100" />
      <el-table-column label="角色名称" prop="role_name" width="150" show-overflow-tooltip />
      <el-table-column label="权限字符" prop="role_key" width="150" show-overflow-tooltip />
      <el-table-column label="显示顺序" prop="role_sort" width="100" />
      <el-table-column label="状态" prop="status" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            active-value="0"
            inactive-value="1"
            :disabled="row.role_id === 1"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="create_time" width="160" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)" v-if="row.role_id !== 1">编辑</el-button>
          <el-button link type="primary" @click="handleMenuScope(row)" v-if="row.role_id !== 1">菜单权限</el-button>
          <el-button link type="danger" @click="handleDelete(row)" v-if="row.role_id !== 1">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="getList"
      @current-change="getList"
      style="margin-top: 15px; justify-content: flex-end"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="0">正常</el-radio>
            <el-radio value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 菜单权限对话框 -->
    <el-dialog title="分配菜单权限" v-model="menuDialogVisible" width="500px" append-to-body>
      <el-tree
        ref="menuTreeRef"
        :data="menuTree"
        :props="{ children: 'children', label: 'label' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedMenuIds"
        default-expand-all
      />
      <template #footer>
        <el-button @click="menuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitMenuScope">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 角色管理页面
 * @author 湖北新华业务中台研发团队
 */
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleName: '',
  roleKey: '',
  status: ''
})

// 列表数据
const loading = ref(false)
const roleList = ref([])
const total = ref(0)
const selectedIds = ref([])

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = ref({})

// 菜单权限对话框
const menuDialogVisible = ref(false)
const menuTreeRef = ref()
const menuTree = ref([])
const checkedMenuIds = ref([])
const currentRoleId = ref(null)

const rules = {
  roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
  roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
  roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }]
}

// 获取角色列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/system/role/list', { params: queryParams })
    roleList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取角色列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取菜单树
const getMenuTree = async () => {
  try {
    const res = await request.get('/api/system/role/menuTree')
    menuTree.value = res.data || []
  } catch (error) {
    console.error('获取菜单树失败:', error)
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.roleName = ''
  queryParams.roleKey = ''
  queryParams.status = ''
  handleQuery()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.role_id)
}

// 新增
const handleAdd = () => {
  form.value = { status: '0', roleSort: 0 }
  dialogTitle.value = '新增角色'
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  try {
    const res = await request.get(`/api/system/role/${row.role_id}`)
    const data = res.data
    form.value = {
      roleId: data.role_id,
      roleName: data.role_name,
      roleKey: data.role_key,
      roleSort: data.role_sort,
      status: data.status,
      remark: data.remark
    }
    dialogTitle.value = '编辑角色'
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取角色信息失败')
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value?.validate()
  try {
    if (form.value.roleId) {
      await request.put('/api/system/role', form.value)
      ElMessage.success('修改成功')
    } else {
      await request.post('/api/system/role', form.value)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 删除
const handleDelete = async (row) => {
  const ids = row?.role_id ? [row.role_id] : selectedIds.value
  if (!ids.length) return
  
  await ElMessageBox.confirm('确认删除选中的角色?', '提示', { type: 'warning' })
  try {
    await request.delete(`/api/system/role/${ids.join(',')}`)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error(error.message || '删除失败')
  }
}

// 状态修改
const handleStatusChange = async (row) => {
  const text = row.status === '0' ? '启用' : '停用'
  try {
    await request.put('/api/system/role/changeStatus', { roleId: row.role_id, status: row.status })
    ElMessage.success(`${text}成功`)
  } catch (error) {
    row.status = row.status === '0' ? '1' : '0'
    ElMessage.error(`${text}失败`)
  }
}

// 菜单权限
const handleMenuScope = async (row) => {
  currentRoleId.value = row.role_id
  try {
    const res = await request.get(`/api/system/role/roleMenuIds/${row.role_id}`)
    checkedMenuIds.value = res.data || []
    menuDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取角色菜单失败')
  }
}

// 提交菜单权限
const submitMenuScope = async () => {
  const menuIds = menuTreeRef.value?.getCheckedKeys() || []
  const halfCheckedKeys = menuTreeRef.value?.getHalfCheckedKeys() || []
  const allMenuIds = [...menuIds, ...halfCheckedKeys]
  
  try {
    await request.put('/api/system/role', {
      roleId: currentRoleId.value,
      menuIds: allMenuIds
    })
    ElMessage.success('菜单权限设置成功')
    menuDialogVisible.value = false
  } catch (error) {
    ElMessage.error('菜单权限设置失败')
  }
}

onMounted(() => {
  getList()
  getMenuTree()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 15px;
}
.mb10 {
  margin-bottom: 10px;
}
</style>
