<script setup lang="ts">
/**
 * 客户详情页 —— V5.0 升级
 * routes: /customers/detail?id=xxx
 * GET /api/customers/{id} → 渲染档案卡 + AI 画像 + 联系人
 */
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Document,
  ArrowLeft,
  CirclePlus,
  Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import request from '@/api/request'

const route = useRoute()
const router = useRouter()
const loading = ref(true)

// --- 销售跟进记录 ---
const followUpLogs = ref<any[]>([])
const loadingLogs = ref(false)

// --- 关联产品库 ---
const relatedProducts = ref<any[]>([])
const loadingProducts = ref(false)

// --- 客户档案（真实数据） ---
const customer = reactive({
  id: '',
  name: '',
  level: '',
  industry: '',
  contact: '',
  phone: '',
  email: '',
  address: '',
  ai_score: 0,
  owner_name: '',
  status: 1,
  created_at: '',
  updated_at: '',
  ai_persona: null as any,
})

const fetchCustomer = async () => {
  const id = route.query.id as string
  if (!id) {
    ElMessage.warning('缺少客户 ID 参数')
    router.push('/customers')
    return
  }
  loading.value = true
  try {
    const data: any = await request.get(`/api/customers/${id}`)
    Object.assign(customer, data)
    fetchLogs(id)
    fetchContacts(id)
    fetchProducts(id)
  } catch {
    ElMessage.error('获取客户详情失败')
    router.push('/customers')
  } finally {
    loading.value = false
  }
}

// --- 联系人管理 ---
const contacts = ref<any[]>([])
const loadingContacts = ref(false)

const contactDialogVisible = ref(false)
const contactSubmitting = ref(false)
const contactFormRef = ref<FormInstance>()
const contactForm = reactive({ name: '', phone: '', title: '' })
const contactRules = {
  name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }]
}

const fetchContacts = async (customerId: string) => {
  loadingContacts.value = true
  try {
    const res: any = await request.get(`/api/customers/${customerId}/contacts`)
    contacts.value = res || []
  } catch {
  } finally {
    loadingContacts.value = false
  }
}

const openContactDialog = () => {
  contactForm.name = ''
  contactForm.phone = ''
  contactForm.title = ''
  contactDialogVisible.value = true
}

const submitContact = async () => {
  if (!contactFormRef.value) return
  const valid = await contactFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  contactSubmitting.value = true
  try {
    await request.post(`/api/customers/${customer.id}/contacts`, contactForm)
    ElMessage.success('添加联系人成功')
    contactDialogVisible.value = false
    fetchContacts(customer.id)
  } catch {
  } finally {
    contactSubmitting.value = false
  }
}

const deleteContact = (id: string, name: string) => {
  ElMessageBox.confirm(`确定要删除联系人「${name}」吗？`, '警告', { type: 'warning' })
    .then(async () => {
      try {
        await request.delete(`/api/contacts/${id}`)
        ElMessage.success('已删除联系人')
        fetchContacts(customer.id)
      } catch {}
    }).catch(() => {})
}

const fetchLogs = async (customerId: string) => {
  loadingLogs.value = true
  try {
    const res: any = await request.get('/api/sales-logs', { params: { customer_id: customerId, size: 50 } })
    followUpLogs.value = res.items || []
  } catch {
    // 错误已统一处理
  } finally {
    loadingLogs.value = false
  }
}

const fetchProducts = async (customerId: string) => {
  loadingProducts.value = true
  try {
    const res: any = await request.get(`/api/customers/${customerId}/products`)
    relatedProducts.value = res || []
  } catch {
  } finally {
    loadingProducts.value = false
  }
}

// --- 级别显示映射 ---
const levelMap: Record<string, { text: string; type: string }> = {
  A: { text: 'A级 · 核心客户', type: 'danger' },
  B: { text: 'B级 · 重要客户', type: 'warning' },
  C: { text: 'C级 · 普通客户', type: 'info' },
}
const getLevelInfo = (level: string) => levelMap[level] || { text: level, type: 'info' }

// --- 归档 ---
const archiveCustomer = () => {
  ElMessageBox.confirm(`确定要归档客户「${customer.name}」吗？`, '警告', { type: 'warning' })
    .then(async () => {
      try {
        await request.delete(`/api/customers/${customer.id}`)
        ElMessage.success('客户已归档')
        router.push('/customers')
      } catch { /* 已统一 */ }
    })
    .catch(() => {})
}

