<script setup lang="ts">
import { useRoleManageStore } from '@/stores/role-manage'
import type { RoleRecord, RouteOverride } from '@/stores/role-manage'
import { useRouteGroupStore } from '@/stores/route-group'
import type { RouteRecord } from '@/stores/route-group'

const props = defineProps<{
  open: boolean
  role: RoleRecord | null
}>()

const emit = defineEmits<{
  'update:open': [value: boolean]
  saved: []
}>()

const roleStore = useRoleManageStore()
const groupStore = useRouteGroupStore()

// 状态
const activeTab = ref('groups')
const loadingData = ref(false)
const savingGroups = ref(false)
const savingOverrides = ref(false)

// Tab 1: 路由组授权
const checkedGroupIds = ref<number[]>([])

// Tab 2: 单条路由覆盖
const overrides = ref<RouteOverride[]>([])
const allRoutes = ref<RouteRecord[]>([])
const addingRouteId = ref<number | null>(null)

// method 颜色映射
const methodColorMap: Record<string, string> = {
  GET: 'green',
  POST: 'blue',
  PUT: 'orange',
  DELETE: 'red',
  PATCH: 'cyan',
}

const overrideColumns = [
  { title: '方法', key: 'method', width: 80 },
  { title: '路径', dataIndex: 'path', key: 'path' },
  { title: '允许', key: 'allowed', width: 80 },
  { title: '操作', key: 'action', width: 80 },
]

// 可添加为覆盖的路由（排除已添加的）
const availableRoutes = computed(() => {
  const existingIds = new Set(overrides.value.map((o) => o.route_id))
  return allRoutes.value.filter((r) => !existingIds.has(r.id))
})

const routeSelectOptions = computed(() =>
  availableRoutes.value.map((r) => ({
    value: r.id,
    label: `${r.method} ${r.path}`,
  })),
)

function handleClose() {
  emit('update:open', false)
}

function resetState() {
  activeTab.value = 'groups'
  checkedGroupIds.value = []
  overrides.value = []
  allRoutes.value = []
  addingRouteId.value = null
}

async function loadData() {
  if (!props.role) return
  loadingData.value = true
  try {
    const [groupIds, roleOverrides, , ] = await Promise.allSettled([
      roleStore.fetchRoleRouteGroups(props.role.id),
      roleStore.fetchRoleOverrides(props.role.id),
      groupStore.fetchGroups(),
      groupStore.fetchRoutes(),
    ])
    checkedGroupIds.value = groupIds.status === 'fulfilled' ? groupIds.value : []
    overrides.value = roleOverrides.status === 'fulfilled' ? roleOverrides.value : []
    allRoutes.value = groupStore.routes
  } finally {
    loadingData.value = false
  }
}

async function saveGroups() {
  if (!props.role) return
  savingGroups.value = true
  try {
    await roleStore.setRoleRouteGroups(props.role.id, checkedGroupIds.value)
    message.success('路由组授权保存成功')
    emit('saved')
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '保存失败'
    message.error(msg)
  } finally {
    savingGroups.value = false
  }
}

function addOverride() {
  if (addingRouteId.value === null) return
  const route = allRoutes.value.find((r) => r.id === addingRouteId.value)
  if (!route) return
  overrides.value.push({
    route_id: route.id,
    method: route.method,
    path: route.path,
    allowed: true,
  })
  addingRouteId.value = null
}

function removeOverride(index: number) {
  overrides.value.splice(index, 1)
}

async function saveOverrides() {
  if (!props.role) return
  savingOverrides.value = true
  try {
    await roleStore.setRoleOverrides(props.role.id, overrides.value)
    message.success('路由覆盖保存成功')
    emit('saved')
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '保存失败'
    message.error(msg)
  } finally {
    savingOverrides.value = false
  }
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      loadData()
    } else {
      resetState()
    }
  },
  { immediate: true },
)
</script>

<template>
  <a-modal
    :open="open"
    :title="`配置权限 - ${role?.label || role?.name || ''}`"
    width="720px"
    :footer="null"
    @cancel="handleClose"
  >
    <a-spin :spinning="loadingData">
      <a-tabs v-model:activeKey="activeTab">
        <!-- Tab 1: 路由组授权 -->
        <a-tab-pane key="groups" tab="路由组授权">
          <a-checkbox-group v-model:value="checkedGroupIds" class="w-full">
            <a-row :gutter="[8, 8]">
              <a-col v-for="group in groupStore.groups" :key="group.id" :span="8">
                <a-checkbox :value="group.id">
                  {{ group.label || group.name }}
                  <span class="text-gray-400 text-xs">({{ group.route_count }} 条路由)</span>
                </a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
          <div class="mt-4 text-right">
            <a-button type="primary" :loading="savingGroups" @click="saveGroups">
              保存组授权
            </a-button>
          </div>
        </a-tab-pane>

        <!-- Tab 2: 单条路由覆盖 -->
        <a-tab-pane key="overrides" tab="单条路由覆盖">
          <div class="mb-3 flex gap-2">
            <a-select
              :value="addingRouteId ?? undefined"
              :options="routeSelectOptions"
              placeholder="选择路由添加覆盖"
              show-search
              :filter-option="(input: string, option: unknown) =>
                ((option as { label: string }).label ?? '').toLowerCase().includes(input.toLowerCase())
              "
              style="flex: 1"
              allow-clear
              @change="(val: unknown) => { addingRouteId = (val as number) ?? null }"
            />
            <a-button type="primary" :disabled="addingRouteId === null" @click="addOverride">
              添加覆盖
            </a-button>
          </div>
          <a-table
            :columns="overrideColumns"
            :data-source="overrides"
            :pagination="false"
            row-key="route_id"
            size="small"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'method'">
                <a-tag :color="methodColorMap[record.method] || 'default'">
                  {{ record.method }}
                </a-tag>
              </template>
              <template v-if="column.key === 'allowed'">
                <a-switch v-model:checked="record.allowed" size="small" />
              </template>
              <template v-if="column.key === 'action'">
                <a-button type="link" size="small" danger @click="removeOverride(index)">
                  移除
                </a-button>
              </template>
            </template>
          </a-table>
          <div class="mt-4 text-right">
            <a-button type="primary" :loading="savingOverrides" @click="saveOverrides">
              保存覆盖
            </a-button>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </a-modal>
</template>
