<template>
  <div class="page-container guide-detail-view">
    <a-spin :spinning="loading">
      <template v-if="guide && profile">
        <div class="detail-header">
          <div class="detail-header__main">
            <a-button type="text" @click="goBack">返回办事指南</a-button>
            <h1>{{ profile.matter_name || guide.profile_id }}</h1>
            <div class="header-tags">
              <a-tag v-if="profile.implementation_code" color="blue">实施编码 {{ profile.implementation_code }}</a-tag>
              <a-tag v-if="profile.basic_code" color="purple">基本编码 {{ profile.basic_code }}</a-tag>
              <a-tag v-if="profile.matter_type">{{ profile.matter_type }}</a-tag>
              <a-tag v-if="qualityNeedsReview" color="orange">待复核</a-tag>
              <a-tag v-for="alias in profile.colloquial_names.slice(0, 4)" :key="alias">{{ alias }}</a-tag>
            </div>
          </div>

          <a-space wrap>
            <a-button type="primary" @click="askAboutGuide">问这个指南</a-button>
            <a-button @click="goToDocument(profile.doc_id)">查看原文</a-button>
            <a-button :disabled="!primaryMatterId" @click="goToMatter(primaryMatterId)">查看关联事项</a-button>
          </a-space>
        </div>

        <a-row :gutter="24">
          <a-col :xs="24" :xl="16">
            <a-card title="基本信息" class="section-card">
              <a-descriptions :column="2" bordered size="small">
                <a-descriptions-item label="事项名称">{{ profile.matter_name || '—' }}</a-descriptions-item>
                <a-descriptions-item label="事项类型">{{ displayMatterType }}</a-descriptions-item>
                <a-descriptions-item label="办理对象">{{ displayServiceObjects }}</a-descriptions-item>
                <a-descriptions-item label="办理机构">{{ displayHandledOrgs }}</a-descriptions-item>
                <a-descriptions-item label="适用地区">{{ displayRegions }}</a-descriptions-item>
                <a-descriptions-item label="办理方式">{{ displayServiceModes }}</a-descriptions-item>
                <a-descriptions-item label="承诺时限">{{ promisedTimeLimitText }}</a-descriptions-item>
                <a-descriptions-item label="法定时限">{{ legalTimeLimitText }}</a-descriptions-item>
                <a-descriptions-item label="预约办理">{{ yesNoText(reservationSupported) }}</a-descriptions-item>
                <a-descriptions-item label="快递办理">{{ yesNoText(expressSupported) }}</a-descriptions-item>
                <a-descriptions-item label="必须现场">{{ yesNoText(mustOnsite) }}</a-descriptions-item>
                <a-descriptions-item label="跑动次数">{{ visitCountText }}</a-descriptions-item>
              </a-descriptions>

              <a-alert
                v-if="mustOnsiteReason"
                class="inline-alert"
                type="warning"
                show-icon
                message="必须现场办理原因"
                :description="mustOnsiteReason"
              />
            </a-card>

            <a-card title="申请材料" class="section-card">
              <a-empty v-if="materialRows.length === 0" description="暂无结构化材料信息" />
              <a-table
                v-else
                size="small"
                :pagination="false"
                :columns="materialColumns"
                :data-source="materialRows"
                row-key="key"
                :scroll="{ x: 960 }"
              />
            </a-card>

            <a-card title="收费信息" class="section-card">
              <a-empty v-if="feeRows.length === 0" description="暂无结构化收费信息" />
              <a-table
                v-else
                size="small"
                :pagination="false"
                :columns="feeColumns"
                :data-source="feeRows"
                row-key="key"
                :scroll="{ x: 800 }"
              />
            </a-card>

            <a-card title="办理流程" class="section-card">
              <div v-if="profile.process_info.summary" class="process-summary">
                {{ profile.process_info.summary }}
              </div>
              <a-steps
                v-if="processSteps.length"
                direction="vertical"
                size="small"
                :current="processSteps.length - 1"
              >
                <a-step v-for="(step, index) in processSteps" :key="`${index}-${step}`" :title="step" />
              </a-steps>
              <a-empty v-else description="暂无结构化流程步骤" />
            </a-card>

            <a-card title="服务窗口" class="section-card">
              <a-empty v-if="windowRows.length === 0" description="暂无窗口信息" />
              <a-table
                v-else
                size="small"
                :pagination="false"
                :columns="windowColumns"
                :data-source="windowRows"
                row-key="key"
                :scroll="{ x: 900 }"
              />
            </a-card>

            <a-card title="法律依据" class="section-card">
              <a-empty v-if="legalBasisRows.length === 0" description="暂无法律依据" />
              <a-table
                v-else
                size="small"
                :pagination="false"
                :columns="legalBasisColumns"
                :data-source="legalBasisRows"
                row-key="key"
                :scroll="{ x: 820 }"
              />
            </a-card>
          </a-col>

          <a-col :xs="24" :xl="8">
            <a-card title="指南摘要" size="small" class="section-card section-card--compact">
              <a-descriptions :column="1" size="small" bordered>
                <a-descriptions-item label="文档 ID">{{ profile.doc_id || guide.doc_id || '—' }}</a-descriptions-item>
                <a-descriptions-item label="指南版本">{{ guide.guide_version || profile.guide_version || '—' }}</a-descriptions-item>
                <a-descriptions-item label="来源标题">{{ profile.document_info.title || '—' }}</a-descriptions-item>
                <a-descriptions-item label="发文机关">{{ profile.document_info.issuing_org || profile.implementing_subject || '—' }}</a-descriptions-item>
                <a-descriptions-item label="更新时间">{{ profile.updated_at || '—' }}</a-descriptions-item>
                <a-descriptions-item label="跨地区办理">{{ displayCrossRegion }}</a-descriptions-item>
              </a-descriptions>
            </a-card>

            <a-card title="咨询与监督" size="small" class="section-card section-card--compact">
              <div class="side-section">
                <div class="side-section__title">咨询电话</div>
                <div v-if="profile.consultation_and_supervision.consultation_phones.length" class="tag-list">
                  <a-tag v-for="phone in profile.consultation_and_supervision.consultation_phones" :key="phone">{{ phone }}</a-tag>
                </div>
                <span v-else>—</span>
              </div>

              <div class="side-section">
                <div class="side-section__title">投诉电话</div>
                <div v-if="profile.consultation_and_supervision.complaint_phones.length" class="tag-list">
                  <a-tag v-for="phone in profile.consultation_and_supervision.complaint_phones" :key="phone" color="orange">{{ phone }}</a-tag>
                </div>
                <span v-else>—</span>
              </div>

              <div class="side-section">
                <div class="side-section__title">在线咨询</div>
                <div v-if="profile.consultation_and_supervision.consultation_urls.length" class="link-list">
                  <a v-for="url in profile.consultation_and_supervision.consultation_urls" :key="url" :href="url" target="_blank" rel="noreferrer">{{ url }}</a>
                </div>
                <span v-else>—</span>
              </div>
            </a-card>

            <a-card v-if="crossRegionItems.length" title="跨区域办理" size="small" class="section-card section-card--compact">
              <div v-for="item in crossRegionItems" :key="item.key" class="side-section">
                <div class="side-section__title">{{ item.scope || '跨区域范围' }}</div>
                <div>{{ item.regions || '—' }}</div>
                <div v-if="item.serviceModes" class="subtle-text">办理方式：{{ item.serviceModes }}</div>
                <div v-if="item.notes" class="subtle-text">备注：{{ item.notes }}</div>
              </div>
            </a-card>

            <a-card title="质量提示" size="small" class="section-card section-card--compact">
              <a-space direction="vertical" style="width: 100%">
                <a-progress :percent="completenessPercent" size="small" status="active">
                  <template #format="percent">完整度 {{ percent }}%</template>
                </a-progress>
                <a-progress :percent="confidencePercent" size="small" stroke-color="#1677ff">
                  <template #format="percent">置信度 {{ percent }}%</template>
                </a-progress>
              </a-space>

              <a-alert
                v-if="qualityNeedsReview"
                class="inline-alert"
                type="warning"
                show-icon
                message="当前指南建议人工复核"
              />

              <div v-if="qualityMessages.length" class="quality-list">
                <div v-for="messageItem in qualityMessages" :key="messageItem" class="quality-list__item">
                  {{ messageItem }}
                </div>
              </div>
              <a-empty v-else description="当前无额外质量提示" />
            </a-card>
          </a-col>
        </a-row>
      </template>

      <a-result
        v-else-if="!loading"
        status="404"
        title="办事指南未找到"
        sub-title="请检查指南 ID 或文档 ID 是否正确。"
      >
        <template #extra>
          <a-space wrap>
            <a-button type="primary" @click="router.push('/guides')">返回办事指南</a-button>
            <a-button v-if="docIdFromRoute" @click="goToDocument(docIdFromRoute)">查看原文</a-button>
          </a-space>
        </template>
      </a-result>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import { getServiceGuideByDoc, getServiceGuideDetail } from '@/api/serviceGuide'
