<template>
  <div class="app-container">
    <a-form
      :model="queryParams"
      layout="inline"
      class="search-form"
      v-show="showSearch"
    >
      <a-form-item label="角色名称" name="roleName">
        <a-input
          v-model:value="queryParams.roleName"
          placeholder="请输入角色名称"
          allow-clear
          style="width: 240px"
          @press-enter="handleQuery"
        />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="handleQuery">
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
          <a-button @click="resetQuery">
            <template #icon><RedoOutlined /></template>
            重置
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <a-table
      v-if="checkType === 'multiple'"
      ref="dataTable"
      :loading="loading"
      :dataSource="roleList"
      :rowKey="record => record.roleId"
      :rowSelection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
        type: 'checkbox'
      }"
      :pagination="false"
    >
      <a-table-column key="roleId" title="角色编号" data-index="roleId" width="120" />
      <a-table-column key="roleName" title="角色名称" data-index="roleName" ellipsis width="150" />
      <a-table-column key="roleKey" title="权限字符" data-index="roleKey" ellipsis width="150" />
      <a-table-column key="roleSort" title="显示顺序" data-index="roleSort" width="100" />
      <a-table-column key="createTime" title="创建时间" align="center" width="180">
        <template #bodyCell="{ record }">
          <span>{{ parseTime(record.createTime) }}</span>
        </template>
      </a-table-column>
    </a-table>

    <a-table
      v-if="checkType === 'single'"
      :loading="loading"
      :dataSource="roleList"
      :rowKey="record => record.roleId"
      :pagination="false"
      @rowClick="handleSingleRoleSelect"
    >
      <a-table-column key="selection" width="55" align="center">
        <template #bodyCell="{ record }">
          <a-radio 
            v-model:checked="radioSelected" 
            :value="record.roleId"
            @change="() => handleSingleRoleSelect(record)"
          ></a-radio>
        </template>
      </a-table-column>
      <a-table-column key="roleId" title="角色编号" data-index="roleId" width="120" />
      <a-table-column key="roleName" title="角色名称" data-index="roleName" ellipsis width="150" />
      <a-table-column key="roleKey" title="权限字符" data-index="roleKey" ellipsis width="150" />
      <a-table-column key="roleSort" title="显示顺序" data-index="roleSort" width="100" />
      <a-table-column key="createTime" title="创建时间" align="center" width="180">
        <template #bodyCell="{ record }">
          <span>{{ parseTime(record.createTime) }}</span>
        </template>
      </a-table-column>
    </a-table>

    <div class="pagination-container">
      <a-pagination
        v-show="total > 0"
        v-model:current="queryParams.pageNum"
        v-model:pageSize="queryParams.pageSize"
        :total="total"
        :pageSizeOptions="['5', '10']"
        show-less-items
        show-size-changer
        @change="getList"
        @showSizeChange="getList"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { SearchOutlined, RedoOutlined } from '@ant-design/icons-vue'
import { listRole } from "@/api/system/role"
import { StrUtil } from "../../common/StrUtil"
import type { TableProps } from 'ant-design-vue'

interface RoleItem {
  roleId: number
  roleName: string
  roleKey: string
  roleSort: number
  createTime: string
}

interface QueryParams {
  pageNum: number
  pageSize: number
  roleName?: string
  roleKey?: string
  status?: string
}

interface Props {
  selectValues?: number | string | number[] | string[]
  checkType?: 'single' | 'multiple'
}

const props = withDefaults(defineProps<Props>(), {
  selectValues: null,
  checkType: 'multiple'
})

const emit = defineEmits<{
  (e: 'handleRoleSelect', ids: string, names: string): void
}>()

// 响应式数据
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const roleList = ref<RoleItem[]>([])
const radioSelected = ref<number | string | null>(null)
const selectedRowKeys = ref<(number | string)[]>([])
const dataTable = ref()

// 查询参数
const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 5,
  roleName: undefined,
  roleKey: undefined,
  status: undefined
})

// 时间格式化函数（需要根据实际项目中的实现调整）
const parseTime = (time: string) => {
  return new Date(time).toLocaleString()
}

// 监听selectValues变化
watch(() => props.selectValues, (newVal) => {
  if (StrUtil.isNotBlank(newVal)) {
    if (typeof newVal === 'number' || typeof newVal === 'string') {
      radioSelected.value = newVal
    } else if (Array.isArray(newVal)) {
      selectedRowKeys.value = newVal
    }
  }
}, { immediate: true })

// 监听roleList变化（多选模式下的回显）
watch(roleList, (newVal) => {
  if (props.checkType === 'multiple' && selectedRowKeys.value.length > 0 && newVal.length > 0) {
    nextTick(() => {
      // Ant Design Table 会自动处理选中状态，只需要设置 selectedRowKeys
    })
  }
})

// 生命周期
onMounted(() => {
  getList()
})

// 多选选择变化
const onSelectChange: TableProps['rowSelection']['onChange'] = (selectedKeys) => {
  selectedRowKeys.value = selectedKeys as (number | string)[]
  const selectedRows = roleList.value.filter(item => selectedKeys.includes(item.roleId))
  const idList = selectedRows.map(item => item.roleId)
  const nameList = selectedRows.map(item => item.roleName)
  emit('handleRoleSelect', idList.join(','), nameList.join(','))
}

/** 查询角色列表 */
const getList = async () => {
  try {
    loading.value = true
    const response = await listRole(queryParams)
    roleList.value = response.rows
    total.value = response.total
  } catch (error) {
    console.error('获取角色列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 单选框选中数据
const handleSingleRoleSelect = (record: RoleItem) => {
  radioSelected.value = record.roleId
  emit('handleRoleSelect', record.roleId.toString(), record.roleName)
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 5,
    roleName: undefined,
    roleKey: undefined,
    status: undefined
  })
  handleQuery()
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.search-form :deep(.ant-form-item) {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.ant-table-row) {
  cursor: pointer;
}

:deep(.ant-table-row:hover) {
  background-color: #f5f5f5;
}

/* 隐藏radio的label */
:deep(.ant-radio-wrapper) {
  margin-right: 0;
}

:deep(.ant-radio-wrapper .ant-radio + span) {
  display: none;
}
</style>