<script setup lang="ts">
/**
 * 合作咨询：只读列表 + page-container 详情 + 状态流转（未读→已读→已联系）。
 */
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useToast } from '@wot-ui/ui'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import AdminFilterBar from '../../components/AdminFilterBar.vue'
import AdminStatusBadge from '../../components/AdminStatusBadge.vue'
import AdminDetailDrawer from '../../components/AdminDetailDrawer.vue'
import { useAdminGuard } from '../../composables/useAdminGuard'
import { adminList, normalizeAdminList, updateInquiryStatus, type Inquiry } from '@/api'

const STATUS_MAP: Record<string, string> = {
  '0': '未读',
  '1': '已读',
  '2': '已联系',
}

const toast = useToast()
const { guardAdmin } = useAdminGuard()
const loading = ref(false)
const list = ref<Inquiry[]>([])
const keyword = ref('')
const filters = ref<Record<string, unknown>>({})
const detailShow = ref(false)
const current = ref<Inquiry | null>(null)

const filterDefs = [
  { key: 'keyword', label: '关键词', type: 'text' as const },
  {
    key: 'status',
    label: '状态',
    type: 'select' as const,
    options: [
      { label: '全部', value: '' },
      { label: '未读', value: 0 },
      { label: '已读', value: 1 },
      { label: '已联系', value: 2 },
    ],
  },
]

async function load() {
  if (!guardAdmin()) return
  loading.value = true
  try {
    list.value = normalizeAdminList(await adminList('inquiries', {
      page: 1,
      pageSize: 500,
      keyword: keyword.value || undefined,
      ...filters.value,
    })) as Inquiry[]
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '加载失败')
  }
  finally {
    loading.value = false
  }
}

onShow(load)

async function openDetail(item: Inquiry) {
  current.value = { ...item }
  detailShow.value = true
  // 未读自动标已读
  if (Number(item.status) === 0) {
    try {
      await updateInquiryStatus(item.id, 1)
      item.status = 1
      current.value.status = 1
    }
    catch { /* 忽略自动标记失败 */ }
  }
}

async function setStatus(status: number) {
  if (!current.value?.id) return
  try {
    await updateInquiryStatus(current.value.id, status)
    current.value.status = status
    const hit = list.value.find(i => i.id === current.value!.id)
    if (hit) hit.status = status
    toast.success('状态已更新')
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '更新失败')
  }
}

function detailRows() {
  const c = current.value
  if (!c) return []
  return [
    { label: '姓名', value: String(c.name || '') },
    { label: '公司', value: String(c.company || '') },
    { label: '联系方式', value: `${c.contactMethod || ''} ${c.contactValue || ''}` },
    { label: '预算', value: String(c.budget || '') },
    { label: '需求', value: String(c.description || '') },
    { label: '状态', value: STATUS_MAP[String(c.status ?? 0)] || '' },
    { label: '时间', value: String(c.createdAt || '') },
  ]
}
</script>

<template>
  <AppPageShell admin>
    <AppNavbar title="合作咨询" show-back />
    <view class="page-pad">
      <AdminFilterBar
        v-model:keyword="keyword"
        v-model="filters"
        :filters="filterDefs"
        @search="load"
        @reset="load"
      />
      <view v-for="item in list" :key="item.id" class="admin-card row" @click="openDetail(item)">
        <view class="main">
          <view class="title-row">
            <text class="title">{{ item.name || '匿名' }}</text>
            <AdminStatusBadge :value="item.status" :map="STATUS_MAP" />
          </view>
          <text class="sub text-art-muted">{{ item.company || '—' }} · {{ item.createdAt || '' }}</text>
        </view>
      </view>
      <wd-loading v-if="loading" />
      <wd-empty v-if="!loading && !list.length" description="暂无咨询" />
    </view>

    <AdminDetailDrawer v-model:show="detailShow" title="咨询详情" :rows="detailRows()">
      <template #footer>
        <wd-button size="small" @click="setStatus(1)">标为已读</wd-button>
        <wd-button size="small" type="primary" @click="setStatus(2)">标为已联系</wd-button>
      </template>
    </AdminDetailDrawer>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 80rpx; }
.row { padding: 24rpx 28rpx; margin-bottom: 16rpx; }
.main { display: flex; flex-direction: column; gap: 8rpx; }
.title-row { display: flex; align-items: center; gap: 12rpx; }
.title { flex: 1; font-size: 30rpx; color: rgb(var(--art-text)); }
.sub { font-size: 24rpx; }
</style>
