<script setup lang="ts">
import { ref, watch } from 'vue'
import { getProductFAQs, getProduct } from '@/api/troubleshoot'
import type { FAQ, Product } from '@/types/troubleshoot'
import { ElMessage } from 'element-plus'
import { renderMarkdown } from '@/utils/markdown'
import { getLocalCache, setLocalCache } from '@/utils/localCache'

interface Props {
  productId: string
  productName: string
}

const props = defineProps<Props>()

const product = ref<Product | null>(null)
const faqs = ref<FAQ[]>([])
const loading = ref(true)
const expandedFAQ = ref<string | null>(null)
const faqDetail = ref<string>('')

async function loadData() {
  loading.value = true
  expandedFAQ.value = null
  faqDetail.value = ''

  try {
    // 优先读取本地缓存（5 分钟过期）
    const cacheKey = `faqs_${props.productId}`
    const cached = getLocalCache<FAQ[]>(cacheKey)

    const [productRes, faqsRes] = await Promise.all([
      getProduct(props.productId),
      // 缓存命中则跳过 FAQ 请求，仅请求产品信息
      cached ? Promise.resolve({ success: true, faqs: cached }) : getProductFAQs(props.productId),
    ])

    if (productRes.success) {
      product.value = productRes.product || null
    }

    if (faqsRes.success) {
      faqs.value = faqsRes.faqs
      setLocalCache(cacheKey, faqsRes.faqs)
    }
  } catch {
    ElMessage.error('加载常见问题失败')
  } finally {
    loading.value = false
  }
}

function toggleFAQ(faq: FAQ) {
  if (expandedFAQ.value === faq.record_id) {
    expandedFAQ.value = null
    return
  }
  expandedFAQ.value = faq.record_id
}

function downloadFAQRecord(faq: FAQ) {
  window.open('/api/troubleshoot/record/' + faq.record_id + '/download', '_blank')
}

watch(() => props.productId, loadData, { immediate: true })
</script>

<template>
  <div class="faqs-panel" v-loading="loading">
    <div class="panel-header">
      <h2>❓ {{ productName }} — 常见问题</h2>
      <span class="faq-count">共 {{ faqs.length }} 个问题</span>
    </div>

    <div v-if="!loading && faqs.length === 0" class="empty-state">
      <div class="empty-icon">📝</div>
      <h3>常见问题整理中</h3>
      <p>排查指引正在整理，敬请期待</p>
    </div>

    <div v-else class="faq-list">
      <div v-for="(faq, i) in faqs" :key="faq.record_id" class="faq-item"
        :class="{ expanded: expandedFAQ === faq.record_id }">
        <div class="faq-header" @click="toggleFAQ(faq)">
          <span class="faq-index">{{ i + 1 }}</span>
          <span class="faq-title">{{ faq.title }}</span>
          <span class="expand-icon" :class="{ expanded: expandedFAQ === faq.record_id }">▶</span>
        </div>
        <transition name="expand">
          <div v-if="expandedFAQ === faq.record_id" class="faq-detail">
            <div class="detail-section" v-if="faq.phenomenon">
              <div class="section-label"><span class="section-icon">🔴</span>问题现象</div>
              <div class="section-content phenomenon">{{ faq.phenomenon }}</div>
            </div>
            <div class="detail-section" v-if="faq.solution">
              <div class="section-label"><span class="section-icon">🟢</span>排查指引</div>
              <div class="section-content markdown-content" v-html="renderMarkdown(faq.solution)"></div>
            </div>
            <div v-if="!faq.solution" class="detail-section">
              <div class="section-label"><span class="section-icon">🟡</span>排查指引</div>
              <div class="section-content"><p class="no-content">排查步骤正在整理中...</p></div>
            </div>
            <div class="detail-actions">
              <el-button size="small" @click="downloadFAQRecord(faq)">📥 下载文档</el-button>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.faqs-panel {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  min-height: 400px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  h2 { font-size: 18px; font-weight: 600; color: #1d2129; margin: 0; }
  .faq-count { font-size: 13px; color: #86909c; background: #f2f3f5; padding: 4px 12px; border-radius: 12px; }
}
.empty-state {
  display: flex; flex-direction: column; align-items: center; justify-content: center;
  height: 300px; color: #86909c;
  .empty-icon { font-size: 56px; margin-bottom: 16px; opacity: 0.5; }
  h3 { font-size: 16px; font-weight: 500; color: #4e5969; margin: 0 0 8px; }
  p { font-size: 14px; margin: 0; }
}
.faq-list { display: flex; flex-direction: column; gap: 10px; }
.faq-item {
  background: #fafafa; border-radius: 10px; border: 1px solid #f0f0f0;
  overflow: hidden; transition: all 0.2s;
  &.expanded { background: #fff; border-color: #e0e7ff; box-shadow: 0 4px 16px rgba(22, 125, 255, 0.1); }
}
.faq-header {
  display: flex; align-items: center; gap: 12px;
  padding: 14px 18px; cursor: pointer; transition: background 0.15s;
  &:hover { background: #f2f3f5; }
  .expanded & { background: #f7f9fc; }
}
.faq-index {
  display: flex; align-items: center; justify-content: center;
  width: 24px; height: 24px; border-radius: 6px;
  background: #e8f3ff; color: #165dff; font-size: 12px; font-weight: 600; flex-shrink: 0;
}
.faq-title { flex: 1; font-size: 14px; font-weight: 500; color: #1d2129; line-height: 1.5; }
.expand-icon {
  font-size: 10px; color: #86909c; transition: transform 0.2s; flex-shrink: 0;
  &.expanded { transform: rotate(90deg); }
}
.faq-detail { padding: 0 18px 18px; border-top: 1px solid #f0f0f0; }
.detail-section { margin-top: 16px; }
.section-label {
  display: flex; align-items: center; gap: 6px;
  font-size: 14px; font-weight: 600; color: #1d2129; margin-bottom: 10px;
  .section-icon { font-size: 12px; }
}
.section-content {
  background: #f7f8fa; border-radius: 8px; padding: 14px 16px;
  font-size: 14px; color: #4e5969; line-height: 1.8;
  &.phenomenon { border-left: 3px solid #ff7d00; }
}
.no-content { color: #c9cdd4; font-style: italic; margin: 0; }
.markdown-content { line-height: 1.8; }
.detail-actions { margin-top: 16px; padding-top: 14px; border-top: 1px solid #f0f0f0; display: flex; justify-content: flex-end; }
.expand-enter-active, .expand-leave-active { transition: all 0.25s ease; overflow: hidden; }
.expand-enter-from, .expand-leave-to { opacity: 0; max-height: 0; padding-top: 0; padding-bottom: 0; }
.expand-enter-to, .expand-leave-from { opacity: 1; max-height: 800px; }
</style>
