<template>
  <div class="roles-page">
    <a-card class="mb-4">
      <template #title>角色管理</template>
      <template #extra>
        <a-button v-permission="'role:create'" type="primary" @click="handleAdd">新增角色</a-button>
      </template>
    </a-card>
    <a-table :columns="columns" :data-source="dataSource" :loading="loading" :pagination="pagination"
      @change="handleTableChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'description'">
          <span>{{ record.description || '-' }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button v-permission="'role:update'" type="link" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <a-button v-permission.hide="'role:delete'" type="link" size="small" danger @click="handleDelete(record)">
              删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑角色弹窗 -->
    <a-modal v-model:open="modalVisible" :title="modalTitle" :confirm-loading="submitLoading" @ok="handleSubmit"
      @cancel="handleCancel" width="800px" :loading="detailLoading">
      <a-tabs v-model:activeKey="activeTab">
        <a-tab-pane key="basic" tab="基本信息">
          <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-form-item label="角色名称" name="name">
              <a-input v-model:value="form.name" placeholder="请输入角色名称" :maxlength="50" />
            </a-form-item>
            <a-form-item label="角色标识" name="code">
              <a-input v-model:value="form.code" placeholder="请输入角色标识（英文，如：admin）" :maxlength="50"
                :disabled="!!editingId" />
            </a-form-item>
            <a-form-item label="角色描述" name="description">
              <a-textarea v-model:value="form.description" placeholder="请输入角色描述" :rows="4" :maxlength="200"
                show-count />
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="permissions" tab="权限分配">
          <div v-if="permissionsLoading" style="text-align: center; padding: 40px;">
            <a-spin size="large" />
          </div>
          <div v-else>
            <div v-for="(group, resource) in permissionGroups" :key="resource" class="permission-group">
              <div class="permission-group-header">
                <a-checkbox :checked="isResourceAllChecked(resource)" :indeterminate="isResourceIndeterminate(resource)"
                  @change="handleResourceCheckAll(resource, $event)">
                  <strong>{{ getResourceName(resource) }}</strong>
                </a-checkbox>
              </div>
              <div class="permission-items">
                <a-row :gutter="[16, 8]">
                  <a-col :span="8" v-for="permission in group" :key="permission.id">
                    <a-checkbox :checked="form.permissionIds?.includes(permission.id)"
                      @change="handlePermissionChange(permission.id, $event)">
                      {{ permission.name }}
                      <!-- <span class="permission-code">({{ permission.code }})</span> -->
                    </a-checkbox>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, computed, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { TableColumnsType, FormInstance } from 'ant-design-vue'
import { rolesApi, type Role, type CreateRoleForm } from '@/api/roles'
import { permissionsApi, type Permission } from '@/api/permissions'
import { useListRequest } from '@/composables/useListRequest'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

const submitLoading = ref(false)
const detailLoading = ref(false)
const permissionsLoading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref('新增角色')
const formRef = ref<FormInstance>()
const editingId = ref<number | null>(null)
const activeTab = ref('basic')

// 权限相关
const allPermissions = ref<Permission[]>([])
const permissionGroups = computed(() => {
  const groups: Record<string, Permission[]> = {}
  allPermissions.value.forEach((permission) => {
    if (!groups[permission.resource]) {
      groups[permission.resource] = []
    }
    groups[permission.resource].push(permission)
  })
  return groups
})

// 使用列表请求组合函数
const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  refresh: refreshList,
} = useListRequest<Role>({
  requestFn: rolesApi.getList,
  errorMessage: '获取角色列表失败',
})

const form = reactive<CreateRoleForm>({
  name: '',
  code: '',
  description: '',
  permissionIds: [],
})

const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { max: 50, message: '角色名称不能超过50个字符', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
      message: '角色标识只能包含字母、数字和下划线，且必须以字母开头',
      trigger: 'blur'
    },
    { max: 50, message: '角色标识不能超过50个字符', trigger: 'blur' },
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' },
  ],
}

const columns: TableColumnsType = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '角色名称', dataIndex: 'name', key: 'name' },
  { title: '角色标识', dataIndex: 'code', key: 'code' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '操作', key: 'action', width: 150, fixed: 'right' },
]


// 加载所有权限
const fetchAllPermissions = async () => {
  permissionsLoading.value = true
  try {
    const response = await permissionsApi.getList({ page: 1, pageSize: 100 })
    allPermissions.value = response.list
  } catch (error) {
    message.error('获取权限列表失败')
  } finally {
    permissionsLoading.value = false
  }
}

