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

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)

async function loadData() {
  loading.value = true
  try {
    const [productRes, docsRes] = await Promise.all([
      getProduct(props.productId),
      getProductDocuments(props.productId),
    ])

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

    if (docsRes.success) {
      documents.value = 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 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>
  </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;
}
</style>
