<template>
  <doc-alert title="功能权限" url="https://doc.iocoder.cn/resource-permission" />
  <doc-alert title="数据权限" url="https://doc.iocoder.cn/data-permission" />

  <!-- 使用 TableList 组件 -->
  <TableList
    ref="tableListRef"
    :config="tableListConfig"
    @update:data="list = $event"
    @update:loading="loading = $event"
  />

  <!-- 表单弹窗：添加/修改 -->
  <RoleForm ref="formRef" @success="handleFormSuccess" />
  <!-- 表单弹窗：菜单权限 -->
  <RoleAssignMenuForm ref="assignMenuFormRef" @success="handleFormSuccess" />
  <!-- 表单弹窗：门户菜单权限 -->
  <RoleAssignPortalMenuForm ref="assignPortalMenuFormRef" @success="handleFormSuccess" />

  <!-- 表单弹窗：数据权限 -->
  <RoleDataPermissionForm ref="dataPermissionFormRef" @success="handleFormSuccess" />
  <!-- 人员列表弹窗 -->
  <UserListDialog ref="UserListDialogRef" />
</template>
<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from '@/hooks/web/useI18n'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { checkPermi } from '@/utils/permission'
import * as RoleApi from '@/api/system/role'
import RoleForm from './RoleForm.vue'
import RoleAssignMenuForm from './RoleAssignMenuForm.vue'
import RoleAssignPortalMenuForm from './RoleAssignPortalMenuForm.vue'
import RoleDataPermissionForm from './RoleDataPermissionForm.vue'
import UserListDialog from './UserListDialog.vue'
import TableList from '@/components/TableList/index.vue'
import type { TableListConfig } from '@/components/TableList/types'