// --- 写新日志 ---
const handleAddLog = () => {
  router.push({ path: '/logs', query: { customer_id: customer.id, customer_name: customer.name } })
}

onMounted(fetchCustomer)
</script>

<template>
  <div class="customer-detail" v-loading="loading">
    <!-- 返回按钮 -->
    <el-button :icon="ArrowLeft" link @click="router.push('/customers')" style="margin-bottom:10px; font-size:14px">返回客户列表</el-button>

    <!-- 1. 顶部客户档案卡片 -->
    <el-card shadow="never" class="profile-header" v-if="customer.id">
      <div class="header-content">
        <div class="info-section">
          <div class="title-row">
            <h2 class="customer-name">{{ customer.name }}</h2>
            <el-tag :type="(getLevelInfo(customer.level).type as any)" effect="dark" class="level-tag">{{ getLevelInfo(customer.level).text }}</el-tag>
            <el-tag v-if="customer.status === 0" type="info" effect="plain">已停用</el-tag>
          </div>
          
          <el-descriptions :column="2" class="desc-box">
            <el-descriptions-item label="所属行业">{{ customer.industry || '-' }}</el-descriptions-item>
            <el-descriptions-item label="归属人">{{ customer.owner_name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="联系人">{{ customer.contact || '-' }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ customer.phone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="电子邮箱">{{ customer.email || '-' }}</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{ customer.address || '-' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ customer.created_at }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ customer.updated_at }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="ai-assist-section">
          <div class="ai-score-container">
            <el-progress
              type="dashboard"
              :percentage="Math.round(customer.ai_score)"
              :color="[ { color: '#f56c6c', percentage: 20 }, { color: '#e6a23c', percentage: 60 }, { color: '#5cb87a', percentage: 100 } ]"
              :width="100"
            >
              <template #default="{ percentage }">
                <div class="score-value">{{ percentage }}分</div>
                <div class="score-label">AI 客情健康</div>
              </template>
            </el-progress>
          </div>
          
          <div class="action-buttons">
            <el-button type="primary" :icon="Document">🤖 生成拜访简报</el-button>
            <el-button type="danger" plain @click="archiveCustomer">归档客户</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 2. Tabs 面板 -->
    <el-card shadow="never" class="tabs-card" v-if="customer.id">
      <el-tabs>
        <el-tab-pane label="AI 企业画像" name="persona">
          <div v-if="customer.ai_persona && Object.keys(customer.ai_persona).length > 0" class="persona-container">
            <!-- 兼容新老 Schema -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card shadow="hover" class="persona-card h-full">
                  <template #header><div class="card-header">🏭 企业属性 (Firmographics)</div></template>
                  <div v-if="customer.ai_persona.firmographics" class="desc-box">
                    <el-descriptions :column="1" size="small">
                      <el-descriptions-item label="行业">{{ customer.ai_persona.firmographics.industry || '-' }}</el-descriptions-item>
                      <el-descriptions-item label="规模">{{ customer.ai_persona.firmographics.scale || '-' }}</el-descriptions-item>
                      <el-descriptions-item label="商业模式">{{ customer.ai_persona.firmographics.business_model || '-' }}</el-descriptions-item>
                    </el-descriptions>
                  </div>
                  <div v-else class="empty-text">无数据</div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card shadow="hover" class="persona-card h-full">
                  <template #header><div class="card-header">🔥 核心痛点与意向 (Dynamic Status)</div></template>
                  <div v-if="customer.ai_persona.dynamic_status">
                    <div style="margin-bottom:10px;">
                      <strong>痛点: </strong>
                      <el-tag v-for="(item, idx) in customer.ai_persona.dynamic_status.pain_points" :key="idx" type="danger" effect="light" class="p-tag" style="margin-right:5px;margin-bottom:5px;">{{ item }}</el-tag>
                    </div>
                    <div>
                      <strong>意向: </strong>
                      <span class="summary-text">{{ customer.ai_persona.dynamic_status.purchase_intent || '未知' }}</span>
                    </div>
                    <div v-if="customer.ai_persona.dynamic_status.recent_events?.length" style="margin-top:10px;">
                      <strong>近期事件: </strong>
                      <ul><li v-for="(ev, idx) in customer.ai_persona.dynamic_status.recent_events" :key="idx" class="summary-text" style="font-size:13px">{{ev}}</li></ul>
                    </div>
                  </div>
                  <!-- 兼容旧版痛点 -->
                  <div v-else-if="customer.ai_persona.pain_points">
                    <el-tag v-for="(item, idx) in customer.ai_persona.pain_points" :key="idx" type="danger" effect="light" class="p-tag" style="margin-right:5px;">{{ item }}</el-tag>
                  </div>
                  <div v-else class="empty-text">无数据</div>
                </el-card>
              </el-col>
            </el-row>
            <el-row :gutter="20" class="mt-20" v-if="customer.ai_persona.summary">
              <el-col :span="24">
                <el-card shadow="hover" class="persona-card">
                  <template #header><div class="card-header">📝 AI 总结 (Summary)</div></template>
                  <div class="summary-text">{{ customer.ai_persona.summary }}</div>
                </el-card>
              </el-col>
            </el-row>
          </div>
          <div v-else class="timeline-container">
            <el-empty description="暂无 AI 画像数据。销售人员提交跟进日志后，AI 将自动分析提取。" />
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="联系人管理" name="contacts">
          <div class="timeline-container" v-loading="loadingContacts">
            <div style="margin-bottom: 15px; text-align: right;">
              <el-button type="primary" :icon="CirclePlus" @click="openContactDialog">新增联系人</el-button>
            </div>
            <el-table :data="contacts" border stripe style="width: 100%">
              <el-table-column prop="name" label="姓名" width="120" />
              <el-table-column prop="title" label="职位" width="150" />
              <el-table-column prop="phone" label="电话" width="150" />
              <el-table-column label="AI 画像 (Buyer Persona)" min-width="250">
                <template #default="{ row }">
                  <div v-if="row.ai_buyer_persona" class="summary-text" style="font-size: 13px;">
                    <template v-if="row.ai_buyer_persona.role">
                      <el-tag size="small" effect="plain">{{ row.ai_buyer_persona.role.decision_role }}</el-tag>
                      <span style="margin-left: 8px;">权限: {{ row.ai_buyer_persona.role.authority_level }}</span><br/>
                    </template>
                    <span v-if="row.ai_buyer_persona.preference?.comm_style">👩‍💻 沟通: {{ row.ai_buyer_persona.preference.comm_style }}<br/></span>
                    <span v-if="row.ai_buyer_persona.kpi?.core_goals?.length">🎯 目标: {{ row.ai_buyer_persona.kpi.core_goals.join('、') }}</span>
                  </div>
                  <span v-else class="empty-text">无画像档案</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button type="danger" link :icon="Delete" @click="deleteContact(row.id, row.name)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="全景时间轴" name="timeline">
          <div class="timeline-container" v-loading="loadingLogs">
            <el-timeline v-if="followUpLogs.length > 0">
              <el-timeline-item 
                v-for="(log, idx) in followUpLogs" 
                :key="log.id"
                :timestamp="log.log_date" 
                placement="top"
                :type="idx === 0 ? 'primary' : 'info'"
              >
                <el-card shadow="hover" class="timeline-card">
                  <div class="log-content-pre">{{ log.content }}</div>
                  <div class="log-meta">
                    <span class="meta-item">创建时间：{{ log.created_at || '-' }}</span>
                    <el-tag v-if="log.ai_processed" type="success" size="small" effect="plain" class="ai-tag">✨ AI 已提取画像</el-tag>
                    <el-tag v-else type="info" size="small" effect="plain" class="ai-tag">⏳ 等待 AI 提取</el-tag>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
            <el-empty v-else description="暂无跟进记录" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="关联产品库" name="products">
          <div class="timeline-container" v-loading="loadingProducts">
            <el-table v-if="relatedProducts.length > 0" :data="relatedProducts" border stripe style="width: 100%">
              <el-table-column prop="sku_code" label="SKU 编码" width="140" />
              <el-table-column prop="sku_name" label="产品名称" min-width="180" show-overflow-tooltip />
              <el-table-column prop="spec" label="规格" min-width="150" show-overflow-tooltip>
                <template #default="{ row }">{{ row.spec || '-' }}</template>
              </el-table-column>
              <el-table-column label="累计购买量" width="120" align="right">
                <template #default="{ row }"><b>{{ row.total_qty }}</b></template>
              </el-table-column>
              <el-table-column prop="order_count" label="关联订单数" width="110" align="center" />
              <el-table-column prop="last_order_date" label="最近购买日期" width="130" align="center">
                <template #default="{ row }">{{ row.last_order_date || '-' }}</template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无关联产品，该客户尚未产生订单记录" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 联系人表单弹窗 -->
    <el-dialog v-model="contactDialogVisible" title="新增联系人" width="400px" destroy-on-close>
      <el-form ref="contactFormRef" :model="contactForm" :rules="contactRules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="contactForm.name" placeholder="联系人姓名" />
        </el-form-item>
        <el-form-item label="职位" prop="title">
          <el-input v-model="contactForm.title" placeholder="如：采购总监" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="contactForm.phone" placeholder="联系电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="contactDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="contactSubmitting" @click="submitContact">保存</el-button>
      </template>
    </el-dialog>

    <!-- 悬浮按钮 - 写新日志 -->
    <el-tooltip content="写新跟进记录" placement="left">
      <el-button v-if="customer.id" type="primary" circle size="large" class="floating-btn" @click="handleAddLog" :icon="CirclePlus" />
    </el-tooltip>
  </div>
</template>

<style scoped>
.customer-detail { display: flex; flex-direction: column; gap: 20px; position: relative; }
.profile-header { border-radius: 8px; border: none; box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08); }
.header-content { display: flex; justify-content: space-between; align-items: flex-start; gap: 30px; }
.info-section { flex: 1; }
.title-row { display: flex; align-items: center; gap: 15px; margin-bottom: 20px; }
.customer-name { margin: 0; font-size: 24px; color: #303133; }
.level-tag { font-weight: bold; }
.desc-box :deep(.el-descriptions__label) { width: 100px; color: #909399; }
.desc-box :deep(.el-descriptions__content) { color: #606266; font-weight: 500; }
.ai-assist-section { display: flex; flex-direction: column; align-items: center; gap: 20px; min-width: 200px; padding-left: 30px; border-left: 1px dashed #dcdfe6; }
.ai-score-container { display: flex; justify-content: center; align-items: center; }
.score-value { font-size: 24px; font-weight: bold; color: #303133; }
.score-label { font-size: 12px; color: #909399; margin-top: 4px; }
.action-buttons { display: flex; flex-direction: column; gap: 10px; width: 100%; }
.action-buttons .el-button { margin: 0; }
.tabs-card { border-radius: 8px; border: none; box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08); min-height: 400px; }
.timeline-container { padding: 10px 20px; }
.floating-btn { position: fixed; right: 40px; bottom: 40px; width: 48px; height: 48px; font-size: 20px; box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4); z-index: 100; }
.drawer-content { display: flex; flex-direction: column; height: 100%; }
.drawer-footer { display: flex; justify-content: flex-end; }

/* AI Persona Styles */
.persona-container { padding: 10px; }
.mt-20 { margin-top: 20px; }
.persona-card { border-radius: 8px; border: 1px solid #ebeef5; }
.h-full { height: 100%; }
.card-header { font-weight: bold; color: #303133; font-size: 14px; }
.tags-wrapper { display: flex; flex-wrap: wrap; gap: 8px; min-height: 24px; }
.p-tag { font-size: 13px; }
.empty-text { color: #909399; font-size: 13px; font-style: italic; }
.intent-wrapper { display: flex; align-items: center; justify-content: center; height: 100%; min-height: 40px; }
.summary-text { color: #606266; font-size: 14px; line-height: 1.6; }

/* Timeline Styles */
.timeline-card { margin-bottom: 10px; border-radius: 6px; }
.log-content-pre { font-size: 14px; color: #303133; white-space: pre-wrap; line-height: 1.6; margin-bottom: 12px; }
.log-meta { display: flex; align-items: center; gap: 12px; font-size: 12px; color: #909399; }
.ai-tag { margin-left: auto; }
</style>
