<script setup lang="ts">
import { ref, watch } from 'vue'
import { getProductDocuments, downloadDocument, getProduct, uploadDocument, deleteDocument, previewDocument } from '@/api/troubleshoot'
import type { ProductDocument, Product } from '@/types/troubleshoot'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getLocalCache, setLocalCache } from '@/utils/localCache'
import { renderMarkdown } from '@/utils/markdown'
import http from '@/utils/http'

interface Props {
  productId: string
  productName: string
}

const props = defineProps<Props>()

const userStore = useUserStore()
const product = ref<Product | null>(null)
const documents = ref<ProductDocument[]>([])
const loading = ref(true)
const uploading = ref(false)
const deletingId = ref<string | null>(null)

// 预览状态
const previewVisible = ref(false)
const previewLoading = ref(false)
const previewTitle = ref('')
const previewContent = ref('')
const previewType = ref<'text' | 'pdf' | 'image' | 'unsupported'>('text')
const previewUrl = ref('')
const previewingDoc = ref<ProductDocument | null>(null)

async function handlePreview(doc: ProductDocument) {
  previewVisible.value = true
  previewingDoc.value = doc
  previewTitle.value = doc.title
  previewContent.value = ''
  previewType.value = 'text'
  previewUrl.value = ''
  previewLoading.value = true

  try {
    const ext = doc.type.toLowerCase()
    // PDF 和图片类型：直接打开预览 URL
    if (ext === 'pdf' || ['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(ext)) {
      previewType.value = ext === 'pdf' ? 'pdf' : 'image'
      previewUrl.value = previewDocument(doc.id)
      previewLoading.value = false
      return
    }
    // 文本类：调用预览 API 获取内容
    if (['md', 'txt', 'log', 'text'].includes(ext)) {
      const res = await http.get(previewDocument(doc.id))
      if (res.data?.success && res.data.content) {
        previewContent.value = res.data.content
      } else {
        previewContent.value = '无法加载文档内容'
      }
    } else {
      previewType.value = 'unsupported'
      previewContent.value = '该格式暂不支持在线预览，请下载后查看'
    }
  } catch {
    previewType.value = 'unsupported'
    previewContent.value = '预览加载失败'
  } finally {
    previewLoading.value = false
  }
}

async function loadData() {
  loading.value = true
  try {
    // 优先读取本地缓存
    const cacheKey = `docs_${props.productId}`
    const cached = getLocalCache<ProductDocument[]>(cacheKey)

    const [productRes, docsRes] = await Promise.all([
      getProduct(props.productId),
      // 缓存命中则跳过文档请求
      cached ? Promise.resolve({ success: true, documents: cached }) : getProductDocuments(props.productId),
    ])

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

    if (docsRes.success) {
      documents.value = docsRes.documents
      setLocalCache(cacheKey, docsRes.documents)
    }
  } catch {
    ElMessage.error('加载资料失败')
  } finally {
    loading.value = false
  }
}

function handleDownload(doc: ProductDocument) {
  const url = downloadDocument(doc.id)
  const link = document.createElement('a')
  link.href = url
  link.download = doc.title + '.' + doc.type
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('正在下载：' + doc.title)
}

async function handleUpload() {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.docx,.pdf,.md,.doc,.xlsx,.xls'
  input.onchange = async (e: Event) => {
    const target = e.target as HTMLInputElement
    const file = target.files?.[0]
    if (!file) return

    uploading.value = true
    try {
      const res = await uploadDocument(props.productId, file)
      if (res.success) {
        ElMessage.success('上传成功！')
        await loadData()
      } else {
        ElMessage.error(res.message || '上传失败')
      }
    } catch {
      ElMessage.error('上传异常')
    } finally {
      uploading.value = false
    }
  }
  input.click()
}

async function handleDelete(doc: ProductDocument) {
  try {
    await ElMessageBox.confirm(
      '确定要删除「' + doc.title + '」吗？此操作不可撤销。',
      '确认删除',
      { confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning' }
    )

    deletingId.value = doc.id
    const res = await deleteDocument(doc.id)
    if (res.success) {
      ElMessage.success('已删除')
      await loadData()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch {
    // 取消操作
  } finally {
    deletingId.value = null
  }
}

function getFileIcon(type: string): string {
  switch (type.toLowerCase()) {
    case 'pdf': return '📕'
    case 'docx':
    case 'doc': return '📘'
    case 'xlsx':
    case 'xls': return '📗'
    case 'md': return '📝'
    default: return '📄'
  }
}

function getTypeColor(type: string): string {
  switch (type.toLowerCase()) {
    case 'pdf': return '#cf1322'
    case 'docx':
    case 'doc': return '#1677ff'
    case 'xlsx':
    case 'xls': return '#389e0d'
    case 'md': return '#531dab'
    default: return '#86909c'
  }
}

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

<template>
  <div class="documents-panel" v-loading="loading || uploading">
    <!-- 标题 -->
    <div class="panel-header">
      <div class="header-left">
        <h2>📁 {{ productName }} — 产品资料</h2>
      </div>
      <div class="header-right">
        <span class="doc-count">共 {{ documents.length }} 份文档</span>
        <el-button
          v-if="userStore.isAdmin"
          type="primary"
          size="small"
          :loading="uploading"
          @click="handleUpload"
        >
          ➕ 上传文档
        </el-button>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && documents.length === 0" class="empty-state">
      <div class="empty-icon">📂</div>
      <h3>暂无资料文档</h3>
      <p>该产品暂未上传维护手册或技术文档</p>
    </div>

    <!-- 文档列表 -->
    <div v-else class="doc-list">
      <div
        v-for="doc in documents"
        :key="doc.id"
        class="doc-item"
      >
        <div class="doc-icon-wrap">
          <span class="doc-icon">{{ getFileIcon(doc.type) }}</span>
        </div>
        <div class="doc-info">
          <div class="doc-title" @click="handleDownload(doc)">
            {{ doc.title }}
          </div>
          <div class="doc-meta">
            <span
              class="doc-type"
              :style="{ color: getTypeColor(doc.type), background: getTypeColor(doc.type) + '12' }"
            >
              {{ doc.type.toUpperCase() }}
            </span>
            <span v-if="doc.size" class="doc-size">{{ doc.size }}</span>
          </div>
        </div>
        <div class="doc-actions">
          <el-button size="small" @click="handlePreview(doc)">
            <span class="btn-icon">👁</span>
            预览
          </el-button>
          <el-button type="primary" size="small" @click="handleDownload(doc)">
            <span class="btn-icon">⬇</span>
            下载
          </el-button>
          <el-button
            v-if="userStore.isAdmin"
            type="danger"
            size="small"
            :loading="deletingId === doc.id"
            @click="handleDelete(doc)"
          >
            🗑
          </el-button>
        </div>
      </div>
    </div>

    <!-- 文档预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      :title="'📄 ' + previewTitle"
      width="720px"
      :destroy-on-close="true"
      top="6vh"
    >
      <div v-loading="previewLoading" class="preview-body">
        <!-- PDF / 图片：内联 iframe / img -->
        <iframe
          v-if="previewType === 'pdf' && !previewLoading"
          :src="previewUrl"
          class="preview-frame"
        />
        <img
          v-else-if="previewType === 'image' && !previewLoading"
          :src="previewUrl"
          class="preview-image"
          alt="文档预览"
        />
        <!-- 文本类：Markdown 渲染 -->
        <div
          v-else-if="previewType === 'text' && previewContent"
          class="preview-markdown"
          v-html="renderMarkdown(previewContent)"
        />
        <!-- 不支持的格式提示 -->
        <div v-else-if="previewType === 'unsupported'" class="preview-unsupported">
          <div class="unsupported-icon">📄</div>
          <p>{{ previewContent }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
        <el-button v-if="previewingDoc" type="primary" @click="handleDownload(previewingDoc)">
          📥 下载文档
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.documents-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;
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .doc-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;
  }
}

.doc-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.doc-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 20px;
  background: #fafafa;
  border-radius: 10px;
  border: 1px solid #f0f0f0;
  transition: all 0.2s;

  &:hover {
    background: #f7f9fc;
    border-color: #e0e7ff;
    box-shadow: 0 2px 8px rgba(22, 125, 255, 0.08);
  }
}

.doc-icon-wrap {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border-radius: 10px;
  border: 1px solid #f0f0f0;
}

.doc-icon {
  font-size: 28px;
}

.doc-info {
  flex: 1;
  min-width: 0;
}

.doc-title {
  font-size: 15px;
  font-weight: 500;
  color: #1d2129;
  margin-bottom: 6px;
  cursor: pointer;

  &:hover {
    color: #165dff;
  }
}

.doc-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 12px;
}

.doc-type {
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 600;
  font-size: 11px;
  letter-spacing: 0.5px;
}

.doc-size {
  color: #86909c;
}

.doc-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.btn-icon {
  margin-right: 4px;
}

// ============================================================
// 文档预览弹窗
// ============================================================
.preview-body {
  min-height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.preview-frame {
  width: 100%;
  height: 70vh;
  border: none;
  border-radius: 8px;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  border-radius: 8px;
}

.preview-markdown {
  width: 100%;
  padding: 20px;
  line-height: 1.8;
  max-height: 70vh;
  overflow-y: auto;

  :deep(h1), :deep(h2), :deep(h3) {
    color: #303133;
    margin-top: 16px;
    margin-bottom: 8px;
  }
  :deep(h1) { font-size: 18px; }
  :deep(h2) { font-size: 16px; color: #2563eb; }
  :deep(h3) { font-size: 14px; }
  :deep(p), :deep(li) { color: #606266; font-size: 14px; }
  :deep(ol), :deep(ul) { padding-left: 20px; margin: 8px 0; }
  :deep(code) { background: #eef2ff; color: #1e40af; padding: 2px 6px; border-radius: 4px; font-size: 13px; }
  :deep(pre) { background: #1e293b; color: #e2e8f0; padding: 12px; border-radius: 8px; overflow-x: auto; }
  :deep(blockquote) { border-left: 3px solid #2563eb; padding: 8px 16px; margin: 12px 0; background: #f8fafc; }
}

.preview-unsupported {
  text-align: center;
  color: #86909c;
  padding: 40px;
  .unsupported-icon { font-size: 48px; margin-bottom: 16px; opacity: 0.5; }
  p { font-size: 14px; margin: 0; }
}
</style>
