<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>投诉建议</h2>
      <div class="header-actions">
        <el-button @click="apiDocVisible = true">
          <el-icon><Document /></el-icon>
          接口说明
        </el-button>
        <el-button @click="openCategoryDialog">
          <el-icon><Collection /></el-icon>
          产品分类
        </el-button>
        <el-button type="primary" @click="editRef.open()">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button @click="fetchList" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-divider />

    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="产品分类">
        <el-select
          v-model="searchForm.categoryId"
          placeholder="全部"
          clearable
          style="width: 160px"
          filterable
        >
          <el-option
            v-for="c in categoryFilterOptions"
            :key="c.id"
            :label="c.name"
            :value="Number(c.id)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 120px">
          <el-option :value="0" label="待处理" />
          <el-option :value="1" label="处理中" />
          <el-option :value="2" label="已回复" />
          <el-option :value="3" label="已关闭" />
        </el-select>
      </el-form-item>
      <el-form-item label="关键词">
        <el-input
          v-model="searchForm.keyword"
          placeholder="标题/内容/联系方式"
          clearable
          style="width: 220px"
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="list" v-loading="loading" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="72" align="center" />
      <el-table-column prop="categoryName" label="产品分类" width="120" align="center" />
      <el-table-column prop="title" label="标题" min-width="160" show-overflow-tooltip />
      <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip />
      <el-table-column label="联系人" width="100" align="center">
        <template #default="{ row }">{{ row.contactName || "—" }}</template>
      </el-table-column>
      <el-table-column label="电话" width="120" align="center">
        <template #default="{ row }">{{ row.contactPhone || "—" }}</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTag(row.status)">{{ statusText(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="提交时间" width="170" align="center" />
      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template #default="{ row }">
          <el-button text type="primary" size="small" @click="editRef.open(row.id)">处理</el-button>
          <el-button text type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @current-change="fetchList"
        @size-change="fetchList"
      />
    </div>

    <ComplaintEdit ref="editRef" @saved="fetchList" />

    <!-- 接口说明（列表页顶栏） -->
    <el-drawer v-model="apiDocVisible" title="投诉建议 — 接口说明" direction="rtl" size="520px">
      <el-scrollbar max-height="calc(100vh - 120px)">
        <div class="api-doc">
          <p class="api-doc-lead">
            以下为 go-platform 已提供的 HTTP 接口。请求前缀为当前环境配置的 API 地址（开发环境示例见下方）。
          </p>
          <p><strong>API 根地址</strong></p>
          <pre class="api-pre">{{ apiBase }}</pre>

          <h4>一、鉴权</h4>
          <p>除特别说明外，均需平台管理员登录后携带：</p>
          <pre class="api-pre">Authorization: Bearer &lt;token&gt;</pre>
          <p class="api-tip">Token 由 <code>POST /platform/login</code> 返回。列表、分类管理、处理投诉等均为平台端接口。</p>

          <h4>二、产品分类（配置「针对哪类产品提建议」）</h4>
          <ul>
            <li><code>GET /platform/complaintCategory/select</code> — 仅返回 <code>status=1</code> 的分类，供下拉/官网选分类用。</li>
            <li><code>GET /platform/complaintCategory/list</code> — 全部分类（管理列表）。</li>
            <li><code>POST /platform/complaintCategory</code> — 新增分类，Body JSON：<code>name</code>（必填）、<code>code</code>、<code>sort</code>、<code>status</code>。</li>
            <li><code>POST /platform/complaintCategory/:id</code> — 更新。</li>
            <li><code>DELETE /platform/complaintCategory/:id</code> — 软删。</li>
          </ul>

          <h4>三、提交投诉建议</h4>
          <p><code>POST /platform/complaint</code></p>
          <p>Body（JSON，camelCase）：</p>
          <pre class="api-pre">{
  "categoryId": 1,
  "title": "建议标题",
  "content": "详细描述",
  "contactName": "可选",
  "contactPhone": "可选",
  "contactEmail": "可选"
}</pre>
          <p>成功示例：<code>{ "code": 200, "msg": "success", "data": { "id": 1 } }</code></p>
          <p class="api-tip">若需在官网/小程序<strong>免登录</strong>提交，需在后端单独增加公开路由（当前接口与平台管理一致，需 Bearer）。</p>

          <h4>四、管理端（列表与处理）</h4>
          <ul>
            <li><code>GET /platform/complaint/list</code> — 分页。Query：<code>page</code>、<code>pageSize</code>、<code>categoryId</code>、<code>status</code>（0~3）、<code>keyword</code>。</li>
            <li><code>GET /platform/complaint/:id</code> — 详情。</li>
            <li><code>POST /platform/complaint/:id</code> — 更新状态、回复等：<code>status</code>、<code>replyContent</code>、<code>remark</code>、<code>categoryId</code> 等。</li>
            <li><code>DELETE /platform/complaint/:id</code> — 软删。</li>
          </ul>
          <p><strong>状态</strong>：<code>0</code> 待处理 · <code>1</code> 处理中 · <code>2</code> 已回复 · <code>3</code> 已关闭</p>

          <h4>五、数据表</h4>
          <p><code>yz_system_complaint_category</code>、<code>yz_system_platform_complaint</code></p>
        </div>
      </el-scrollbar>
    </el-drawer>

    <!-- 产品分类管理 -->
    <el-dialog v-model="categoryVisible" title="投诉建议 — 产品分类" width="640px" destroy-on-close>
      <div class="cat-toolbar">
        <el-button type="primary" size="small" @click="openCatForm()">新增分类</el-button>
        <el-button size="small" @click="loadCategoryList">刷新</el-button>
      </div>
      <el-table :data="categoryRows" v-loading="catLoading" border size="small" style="margin-top: 12px">
        <el-table-column prop="id" label="ID" width="64" align="center" />
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column prop="code" label="编码" width="100" />
        <el-table-column prop="sort" label="排序" width="72" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? "启用" : "禁用" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center">
          <template #default="{ row }">
            <el-button text type="primary" size="small" @click="openCatForm(row)">编辑</el-button>
            <el-button text type="danger" size="small" @click="handleCatDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      v-model="catFormVisible"
      :title="catForm.id ? '编辑分类' : '新增分类'"
      width="420px"
      append-to-body
    >
      <el-form :model="catForm" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="catForm.name" placeholder="如：官网、租户后台" />
        </el-form-item>
        <el-form-item label="编码">
          <el-input v-model="catForm.code" placeholder="可选" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="catForm.sort" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="catForm.status">
            <el-radio-button :value="1">启用</el-radio-button>
            <el-radio-button :value="0">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="catFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="catSaving" @click="saveCategory">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Refresh, Collection, Document } from "@element-plus/icons-vue";
