<template>
  <div class="page-card">
    <h2 class="page-title">回访线索</h2>
    <div class="filter-row">
      <el-select v-model="status" style="width: 140px" @change="load">
        <el-option label="待回访" value="pending" />
        <el-option label="全部" value="all" />
      </el-select>
      <el-checkbox v-model="dueToday" @change="load">到期≤今天</el-checkbox>
    </div>
    <el-table :data="rows" v-loading="loading" stripe>
      <el-table-column prop="petName" label="宠物" width="120" />
      <el-table-column prop="serviceType" label="服务" min-width="120" />
      <el-table-column prop="phone" label="手机" width="140" />
      <el-table-column prop="remindDate" label="建议日期" width="120" />
      <el-table-column prop="remindStatus" label="状态" width="100" />
      <el-table-column label="微信" width="80">
        <template #default="{ row }">{{ row.wechatBound ? '是' : '否' }}</template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button
            v-if="row.reportId"
            link
            type="primary"
            @click="openReport(row)"
          >打开报告</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getLeads, getReportList } from '@/api'
import { reportPublicUrl } from '@/utils/publicLinks'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const status = ref('pending')
const dueToday = ref(route.query.due === 'today')
const rows = ref<Array<Record<string, unknown>>>([])

function todayStr() {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

async function load() {
  loading.value = true
  try {
    const res = await getLeads(status.value)
    let list = Array.isArray(res.data) ? (res.data as Array<Record<string, unknown>>) : []
    if (dueToday.value) {
      const t = todayStr()
      list = list.filter((l) => {
        const d = l.remindDate as string | undefined
        return !d || d <= t
      })
    }
    rows.value = list
  } finally {
    loading.value = false
  }
}

async function openReport(row: Record<string, unknown>) {
  const reportId = Number(row.reportId)
  if (!reportId) return
  // 优先用列表里的 token；没有则从报告列表反查
  const listRes = await getReportList({ page: 1, pageSize: 200 })
  const reports = Array.isArray(listRes.data) ? (listRes.data as Array<Record<string, unknown>>) : []
  const hit = reports.find((r) => Number(r.id) === reportId)
  const token = hit?.reportToken as string | undefined
  if (token) {
    window.open(reportPublicUrl(token), '_blank')
    return
  }
  ElMessage.warning('未找到公开链接，已跳转报告中心')
  await router.push({ path: '/reports', query: { q: String(reportId) } })
}

onMounted(load)
</script>