// 获取资源名称（中文显示）
const getResourceName = (resource: string): string => {
  const resourceMap: Record<string, string> = {
    user: '用户管理',
    role: '角色管理',
    permission: '权限管理',
    menu: '菜单管理',
    dict: '数据字典',
    config: '系统配置',
    log: '日志管理',
  }
  return resourceMap[resource] || resource
}

// 检查资源是否全选
const isResourceAllChecked = (resource: string): boolean => {
  const group = permissionGroups.value[resource]
  if (!group || group.length === 0) return false
  return group.every((perm) => form.permissionIds?.includes(perm.id))
}

// 检查资源是否部分选中
const isResourceIndeterminate = (resource: string): boolean => {
  const group = permissionGroups.value[resource]
  if (!group || group.length === 0) return false
  const checkedCount = group.filter((perm) => form.permissionIds?.includes(perm.id)).length
  return checkedCount > 0 && checkedCount < group.length
}

// 资源全选/取消全选
const handleResourceCheckAll = (resource: string, e: any) => {
  const group = permissionGroups.value[resource]
  if (!group) return

  const checked = e.target.checked
  const resourcePermissionIds = group.map((perm) => perm.id)

  if (checked) {
    // 全选：添加该资源的所有权限
    const newIds = [...(form.permissionIds || [])]
    resourcePermissionIds.forEach((id) => {
      if (!newIds.includes(id)) {
        newIds.push(id)
      }
    })
    form.permissionIds = newIds
  } else {
    // 取消全选：移除该资源的所有权限
    form.permissionIds = (form.permissionIds || []).filter((id) => !resourcePermissionIds.includes(id))
  }
}

// 处理单个权限选中/取消选中
const handlePermissionChange = (permissionId: number, e: any) => {
  const checked = e.target.checked
  // 确保 form.permissionIds 是数组
  if (!form.permissionIds) {
    form.permissionIds = []
  }

  if (checked) {
    // 选中：添加到数组（如果不存在）
    if (!form.permissionIds.includes(permissionId)) {
      form.permissionIds = [...form.permissionIds, permissionId]
    }
  } else {
    // 取消选中：从数组移除
    form.permissionIds = form.permissionIds.filter((id) => id !== permissionId)
  }
}

// 新增角色
const handleAdd = () => {
  // 权限检查
  if (!authStore.hasPermission('role:create')) {
    message.error('您没有创建角色的权限')
    return
  }

  modalTitle.value = '新增角色'
  editingId.value = null
  activeTab.value = 'basic'
  modalVisible.value = true
  // 清除表单验证状态
  nextTick(() => {
    formRef.value?.resetFields()
    form.name = ''
    form.code = ''
    form.description = ''
    form.permissionIds = []
  })
}

// 编辑角色
const handleEdit = async (record: Role) => {
  modalTitle.value = '编辑角色'
  editingId.value = record.id
  activeTab.value = 'basic'
  modalVisible.value = true
  detailLoading.value = true

  try {
    const detail = await rolesApi.getDetail(record.id)
    form.name = detail.name
    form.code = detail.code
    form.description = detail.description || ''
    // 回显权限
    form.permissionIds = detail.permissions?.map((rp) => rp.permission.id) || []
  } catch (error) {
    message.error('获取角色详情失败')
    modalVisible.value = false
  } finally {
    detailLoading.value = false
  }
}

// 删除角色
const handleDelete = (record: Role) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除角色 "${record.name}" 吗？删除后无法恢复。`,
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await rolesApi.delete(record.id)
        message.success('删除成功')
        refreshList()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || '删除失败'
        message.error(errorMessage)
      }
    },
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (editingId.value) {
      // 编辑
      await rolesApi.update(editingId.value, form)
      message.success('编辑成功')
    } else {
      // 新增
      await rolesApi.create(form)
      message.success('新增成功')
    }

    modalVisible.value = false
    refreshList()
  } catch (error: any) {
    if (error?.errorFields) {
      // 表单验证错误
      return
    }
    const errorMessage = error?.response?.data?.message || (editingId.value ? '编辑失败' : '新增失败')
    message.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

// 取消表单
const handleCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
  activeTab.value = 'basic'
}

// 初始化加载权限列表
onMounted(() => {
  fetchAllPermissions()
})
</script>

<style scoped lang="scss">
.permission-group {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;

  .permission-group-header {
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }

  .permission-items {
    padding-left: 24px;
  }

  .permission-code {
    color: #999;
    font-size: 12px;
    margin-left: 4px;
  }
}
</style>
