<template>
  <div class="module-upload">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>功能模块上传</span>
          <div>
            <el-select v-model="siteId" placeholder="选择站点" filterable style="width: 220px; margin-right: 12px" @change="fetchList">
              <el-option v-for="s in sites" :key="s.id" :label="s.name" :value="s.id" />
            </el-select>
            <el-upload
              :show-file-list="false"
              :disabled="!siteId"
              :before-upload="beforeUpload"
            >
              <el-button type="primary" :disabled="!siteId" :loading="uploading">上传文件</el-button>
            </el-upload>
          </div>
        </div>
      </template>

      <el-alert v-if="!siteId" title="请先选择站点" type="info" style="margin-bottom: 16px" />

      <el-table v-else :data="list" v-loading="loading" stripe>
        <el-table-column label="文件名" prop="name" min-width="180" />
        <el-table-column label="存储路径" prop="file_path" min-width="200" show-overflow-tooltip />
        <el-table-column label="大小" width="100">
          <template #default="{ row }">{{ formatSize(row.size) }}</template>
        </el-table-column>
        <el-table-column label="上传时间" prop="created_at" width="180" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="siteId && !loading && list.length === 0" description="暂无上传文件，请点击上传" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSites, getSiteAssets, uploadSiteAsset, deleteSiteAsset } from '../../api/admin'

const siteId = ref('')
const sites = ref([])
const list = ref([])
const loading = ref(false)
const uploading = ref(false)

const fetchSites = async () => {
  try {
    const res = await getSites()
    sites.value = res.list || []
    const q = new URLSearchParams(window.location.search)
    if (q.get('site_id') && sites.value.some((s) => s.id === q.get('site_id'))) {
      siteId.value = q.get('site_id')
    } else if (sites.value.length) {
      siteId.value = sites.value[0].id
    }
  } catch (e) {
    ElMessage.error(e.message)
  }
}

const fetchList = async () => {
  if (!siteId.value) {
    list.value = []
    return
  }
  loading.value = true
  try {
    const res = await getSiteAssets(siteId.value)
    list.value = res.list || []
  } catch (e) {
    ElMessage.error(e.message)
  } finally {
    loading.value = false
  }
}

watch(siteId, fetchList)

const beforeUpload = async (file) => {
  uploading.value = true
  try {
    await uploadSiteAsset(siteId.value, file)
    ElMessage.success('上传成功')
    fetchList()
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message || '上传失败')
  } finally {
    uploading.value = false
  }
  return false
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm('确定删除该文件？', '提示', { type: 'warning' })
  try {
    await deleteSiteAsset(siteId.value, row.id)
    ElMessage.success('删除成功')
    fetchList()
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  }
}

const formatSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

onMounted(() => {
  fetchSites().then(() => fetchList())
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