import type {
  ServiceGuideDetailResponse,
  StandardServiceGuideProfile,
} from '@/types/service-guide'

type TableColumn = {
  title: string
  dataIndex: string
  key: string
  width?: number
  ellipsis?: boolean
}

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

const loading = ref(false)
const guide = ref<ServiceGuideDetailResponse | null>(null)

const materialColumns: TableColumn[] = [
  { title: '材料名称', dataIndex: 'material_name', key: 'material_name', width: 220, ellipsis: true },
  { title: '要求', dataIndex: 'requirement_level', key: 'requirement_level', width: 120 },
  { title: '份数', dataIndex: 'count_summary', key: 'count_summary', width: 120 },
  { title: '表单/规格', dataIndex: 'form_summary', key: 'form_summary', ellipsis: true },
  { title: '说明', dataIndex: 'notes', key: 'notes', ellipsis: true },
]

const feeColumns: TableColumn[] = [
  { title: '收费项目', dataIndex: 'fee_name', key: 'fee_name', width: 220, ellipsis: true },
  { title: '金额', dataIndex: 'amount_text', key: 'amount_text', width: 120 },
  { title: '收费主体', dataIndex: 'charging_body', key: 'charging_body', width: 180, ellipsis: true },
  { title: '收费方式', dataIndex: 'charging_method', key: 'charging_method', width: 140 },
  { title: '备注', dataIndex: 'notes', key: 'notes', ellipsis: true },
]

