<template>
  <div class="page-container guides-view">
    <div class="page-header">
      <div>
        <h2>办事指南</h2>
        <p>直接查看标准办事指南的结构化信息，快速核对材料、收费、时限、窗口与咨询方式。</p>
      </div>
      <a-space wrap>
        <a-button v-if="matterScoped" @click="clearMatterScope">清除事项限定</a-button>
        <a-button type="primary" @click="handleSearch" :disabled="matterScoped">搜索指南</a-button>
      </a-space>
    </div>

    <a-alert
      v-if="matterScoped"
      class="scope-alert"
      type="info"
      show-icon
      :message="`当前正在查看事项“${matterScopeName || matterScopeId}”的关联办事指南`"
      description="如需进行全局筛选，请先清除事项限定。"
    >
      <template #action>
        <a-button size="small" @click="clearMatterScope">切换到全局检索</a-button>
      </template>
    </a-alert>

    <a-card class="filter-card">
      <a-row :gutter="[16, 16]">
        <a-col :xs="24" :md="12" :xl="8">
          <a-input-search
            v-model:value="filters.query"
            placeholder="关键词，如：护照、加注、快递领取"
            enter-button="搜索"
            :disabled="matterScoped"
            @search="handleSearch"
          />
        </a-col>
        <a-col :xs="24" :md="12" :xl="8">
          <a-input
            v-model:value="filters.matter_name"
            placeholder="事项名称（精确匹配）"
            :disabled="matterScoped"
          />
        </a-col>
        <a-col :xs="24" :md="12" :xl="8">
          <a-input
            v-model:value="filters.implementation_code"
            placeholder="实施编码"
            :disabled="matterScoped"
          />
        </a-col>
        <a-col :xs="24" :md="12" :xl="8">
          <a-input
            v-model:value="filters.basic_code"
            placeholder="基本编码"
            :disabled="matterScoped"
          />
        </a-col>
        <a-col :xs="24" :md="12" :xl="8">
          <a-input
            v-model:value="filters.matter_type"
            placeholder="事项类型，如：行政许可"
            :disabled="matterScoped"
          />
        </a-col>
        <a-col :xs="24" :md="12" :xl="8">
          <a-input
            v-model:value="filters.handled_org"
            placeholder="办理机构，如：广州市公安局"
            :disabled="matterScoped"
          />
        </a-col>
        <a-col :xs="24" :md="12" :xl="8">
          <a-input
            v-model:value="filters.region"
            placeholder="地区，如：广州市"
            :disabled="matterScoped"
          />
        </a-col>
        <a-col :xs="24" :md="12" :xl="8">
          <a-select v-model:value="filters.express_supported" :options="booleanFilterOptions" :disabled="matterScoped" />
        </a-col>
        <a-col :xs="24" :md="12" :xl="8">
          <a-select v-model:value="filters.reservation_supported" :options="reservationFilterOptions" :disabled="matterScoped" />
        </a-col>
        <a-col :xs="24" :md="12" :xl="8">
          <a-select v-model:value="filters.must_onsite" :options="onsiteFilterOptions" :disabled="matterScoped" />
        </a-col>
      </a-row>

      <div class="filter-actions">
        <a-space wrap>
          <a-button type="primary" @click="handleSearch" :disabled="matterScoped">应用筛选</a-button>
          <a-button @click="resetFilters" :disabled="matterScoped">重置筛选</a-button>
        </a-space>
      </div>
    </a-card>

    <div class="result-header">
      <span>共找到 <strong>{{ total }}</strong> 条办事指南</span>
      <a-space wrap>
        <a-tag v-if="matterScoped" color="gold">事项关联模式</a-tag>
        <a-tag v-if="filters.express_supported === 'true'" color="green">支持快递</a-tag>
        <a-tag v-if="filters.reservation_supported === 'true'" color="blue">支持预约</a-tag>
        <a-tag v-if="filters.must_onsite === 'true'" color="orange">必须现场</a-tag>
      </a-space>
    </div>

    <a-card class="results-card" :loading="loading">
      <a-empty v-if="!loading && items.length === 0" description="当前条件下未找到办事指南" />

      <a-list v-else :data-source="items" item-layout="vertical">
        <template #renderItem="{ item }">
          <a-list-item class="guide-list-item" @click="goToGuide(item.profile_id)">
            <template #actions>
              <a @click.stop="goToGuide(item.profile_id)">查看结构化详情</a>
              <a @click.stop="goToDocument(item.doc_id)">查看原文</a>
              <a @click.stop="askAboutGuide(item)">问这个指南</a>
            </template>
            <a-list-item-meta>
              <template #title>
                <div class="guide-title-row">
                  <div class="guide-title-main">
                    <span>{{ item.matter_name }}</span>
                    <a-tag v-if="item.needs_review" color="orange">待复核</a-tag>
                  </div>
                  <a-space wrap>
                    <a-tag v-if="item.implementation_code">实施编码 {{ item.implementation_code }}</a-tag>
                    <a-tag v-if="item.matter_version">版本 {{ item.matter_version }}</a-tag>
                  </a-space>
                </div>
              </template>
              <template #description>
                <div class="guide-meta">
                  <div>办理机构：{{ joinValues(item.handled_org_names) || '—' }}</div>
                  <div>适用地区：{{ joinValues(item.region_names) || '—' }}</div>
                  <div v-if="item.colloquial_names.length" class="guide-aliases">
                    <span>常用叫法：</span>
                    <a-tag v-for="alias in item.colloquial_names.slice(0, 4)" :key="alias">{{ alias }}</a-tag>
                  </div>
                  <div class="guide-feature-tags">
                    <a-tag v-if="item.express_supported === true" color="green">支持快递</a-tag>
                    <a-tag v-else-if="item.express_supported === false">不支持快递</a-tag>
                    <a-tag v-if="item.reservation_supported === true" color="blue">支持预约</a-tag>
                    <a-tag v-else-if="item.reservation_supported === false">不支持预约</a-tag>
                  </div>
                </div>
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>
    </a-card>

    <div class="result-pagination">
      <a-pagination
        :current="page"
        :total="total"
        :page-size="pageSize"
        show-quick-jumper
        show-size-changer
        @change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import { listServiceGuides, listServiceGuidesByMatter } from '@/api/serviceGuide'
