<!-- 租户角色管理页面 -->
<template>
  <div class="art-full-height">
    <!-- 搜索栏 -->
    <RoleSearch
      v-show="showSearchBar"
      v-model="searchForm"
      @search="handleSearch"
      @reset="resetSearchParams"
    ></RoleSearch>

    <ElCard
      class="art-table-card"
      shadow="never"
      :style="{ 'margin-top': showSearchBar ? '12px' : '0' }"
    >
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap>
            <!-- 租户选择器 -->
            <ElSelect
              v-model="currentTenantId"
              placeholder="请选择租户"
              style="width: 200px"
              filterable
              clearable
            >
              <ElOption
                v-for="item in tenantList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </ElSelect>
            <ElButton
              type="primary"
              :disabled="!currentTenantId"
              @click="showDialog('add')"
              v-ripple
            >
              新增角色
            </ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <template #operation="{ row }">
          <div class="action-wrap">
            <button class="art-action-btn primary" @click="handleAction('edit', row)">
              <ArtSvgIcon icon="ri:edit-2-line" class="art-action-icon" />
              <span>编辑</span>
            </button>
            <button class="art-action-btn warning" @click="handleAction('permission', row)">
              <ArtSvgIcon icon="ri:shield-keyhole-line" class="art-action-icon" />
              <span>权限</span>
            </button>
            <ElDropdown @command="(cmd) => handleAction(cmd, row)">
              <button class="art-action-btn info">
                <ArtSvgIcon icon="ri:more-2-line" class="art-action-icon" />
                <span>更多</span>
              </button>
              <template #dropdown>
                <ElDropdownMenu>
                  <ElDropdownItem command="clone">
                    <div class="flex items-center gap-2">
                      <ArtSvgIcon icon="ri:file-copy-line" />
                      <span>克隆</span>
                    </div>
                  </ElDropdownItem>
                  <ElDropdownItem command="delete" divided>
                    <div class="flex items-center gap-2 text-danger">
                      <ArtSvgIcon icon="ri:delete-bin-line" />
                      <span>删除</span>
                    </div>
                  </ElDropdownItem>
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </div>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 角色编辑弹窗 -->
    <RoleEditDialog
      v-model="dialogVisible"
      :dialog-type="dialogType"
      :role-data="currentRoleData"
      :tenant-id="currentTenantId"
      @success="refreshData"
    />

    <!-- 菜单权限弹窗 -->
    <RolePermissionDialog
      v-model="permissionDialog"
      :role-data="currentRoleData"
      :tenant-id="currentTenantId"
      @success="refreshData"
    />
  </div>
</template>

<script setup lang="ts">
  // ... (script content unchanged)
  import { ref, watch, onMounted } from 'vue'
  import { useTable } from '@/hooks/core/useTable'
  import { fetchGetTenantRoles, fetchDeleteTenantRole } from '@/api/tenant-role'
  import { fetchGetTenantList } from '@/api/tenant'
  import RoleSearch from './modules/role-search.vue'
  import RoleEditDialog from './modules/role-edit-dialog.vue'
  import RolePermissionDialog from './modules/role-permission-dialog.vue'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import { ElMessageBox, ElMessage, ElSelect, ElOption, ElButton, ElSpace } from 'element-plus'

  defineOptions({ name: 'TenantRole' })

  type RoleDto = Api.TenantRole.RoleDto
  type TenantDto = Api.Tenant.TenantDto

  // 搜索表单
  const searchForm = ref({
    keyword: '' as string
  })

  const showSearchBar = ref(false)

  const dialogVisible = ref(false)
  const permissionDialog = ref(false)
  const currentRoleData = ref<RoleDto | undefined>(undefined)
  const dialogType = ref<'add' | 'edit' | 'copy'>('add')

  // 租户列表
  const tenantList = ref<TenantDto[]>([])
  const currentTenantId = ref<string | number | undefined>(undefined)

  // 1. 获取租户列表并默认选中第一个租户
  const getTenantList = async () => {
    try {
      // 获取租户列表，尝试获取较多数据以填充下拉框
      const res = await fetchGetTenantList({ Page: 1, PageSize: 100 })

      // 处理可能的响应结构（分页对象或数组）
      if (res && typeof res === 'object' && 'items' in res && Array.isArray((res as any).items)) {
        tenantList.value = (res as Api.Tenant.TenantDto[] | any).items
      } else if (Array.isArray(res)) {
        tenantList.value = res
      } else {
        tenantList.value = []
      }

      if (tenantList.value.length > 0) {
        currentTenantId.value = tenantList.value[0].id
        // 1. 选中租户后立即刷新角色列表
        refreshData()
      }
    } catch (error) {
      console.error('获取租户列表失败:', error)
    }
  }

  onMounted(() => {
    getTenantList()
  })

  const {
    columns,
    columnChecks,
    loading,
    pagination,
    data,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: async (params) => {
        // 1. 未选择租户时直接返回空数据，避免错误请求
        if (!currentTenantId.value) {
          return { data: { list: [], total: 0 } }
        }

        // 2. 调用实例层租户角色接口并处理分页参数
        const keyword = searchForm.value.keyword?.trim()
        const res = await fetchGetTenantRoles(currentTenantId.value, {
          ...params,
          Keyword: keyword || undefined,
          Page: params.current,
          PageSize: params.size
        })

        return {
          data: {
            list: res?.items || [],
            total: res?.totalCount || 0
          }
        }
      },
      apiParams: {},
      immediate: false,
      columnsFactory: () => [
        {
          prop: 'code',
          label: '角色编码',
          minWidth: 150
        },
        {
          prop: 'name',
          label: '角色名称',
          minWidth: 150
        },
        {
          prop: 'description',
          label: '描述',
          minWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'operation',
          label: '操作',
          width: 400,
          fixed: 'right',
          slotName: 'operation',
          useSlot: true
        }
      ]
    }
  })

  // 2. 监听租户切换后重置分页并刷新列表
  watch(
    () => currentTenantId.value,
    (newTenantId) => {
      if (!newTenantId) return
      // 1. 租户切换后重置列表
      refreshData()
    }
  )

  const handleAction = async (key: string, row: RoleDto) => {
    currentRoleData.value = row
    if (key === 'edit') {
      dialogType.value = 'edit'
      dialogVisible.value = true
    } else if (key === 'permission') {
      permissionDialog.value = true
    } else if (key === 'clone') {
      dialogType.value = 'copy'
      dialogVisible.value = true
    } else if (key === 'delete') {
      try {
        await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
        if (currentTenantId.value) {
          await fetchDeleteTenantRole(currentTenantId.value, row.id)
          ElMessage.success('删除成功')
          refreshData()
        }
      } catch {
        // cancel
      }
    }
  }

  const showDialog = (type: 'add' | 'edit' | 'copy') => {
    dialogType.value = type
    currentRoleData.value = undefined
    dialogVisible.value = true
  }

  const handleSearch = () => {
    refreshData()
  }

  const resetSearchParams = () => {
    searchForm.value.keyword = ''
    refreshData()
  }
</script>

<style scoped>
  .action-wrap {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
  }
</style>