const windowColumns: TableColumn[] = [
  { title: '窗口名称', dataIndex: 'window_name', key: 'window_name', width: 180, ellipsis: true },
  { title: '办理地点', dataIndex: 'location', key: 'location', width: 260, ellipsis: true },
  { title: '联系电话', dataIndex: 'office_phone', key: 'office_phone', width: 140 },
  { title: '办公时间', dataIndex: 'office_hours', key: 'office_hours', width: 180, ellipsis: true },
  { title: '服务范围', dataIndex: 'scope', key: 'scope', ellipsis: true },
]

const legalBasisColumns: TableColumn[] = [
  { title: '法律依据', dataIndex: 'law_name', key: 'law_name', width: 220, ellipsis: true },
  { title: '条款', dataIndex: 'article_no', key: 'article_no', width: 120 },
  { title: '文号', dataIndex: 'document_no', key: 'document_no', width: 180, ellipsis: true },
  { title: '制定机关', dataIndex: 'issuing_body', key: 'issuing_body', width: 180, ellipsis: true },
  { title: '内容摘要', dataIndex: 'article_content', key: 'article_content', ellipsis: true },
]

const profile = computed<StandardServiceGuideProfile | null>(() => guide.value?.profile ?? null)
const docIdFromRoute = computed(() => String(route.params.docId || profile.value?.doc_id || ''))
const primaryMatterId = computed(
  () => profile.value?.linked_matter_ids?.[0] || profile.value?.bindings?.matter_ids?.[0] || '',
)