import type {
  GuideBooleanFilter,
  ServiceGuideListItem,
} from '@/types/service-guide'

type GuideListFilters = {
  query: string
  matter_name: string
  implementation_code: string
  basic_code: string
  matter_type: string
  handled_org: string
  region: string
  express_supported: GuideBooleanFilter
  reservation_supported: GuideBooleanFilter
  must_onsite: GuideBooleanFilter
}

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const items = ref<ServiceGuideListItem[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const matterScopeId = ref('')
const matterScopeName = ref('')
const filters = reactive<GuideListFilters>(createDefaultFilters())

const matterScoped = computed(() => !!matterScopeId.value)

const booleanFilterOptions = [
  { label: '快递支持：不限', value: 'all' },
  { label: '快递支持：是', value: 'true' },
  { label: '快递支持：否', value: 'false' },
]

const reservationFilterOptions = [
  { label: '预约办理：不限', value: 'all' },
  { label: '预约办理：是', value: 'true' },
  { label: '预约办理：否', value: 'false' },
]

const onsiteFilterOptions = [
  { label: '现场办理：不限', value: 'all' },
  { label: '现场办理：必须', value: 'true' },
  { label: '现场办理：非必须', value: 'false' },
]

watch(
  () => route.query,
  async () => {
    syncStateFromRoute()
    await loadGuides()
  },
  { immediate: true },
)

function createDefaultFilters(): GuideListFilters {
  return {
    query: '',
    matter_name: '',
    implementation_code: '',
    basic_code: '',
    matter_type: '',
    handled_org: '',
    region: '',
    express_supported: 'all',
    reservation_supported: 'all',
    must_onsite: 'all',
  }
}

function normalizeRouteValue(value: unknown): string {
  if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : ''
  return typeof value === 'string' ? value : ''
}

function parsePositiveInt(value: unknown, fallback: number): number {
  const parsed = Number(normalizeRouteValue(value))
  return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback
}

function parseTriState(value: unknown): GuideBooleanFilter {
  const normalized = normalizeRouteValue(value)
  return normalized === 'true' || normalized === 'false' ? normalized : 'all'
}

function triStateToBoolean(value: GuideBooleanFilter): boolean | undefined {
  if (value === 'true') return true
  if (value === 'false') return false
  return undefined
}

function syncStateFromRoute() {
  filters.query = normalizeRouteValue(route.query.query) || normalizeRouteValue(route.query.q)
  filters.matter_name = normalizeRouteValue(route.query.matter_name)
  filters.implementation_code = normalizeRouteValue(route.query.implementation_code)
  filters.basic_code = normalizeRouteValue(route.query.basic_code)
  filters.matter_type = normalizeRouteValue(route.query.matter_type)
  filters.handled_org = normalizeRouteValue(route.query.handled_org)
  filters.region = normalizeRouteValue(route.query.region)
  filters.express_supported = parseTriState(route.query.express_supported)
  filters.reservation_supported = parseTriState(route.query.reservation_supported)
  filters.must_onsite = parseTriState(route.query.must_onsite)
  matterScopeId.value = normalizeRouteValue(route.query.matterId)
  matterScopeName.value = normalizeRouteValue(route.query.matterName)
  page.value = parsePositiveInt(route.query.page, 1)
  pageSize.value = parsePositiveInt(route.query.pageSize ?? route.query.page_size, 10)
}

function buildRouteQuery(nextPage = 1, nextPageSize = pageSize.value): Record<string, string> {
  const query: Record<string, string> = {
    page: String(nextPage),
    pageSize: String(nextPageSize),
  }

  if (matterScopeId.value) {
    query.matterId = matterScopeId.value
    if (matterScopeName.value) query.matterName = matterScopeName.value
    return query
  }

  if (filters.query.trim()) query.query = filters.query.trim()
  if (filters.matter_name.trim()) query.matter_name = filters.matter_name.trim()
  if (filters.implementation_code.trim()) query.implementation_code = filters.implementation_code.trim()
  if (filters.basic_code.trim()) query.basic_code = filters.basic_code.trim()
  if (filters.matter_type.trim()) query.matter_type = filters.matter_type.trim()
  if (filters.handled_org.trim()) query.handled_org = filters.handled_org.trim()
  if (filters.region.trim()) query.region = filters.region.trim()
  if (filters.express_supported !== 'all') query.express_supported = filters.express_supported
  if (filters.reservation_supported !== 'all') query.reservation_supported = filters.reservation_supported
  if (filters.must_onsite !== 'all') query.must_onsite = filters.must_onsite
  return query
}

async function loadGuides() {
  loading.value = true
  try {
    const response = matterScopeId.value
      ? await listServiceGuidesByMatter(matterScopeId.value, page.value, pageSize.value)
      : await listServiceGuides({
          query: filters.query || undefined,
          matter_name: filters.matter_name || undefined,
          implementation_code: filters.implementation_code || undefined,
          basic_code: filters.basic_code || undefined,
          matter_type: filters.matter_type || undefined,
          handled_org: filters.handled_org || undefined,
          region: filters.region || undefined,
          express_supported: triStateToBoolean(filters.express_supported),
          reservation_supported: triStateToBoolean(filters.reservation_supported),
          must_onsite: triStateToBoolean(filters.must_onsite),
          page: page.value,
          page_size: pageSize.value,
        })

    items.value = response.items
    total.value = response.total
  } catch (error) {
    console.error('Failed to load service guides:', error)
    items.value = []
    total.value = 0
    message.error('办事指南加载失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  router.replace({ path: '/guides', query: buildRouteQuery(1, pageSize.value) })
}

function handlePageChange(nextPage: number, nextPageSize: number) {
  router.replace({ path: route.path, query: buildRouteQuery(nextPage, nextPageSize) })
}

function resetFilters() {
  Object.assign(filters, createDefaultFilters())
  router.replace({ path: '/guides', query: { page: '1', pageSize: String(pageSize.value) } })
}

function clearMatterScope() {
  router.replace({ path: '/guides', query: {} })
}

function joinValues(values: string[]): string {
  return values.filter(Boolean).join('、')
}

function goToGuide(profileId: string) {
  router.push(`/guides/${profileId}`)
}

function goToDocument(docId: string) {
  router.push(`/doc/${docId}`)
}

function askAboutGuide(item: ServiceGuideListItem) {
  router.push({
    path: '/qa',
    query: {
      launchKey: String(Date.now()),
      kind: 'guide',
      guideId: item.profile_id,
      docId: item.doc_id,
      title: item.matter_name,
      prompt: `请基于办事指南“${item.matter_name}”梳理办理条件、申请材料、收费标准、办理时限和窗口信息。`,
    },
  })
}
</script>

<style scoped lang="less">
.guides-view {
  .page-header {
    display: flex;
    justify-content: space-between;
    gap: 16px;
    align-items: flex-start;
    margin-bottom: 16px;
    flex-wrap: wrap;

    h2 {
      margin-bottom: 4px;
    }

    p {
      color: #8c8c8c;
      margin-bottom: 0;
    }
  }

  .scope-alert {
    margin-bottom: 16px;
  }

  .filter-card {
    margin-bottom: 16px;
  }

  .filter-actions {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .result-header {
    display: flex;
    justify-content: space-between;
    gap: 12px;
    align-items: center;
    margin-bottom: 12px;
    flex-wrap: wrap;
  }

  .guide-list-item {
    cursor: pointer;
    border-radius: 10px;
    transition: background 0.2s ease;
    padding-left: 8px;
    padding-right: 8px;

    &:hover {
      background: #fafafa;
    }
  }

  .guide-title-row {
    display: flex;
    justify-content: space-between;
    gap: 16px;
    align-items: flex-start;
    width: 100%;
  }

  .guide-title-main {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: wrap;
  }

  .guide-meta {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .guide-aliases,
  .guide-feature-tags {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    align-items: center;
  }

  .result-pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>