import {
  getComplaintList,
  deleteComplaint,
  getComplaintCategoryList,
  createComplaintCategory,
  updateComplaintCategory,
  deleteComplaintCategory,
} from "@/api/complaint";
import ComplaintEdit from "./components/edit.vue";

const editRef = ref(null);
const apiDocVisible = ref(false);
const apiBase = import.meta.env.VITE_API_BASE_URL || "";
const loading = ref(false);
const list = ref([]);
const categoryFilterOptions = ref([]);

const searchForm = reactive({
  categoryId: null,
  status: null,
  keyword: "",
});

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0,
});

const categoryVisible = ref(false);
const catLoading = ref(false);
const categoryRows = ref([]);
const catFormVisible = ref(false);
const catSaving = ref(false);
const catForm = reactive({
  id: 0,
  name: "",
  code: "",
  sort: 0,
  status: 1,
});

function statusText(s) {
  const m = { 0: "待处理", 1: "处理中", 2: "已回复", 3: "已关闭" };
  return m[s] ?? String(s);
}

function statusTag(s) {
  if (s === 2) return "success";
  if (s === 3) return "info";
  if (s === 1) return "warning";
  return "";
}

async function loadCategoryFilter() {
  const res = await getComplaintCategoryList();
  if (res?.code === 200 && Array.isArray(res.data)) {
    categoryFilterOptions.value = res.data;
  }
}

async function fetchList() {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword || undefined,
    };
    if (searchForm.categoryId != null && searchForm.categoryId !== "") {
      params.categoryId = searchForm.categoryId;
    }
    if (searchForm.status !== null && searchForm.status !== "") {
      params.status = searchForm.status;
    }
    const res = await getComplaintList(params);
    if (res?.code === 200 && res.data) {
      list.value = res.data.list || [];
      pagination.total = res.data.total ?? 0;
    } else {
      list.value = [];
      ElMessage.error(res?.msg || "加载失败");
    }
  } finally {
    loading.value = false;
  }
}