const displayMatterType = computed(
  () => profile.value?.matter_type || profile.value?.matter_identity?.matter_type || '—',
)
const displayServiceObjects = computed(() => {
  if (!profile.value) return '—'
  return joinValues(profile.value.service_objects.length ? profile.value.service_objects : profile.value.basic_info.service_object)
})
const displayHandledOrgs = computed(() => {
  if (!profile.value) return '—'
  return joinValues(profile.value.handled_org_names.length ? profile.value.handled_org_names : [profile.value.implementing_subject])
})
const displayRegions = computed(() => joinValues(profile.value?.region_names || []))
const displayServiceModes = computed(() => {
  if (!profile.value) return '—'
  return joinValues(profile.value.service_modes.length ? profile.value.service_modes : profile.value.basic_info.service_modes)
})
const promisedTimeLimitText = computed(() => {
  if (!profile.value) return '—'
  return formatTimeLimit(profile.value.basic_info.promised_time_limit, profile.value.promised_time_limit_days)
})
const legalTimeLimitText = computed(() => {
  if (!profile.value) return '—'
  return formatTimeLimit(profile.value.basic_info.legal_time_limit, profile.value.legal_time_limit_days)
})
const reservationSupported = computed(() => pickBoolean(profile.value?.reservation_supported, profile.value?.basic_info.reservation_supported))
const expressSupported = computed(() => pickBoolean(profile.value?.express_supported, profile.value?.basic_info.express_supported))
const mustOnsite = computed(() => pickBoolean(profile.value?.must_onsite, profile.value?.basic_info.must_onsite))
const mustOnsiteReason = computed(() => profile.value?.must_onsite_reason || profile.value?.basic_info.must_onsite_reason || '')
const visitCountText = computed(() => {
  const count = profile.value?.visit_count_to_hall ?? profile.value?.basic_info.visit_count_to_hall
  return count == null ? '—' : `${count} 次`
})
const displayCrossRegion = computed(() => joinValues(profile.value?.cross_region_summary || []))
const completenessPercent = computed(() => Math.round((profile.value?.quality?.completeness_score ?? profile.value?.completeness_score ?? 0) * 100))
const confidencePercent = computed(() => Math.round((profile.value?.quality?.confidence_score ?? profile.value?.confidence_score ?? 0) * 100))
const qualityNeedsReview = computed(() => Boolean(profile.value?.needs_review || profile.value?.quality?.needs_review))
const qualityMessages = computed(() => {
  if (!profile.value) return []
  const warnings = profile.value.quality?.warnings || []
  const missing = (profile.value.quality?.missing_fields || []).map((field) => `缺失字段：${field}`)
  return [...warnings, ...missing]
})

const materialRows = computed(() => (profile.value?.materials || []).map((item, index) => ({
  key: item.guide_material_id || `${index}`,
  material_name: item.material_name || '未命名材料',
  requirement_level: requirementLabel(item.requirement_level),
  count_summary: formatCounts(item.original_count, item.copy_count),
  form_summary: joinSegments([
    item.form_types.join('、'),
    item.paper_spec,
    item.download_hint,
  ]),
  notes: joinSegments([
    item.fill_instructions,
    item.notes,
    item.applicable_conditions.join('；'),
  ]),
})))

const feeRows = computed(() => (profile.value?.fees || []).map((item, index) => ({
  key: `${index}-${item.fee_name}`,
  fee_name: item.fee_name || '未命名收费项',
  amount_text: item.amount_text || (item.amount_value != null ? `${item.amount_value}` : '—'),
  charging_body: item.charging_body || '—',
  charging_method: item.charging_method || '—',
  notes: item.notes || '—',
})))

const windowRows = computed(() => (profile.value?.service_windows || []).map((item, index) => ({
  key: `${index}-${item.window_name}`,
  window_name: item.window_name || '综合窗口',
  location: item.location || '—',
  office_phone: item.office_phone || '—',
  office_hours: item.office_hours || '—',
  scope: item.scope || '—',
})))

const legalBasisRows = computed(() => (profile.value?.legal_basis || []).map((item, index) => ({
  key: `${index}-${item.law_name}`,
  law_name: item.law_name || '未命名依据',
  article_no: item.article_no || '—',
  document_no: item.document_no || '—',
  issuing_body: item.issuing_body || '—',
  article_content: item.article_content || '—',
})))

