<template>
  <div class="page-container matter-detail-view">
    <a-spin :spinning="matterStore.detailLoading">
      <template v-if="matterStore.currentMatter">
        <div class="detail-header">
          <a-button type="text" @click="router.push('/matters')">返回事项页</a-button>
          <a-space wrap>
            <a-button type="primary" @click="askAboutMatter">问这个事项</a-button>
            <a-button @click="viewRelatedGuides">查看关联办事指南</a-button>
            <a-button @click="openMatterImportDialog">加入资料篮</a-button>
            <a-button @click="exportChecklist">导出办理清单</a-button>
            <a-button
              type="primary"
              ghost
              @click="openGoverningDocImportDialog"
              :disabled="matterStore.currentMatter.governing_docs.length === 0"
            >
              依据文件加入资料篮
            </a-button>
          </a-space>
        </div>

        <MatterCard :matter="matterStore.currentMatter" @open-document="openDocument" />

        <ImportToResearchDialog
          v-model:open="importDialogOpen"
          :items="importPreviewItems"
          :title="importDialogTitle"
          :extra-options="importExtraOptions"
          @confirm="handleImportConfirm"
        />
      </template>

      <a-result v-else-if="!matterStore.detailLoading" status="404" title="事项未找到" sub-title="请检查事项 ID 是否正确。">
        <template #extra>
          <a-button type="primary" @click="router.push('/matters')">返回事项页</a-button>
        </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 ImportToResearchDialog from '@/components/ImportToResearchDialog.vue'
import MatterCard from '@/components/MatterCard.vue'
import { useResearchImport } from '@/composables/useResearchImport'
import { useMatterStore } from '@/stores/matter'
import type { BasketItem } from '@/types/basket'
import type {
  ImportDialogExtraOption,
  ResearchImportDialogPayload,
} from '@/types/research-import'

const route = useRoute()
const router = useRouter()
const matterStore = useMatterStore()
const { applyImport } = useResearchImport()

const importMode = ref<'matter' | 'governing-docs'>('matter')
const importDialogOpen = ref(false)

const importDialogTitle = computed(() => {
  if (!matterStore.currentMatter) return '加入资料篮'
  return importMode.value === 'matter'
    ? `将事项”${matterStore.currentMatter.name}”加入资料篮`
    : `将”${matterStore.currentMatter.name}”的依据文件加入资料篮`
})

const importPreviewItems = computed<BasketItem[]>(() => {
  const matter = matterStore.currentMatter
  if (!matter) return []

  if (importMode.value === 'governing-docs') {
    return buildGoverningDocItems()
  }
  return [buildMatterItem()]
})

const importExtraOptions = computed<ImportDialogExtraOption[]>(() => {
  if (importMode.value === 'governing-docs') return []
  return [
    {
      key: 'include-governing-docs',
      label: '同时加入依据文件',
      description: '将该事项的 governing docs 一并导入本次 Research。',
    },
  ]
})

watch(
  () => route.params.matterId,
  async (matterId) => {
    if (!matterId) return
    try {
      await matterStore.loadCard(String(matterId))
    } catch {
      message.error('事项详情加载失败')
    }
  },
  { immediate: true },
)

function buildMatterItem(): BasketItem {
  const matter = matterStore.currentMatter!
  return {
    item_type: 'matter',
    title: matter.name,
    selected_from: 'matter',
    importance: 'reference',
    matter_id: matter.matter_id,
    governing_doc_ids: matter.governing_docs.map((doc) => doc.doc_id),
    added_at: Date.now(),
  }
}

function buildGoverningDocItems(): BasketItem[] {
  const matter = matterStore.currentMatter
  if (!matter) return []

  return matter.governing_docs.map((doc) => ({
    item_type: 'document',
    title: doc.title || doc.doc_code || doc.doc_id,
    selected_from: 'matter',
    importance: 'reference',
    doc_id: doc.doc_id,
    doc_code: doc.doc_code,
    added_at: Date.now(),
  }))
}

function openMatterImportDialog() {
  importMode.value = 'matter'
  importDialogOpen.value = true
}

function openGoverningDocImportDialog() {
  importMode.value = 'governing-docs'
  importDialogOpen.value = true
}

function handleImportConfirm(payload: ResearchImportDialogPayload) {
  const items = importMode.value === 'governing-docs'
    ? buildGoverningDocItems()
    : [
        buildMatterItem(),
        ...(payload.selectedExtraKeys.includes('include-governing-docs')
          ? buildGoverningDocItems()
          : []),
      ]
  applyImport(items, payload)
}

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

function askAboutMatter() {
  const matter = matterStore.currentMatter
  if (!matter) return

  router.push({
    path: '/qa',
    query: {
      launchKey: String(Date.now()),
      kind: 'matter',
      matterId: matter.matter_id,
      title: matter.name,
      governingDocIds: matter.governing_docs.map((doc) => doc.doc_id).join(','),
      prompt: `请围绕事项“${matter.name}”梳理办理条件、所需材料、办理时限和依据文件。`,
    },
  })
}

function viewRelatedGuides() {
  const matter = matterStore.currentMatter
  if (!matter) return

  router.push({
    path: '/guides',
    query: {
      matterId: matter.matter_id,
      matterName: matter.name,
    },
  })
}

function exportChecklist() {
  const matter = matterStore.currentMatter
  if (!matter) return

  const lines = [
    `事项名称：${matter.name}`,
    `事项类型：${matter.matter_type || '-'}`,
    `状态：${matter.status || '-'}`,
    `办理部门：${matter.handled_by.map((item) => item.name).join('、') || '-'}`,
    `适用地域：${matter.regions.map((item) => item.full_name).join('、') || '-'}`,
    '',
    '办理条件：',
    ...(matter.conditions.length
      ? matter.conditions.map((item, index) => `${index + 1}. ${item.name}：${item.description || item.structured_value || '-'}`)
      : ['- 无']),
    '',
    '所需材料：',
    ...(matter.materials.length
      ? matter.materials.map((item, index) => `${index + 1}. ${item.name}${item.is_required ? '（必需）' : ''}`)
      : ['- 无']),
    '',
    '办理时限：',
    ...(matter.time_limits.length
      ? matter.time_limits.map((item, index) => `${index + 1}. ${item.name}：${item.duration || '-'}${item.unit || ''}`)
      : ['- 无']),
  ]

  const blob = new Blob([lines.join('\n')], { type: 'text/plain;charset=utf-8' })
  const url = window.URL.createObjectURL(blob)
  const link = window.document.createElement('a')
  link.href = url
  link.download = `${matter.name}-办理清单.txt`
  link.click()
  window.URL.revokeObjectURL(url)
  message.success('办理清单已导出')
}
</script>

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