defineOptions({ name: 'SystemRole' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(false) // 列表的加载中
const list = ref<RoleApi.RoleVO[]>([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: '',
  name: '',
  status: undefined,
  createTime: []
})
const exportLoading = ref(false) // 导出的加载中
const checkedIds = ref<number[]>([]) // 选中的角色ID数组
//人员列表
const UserListDialogRef = ref<InstanceType<typeof UserListDialog>>()
const tableListRef = ref<InstanceType<typeof TableList>>() // TableList组件引用
const handleSelectionChange = (rows: RoleApi.RoleVO[]) => {
  checkedIds.value = rows.map((row) => row.id)
}
const roleSearchFormConfig = {
  items: [
    {
      field: 'name',
      label: '角色名称',
      type: 'input' as const,
      placeholder: '请输入角色名称'
    },
    {
      field: 'code',
      label: '角色标识',
      type: 'input' as const,
      placeholder: '请输入角色标识'
    },
    {
      field: 'status',
      label: '状态',
      type: 'select' as const,
      placeholder: '请选择状态',
      options: getIntDictOptions(DICT_TYPE.COMMON_STATUS).map((dict: any) => ({
        label: dict.label,
        value: dict.value
      }))
    },
    {
      field: 'createTime',
      label: '创建时间',
      type: 'date-range' as const,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')]
    }
  ]
}
const roleTableColumns = [
  {
    prop: 'name',
    label: '角色名称',
    width: 120,
    align: 'center' as const
  },
  // {
  //   prop: 'type',
  //   label: '角色类型',
  //   width: 120,
  //   align: 'center' as const,
  //   dictType: DICT_TYPE.SYSTEM_ROLE_TYPE
  // },
  {
    prop: 'code',
    label: '角色标识',
    width: 180,
    align: 'center' as const
  },
  {
    prop: 'sort',
    label: '显示顺序',
    width: 100,
    align: 'center' as const
  },
  {
    prop: 'remark',
    label: '备注',
    minWidth: 220,
    align: 'center' as const
  },
  {
    prop: 'status',
    label: '状态',
    width: 80,
    align: 'center' as const,
    dictType: DICT_TYPE.COMMON_STATUS
  },
  {
    prop: 'creatorName',
    label: '创建人',
    align: 'center',
    width: 180
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: 180,
    align: 'center' as const,
    formatter: (row: RoleApi.RoleVO) => dateFormatter(row, {}, row.createTime)
  },
  {
    prop: 'updaterName',
    label: '修改人',
    align: 'center',
    width: 180
  },
  {
    prop: 'updateTime',
    label: '修改时间',
    align: 'center',
    width: 180,
    formatter: (row: any) => dateFormatter({}, {}, row.updateTime)
  }
]
// TableList 操作按钮配置
const roleTableActions = [
  {
    label: '新增',
    type: 'primary' as const,
    icon: 'ep:plus',
    permission: 'system:role:create',
    handler: () => openForm('create')
  },
  // {
  //   label: '导出',
  //   type: 'success' as const,
  //   icon: 'ep:download',
  //   loading: exportLoading,
  //   permission: 'system:role:export',
  //   handler: () => handleExport()
  // },
  {
    label: '批量删除',
    type: 'danger' as const,
    icon: 'ep:delete',
    disabled: computed(() => checkedIds.value.length === 0),
    permission: 'system:role:delete',
    handler: () => handleDeleteBatch()
  }
]
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RoleApi.exportRole(queryParams)
    download.excel(data, '角色数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
// TableList 配置
const tableListConfig: TableListConfig = {
  searchForm: roleSearchFormConfig,
  actions: roleTableActions,
  settings: {
    refresh: true, // 显示刷新按钮
    download: false, // 传递角色管理页面的导出方法
    print: true, // 不显示打印按钮
    size: true, // 显示大小设置按钮
    columns: true, // 显示列设置按钮
    fullscreen: true // 暂时不显示全屏按钮
  },
  table: {
    loading: false,
    data: list.value,
    selection: true,
    actionsWidth: 200, //操作列的宽度
    columns: [...roleTableColumns],
    actions: [
      {
        label: '人员',
        type: 'primary',
        link: true,
        show: (row) => checkPermi(['system:role:query']),
        handler: (row) => handleUserList(row.id)
      },
      {
        label: '菜单权限',
        type: 'primary',
        link: true,
        // show: (row) => checkPermi(['system:permission:assign-role-menu']),
        handler: (row) => openAssignMenuForm(row)
      },
      {
        label: '编辑',
        type: 'primary',
        link: true,
        show: (row) => checkPermi(['system:role:update']),
        handler: (row) => openForm('update', row.id)
      },
      // {
      //   label: '数据权限',
      //   type: 'primary',
      //   link: true,
      //   show: (row) => checkPermi(['system:permission:assign-role-data-scope']),
      //   handler: (row) => openDataPermissionForm(row)
      // },
      {
        label: '删除',
        type: 'danger',
        link: true,
        show: (row) => checkPermi(['system:role:delete']),
        handler: (row) => handleDelete(row.id)
      }
    ]
  },
  pagination: {
    show: true,
    pageSize: 10
  },
  api: {
    getList: async (params) => {
      const response = await RoleApi.getRolePage(params)
      return response
    }
  },
  queryParams: queryParams,
  onSearch: () => {
    handleQuery()
  },
  onReset: () => {
    resetQuery()
  },
  onSelectionChange: handleSelectionChange
}

/** 表单操作成功后的回调 */
const handleFormSuccess = () => {
  tableListRef.value?.getList()
}

//用户列表
const handleUserList = (id) => {
  console.log('用户列表:', id)
  // 如果需要打开用户选择弹窗
  UserListDialogRef.value?.open?.(id)
}

/** 查询角色列表 - 由 TableList 组件处理 */

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  tableListRef.value?.getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  queryParams.name = ''
  queryParams.code = ''
  queryParams.status = undefined
  queryParams.createTime = []
  tableListRef.value?.getList()
}

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof RoleForm>>()
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

/** 数据权限操作 */
const dataPermissionFormRef = ref<InstanceType<typeof RoleDataPermissionForm>>()
const openDataPermissionForm = async (row: RoleApi.RoleVO) => {
  dataPermissionFormRef.value?.open(row)
}

/** 菜单权限操作 */
const assignMenuFormRef = ref<InstanceType<typeof RoleAssignMenuForm>>()
const openAssignMenuForm = async (row: RoleApi.RoleVO) => {
  assignMenuFormRef.value?.open(row)
}

/** 门户菜单权限操作 */
const assignPortalMenuFormRef = ref<InstanceType<typeof RoleAssignPortalMenuForm>>()
const openAssignPortalMenuForm = async (row: RoleApi.RoleVO) => {
  assignPortalMenuFormRef.value?.open(row)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RoleApi.deleteRole(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await tableListRef.value?.getList()
  } catch {}
}

/** 批量删除按钮操作 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起批量删除
    await RoleApi.deleteRoleList(checkedIds.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await tableListRef.value?.getList()
  } catch {}
}
onMounted(() => {
  // 初始化时调用 getList()
  tableListRef.value.getList()
})
/** 初始化 */
</script>
<style lang="scss" scoped>
:deep(.el-popper) {
  min-width: 50px !important; /* 强制覆盖默认样式 */
}
</style>