function handleSearch() {
  pagination.page = 1;
  fetchList();
}

function resetSearch() {
  searchForm.categoryId = null;
  searchForm.status = null;
  searchForm.keyword = "";
  pagination.page = 1;
  fetchList();
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(`确定删除「${row.title}」吗？`, "提示", { type: "warning" });
  } catch {
    return;
  }
  const res = await deleteComplaint(row.id);
  if (res?.code === 200) {
    ElMessage.success("已删除");
    fetchList();
  } else {
    ElMessage.error(res?.msg || "删除失败");
  }
}

function openCategoryDialog() {
  categoryVisible.value = true;
  loadCategoryList();
}

async function loadCategoryList() {
  catLoading.value = true;
  try {
    const res = await getComplaintCategoryList();
    if (res?.code === 200 && Array.isArray(res.data)) {
      categoryRows.value = res.data;
    }
  } finally {
    catLoading.value = false;
  }
}

function openCatForm(row) {
  if (row) {
    catForm.id = row.id;
    catForm.name = row.name || "";
    catForm.code = row.code || "";
    catForm.sort = row.sort ?? 0;
    catForm.status = row.status ?? 1;
  } else {
    catForm.id = 0;
    catForm.name = "";
    catForm.code = "";
    catForm.sort = 0;
    catForm.status = 1;
  }
  catFormVisible.value = true;
}

async function saveCategory() {
  if (!catForm.name.trim()) {
    ElMessage.warning("请填写名称");
    return;
  }
  catSaving.value = true;
  try {
    const body = {
      name: catForm.name.trim(),
      code: catForm.code?.trim() || undefined,
      sort: catForm.sort,
      status: catForm.status,
    };
    let res;
    if (catForm.id) {
      res = await updateComplaintCategory(catForm.id, body);
    } else {
      res = await createComplaintCategory(body);
    }
    if (res?.code === 200) {
      ElMessage.success("已保存");
      catFormVisible.value = false;
      await loadCategoryList();
      await loadCategoryFilter();
    } else {
      ElMessage.error(res?.msg || "失败");
    }
  } finally {
    catSaving.value = false;
  }
}

async function handleCatDelete(row) {
  try {
    await ElMessageBox.confirm(`删除分类「${row.name}」？已有投诉引用时请谨慎。`, "提示", { type: "warning" });
  } catch {
    return;
  }
  const res = await deleteComplaintCategory(row.id);
  if (res?.code === 200) {
    ElMessage.success("已删除");
    loadCategoryList();
    loadCategoryFilter();
  } else {
    ElMessage.error(res?.msg || "删除失败");
  }
}

onMounted(() => {
  loadCategoryFilter();
  fetchList();
});
</script>

<style scoped>
.container-box {
  padding: 16px;
}
.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header-actions {
  display: flex;
  gap: 8px;
}
.search-form {
  margin-bottom: 12px;
}
.pager {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
.cat-toolbar {
  display: flex;
  gap: 8px;
}

.api-doc {
  padding-right: 12px;
  font-size: 13px;
  line-height: 1.6;
  color: var(--el-text-color-regular);
}
.api-doc h4 {
  margin: 18px 0 8px;
  font-size: 14px;
  color: var(--el-text-color-primary);
}
.api-doc ul {
  margin: 8px 0;
  padding-left: 1.2em;
}
.api-doc code {
  font-size: 12px;
  padding: 0 4px;
  background: var(--el-fill-color-light);
  border-radius: 4px;
}
.api-pre {
  margin: 8px 0;
  padding: 10px 12px;
  font-size: 12px;
  line-height: 1.5;
  background: var(--el-fill-color-light);
  border-radius: 6px;
  overflow-x: auto;
  white-space: pre-wrap;
  word-break: break-all;
}
.api-doc-lead {
  margin: 0 0 12px;
}
.api-tip {
  margin-top: 8px;
  padding: 8px 10px;
  font-size: 12px;
  background: var(--el-color-info-light-9);
  border-radius: 6px;
  color: var(--el-text-color-secondary);
}
</style>