const processSteps = computed(() => profile.value?.process_info.step_titles || [])
const crossRegionItems = computed(() => (profile.value?.cross_region_service || []).map((item, index) => ({
  key: `${index}-${item.service_scope_type}`,
  scope: item.service_scope_type,
  regions: joinValues(item.regions_summary.length ? item.regions_summary : item.regions_detail),
  serviceModes: joinValues(item.service_modes),
  notes: item.notes,
})))

watch(
  () => [route.name, route.params.profileId, route.params.docId],
  async () => {
    await loadGuide()
  },
  { immediate: true },
)

async function loadGuide() {
  loading.value = true
  guide.value = null

  try {
    guide.value = route.name === 'GuideByDoc'
      ? await getServiceGuideByDoc(String(route.params.docId || ''))
      : await getServiceGuideDetail(String(route.params.profileId || ''))
  } catch (error) {
    console.error('Failed to load service guide detail:', error)
    guide.value = null
  } finally {
    loading.value = false
  }
}

function joinValues(values: string[]): string {
  const normalized = values.filter(Boolean)
  return normalized.length ? normalized.join('、') : '—'
}

function joinSegments(values: string[]): string {
  const normalized = values.filter(Boolean)
  return normalized.length ? normalized.join('；') : '—'
}

function pickBoolean(...values: Array<boolean | null | undefined>): boolean | undefined {
  return values.find((value) => typeof value === 'boolean') as boolean | undefined
}

function yesNoText(value: boolean | undefined): string {
  if (value === true) return '是'
  if (value === false) return '否'
  return '—'
}

function formatTimeLimit(
  value: StandardServiceGuideProfile['basic_info']['promised_time_limit'],
  fallbackDays?: number | null,
): string {
  if (value?.raw_text) return value.raw_text
  if (value?.duration && value.unit) return `${value.duration}${value.unit}`
  if (fallbackDays != null) return `${fallbackDays} 个工作日`
  return '—'
}

function formatCounts(originalCount: number | null, copyCount: number | null): string {
  const segments: string[] = []
  if (originalCount != null) segments.push(`原件 ${originalCount}`)
  if (copyCount != null) segments.push(`复印件 ${copyCount}`)
  return segments.length ? segments.join(' / ') : '—'
}

function requirementLabel(value: string): string {
  if (value === 'required') return '必需'
  if (value === 'optional') return '可选'
  if (value === 'conditional') return '有条件'
  return value || '—'
}

function goBack() {
  if (window.history.length > 1) {
    router.back()
    return
  }
  router.push('/guides')
}

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

function goToMatter(matterId: string) {
  if (!matterId) return
  router.push(`/matters/${matterId}`)
}

function askAboutGuide() {
  if (!profile.value) return
  router.push({
    path: '/qa',
    query: {
      launchKey: String(Date.now()),
      kind: 'guide',
      guideId: profile.value.profile_id,
      docId: profile.value.doc_id,
      title: profile.value.matter_name,
      prompt: `请基于办事指南“${profile.value.matter_name}”总结办理对象、申请材料、收费标准、办理时限、窗口和咨询方式。`,
    },
  })
}
</script>

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

  .detail-header__main {
    h1 {
      margin: 8px 0;
    }
  }

  .header-tags {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

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

  .section-card--compact {
    :deep(.ant-card-body) {
      display: flex;
      flex-direction: column;
      gap: 16px;
    }
  }

  .inline-alert {
    margin-top: 16px;
  }

  .process-summary {
    margin-bottom: 16px;
    color: #595959;
    line-height: 1.7;
  }

  .side-section {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .side-section__title {
    font-weight: 600;
    color: #262626;
  }

  .tag-list,
  .link-list {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .link-list {
    flex-direction: column;
    align-items: flex-start;
  }

  .subtle-text {
    color: #8c8c8c;
    line-height: 1.6;
  }

  .quality-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .quality-list__item {
    padding: 8px 10px;
    border-radius: 8px;
    background: #fffbe6;
    color: #8c6d1f;
  }
}
</style>