<template>
  <div class="site-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>站点管理</span>
          <el-button type="primary" @click="openDialog()">新增站点</el-button>
        </div>
      </template>

      <el-table :data="list" v-loading="loading" stripe>
        <el-table-column label="ID" width="240">
          <template #default="{ row }">{{ row.id }}</template>
        </el-table-column>
        <el-table-column prop="name" label="站点名称" width="160" />
        <el-table-column prop="domain" label="域名" width="180" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="380">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="$router.push(`/pages?site_id=${row.id}`)">网页管理</el-button>
            <el-button link type="primary" size="small" @click="$router.push(`/homepage-edit?site_id=${row.id}`)">首页编辑</el-button>
            <el-button link type="primary" size="small" @click="$router.push(`/module-upload?site_id=${row.id}`)">功能模块</el-button>
            <el-tag v-if="officialSiteId === row.id" type="success" size="small">官网</el-tag>
            <el-button v-else link type="success" size="small" @click="setAsOfficial(row)">设为官网</el-button>
            <el-button link type="primary" size="small" @click="openDialog(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="editId ? '编辑站点' : '新增站点'" width="500px" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="站点名称" />
        </el-form-item>
        <el-form-item label="域名" prop="domain">
          <el-input v-model="form.domain" placeholder="如 www.example.com" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" rows="2" placeholder="可选" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSites, createSite, updateSite, deleteSite, getOfficialSite, setOfficialSite } from '../../api/admin'

const list = ref([])
const loading = ref(false)
const officialSiteId = ref('')

const fetchOfficialSite = async () => {
  try {
    const res = await getOfficialSite()
    officialSiteId.value = res.site_id || ''
  } catch (_) {
    officialSiteId.value = ''
  }
}

const setAsOfficial = async (row) => {
  try {
    await setOfficialSite(row.id)
    ElMessage.success('已设为官网站点')
    officialSiteId.value = row.id
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  }
}

const fetchList = async () => {
  loading.value = true
  try {
    const sitesRes = await getSites()
    list.value = sitesRes.list || []
    try {
      const officialRes = await getOfficialSite()
      officialSiteId.value = officialRes.site_id || ''
    } catch (_) {
      officialSiteId.value = ''
    }
  } catch (e) {
    ElMessage.error(e.message)
  } finally {
    loading.value = false
  }
}

const dialogVisible = ref(false)
const editId = ref('')
const submitting = ref(false)
const formRef = ref(null)
const form = reactive({ name: '', domain: '', description: '' })
const rules = { name: [{ required: true, message: '请输入站点名称', trigger: 'blur' }] }

const openDialog = (row) => {
  editId.value = row ? row.id : ''
  form.name = row ? row.name : ''
  form.domain = row ? row.domain || '' : ''
  form.description = row ? row.description || '' : ''
  dialogVisible.value = true
}

const resetForm = () => {
  form.name = ''
  form.domain = ''
  form.description = ''
  editId.value = ''
}

const submitForm = async () => {
  await formRef.value?.validate()
  submitting.value = true
  try {
    if (editId.value) {
      await updateSite(editId.value, { name: form.name, domain: form.domain, description: form.description })
      ElMessage.success('更新成功')
    } else {
      await createSite(form)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchList()
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  } finally {
    submitting.value = false
  }
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm('确定删除该站点？其网页与上传文件将一并删除。', '提示', { type: 'warning' })
  try {
    await deleteSite(row.id)
    ElMessage.success('删除成功')
    fetchList()
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  }
}

onMounted(fetchList)
</script>

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