<template>
  <el-table :data="items" v-loading="loading" style="width: 100%">
    <el-table-column prop="question" label="问题" min-width="200" />
    <el-table-column prop="category_id" label="分类" width="140">
      <template #default="scope">
        {{ categoryMap[scope.row.category_id] || scope.row.category_id }}
      </template>
    </el-table-column>
    <el-table-column prop="version" label="版本" width="80" />
    <el-table-column prop="is_active" label="启用" width="80">
      <template #default="scope">
        <el-tag :type="scope.row.is_active ? 'success' : 'info'">{{ scope.row.is_active ? "是" : "否" }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="updated_at" label="更新时间" width="180" />
    <el-table-column label="操作" width="180">
      <template #default="scope">
        <el-button type="text" size="small" @click="view(scope.row)">查看</el-button>
        <PermissionAction v-if="canEdit" action="faq.edit">
          <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
        </PermissionAction>
        <PermissionAction v-if="canEdit" action="faq.edit">
          <el-button
            type="text"
            size="small"
            @click="toggle(scope.row)"
            :style="{ color: scope.row.is_active ? '#f56c6c' : '#67c23a' }"
          >
            {{ scope.row.is_active ? "停用" : "启用" }}
          </el-button>
        </PermissionAction>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { computed } from "vue";
import { useRouter } from "vue-router";
import { updateFaqItem } from "../api/faqs";
import type { FaqItem, FaqCategory } from "../api/faqs";
import PermissionAction from "./PermissionAction.vue";

const props = defineProps<{
  items: FaqItem[];
  categories: FaqCategory[];
  loading: boolean;
  canEdit: boolean;
}>();
const emit = defineEmits(["refresh", "edit"]);

const router = useRouter();

const categoryMap = computed(() =>
  props.categories.reduce<Record<string, string>>((acc, cur) => {
    acc[cur.id] = cur.name;
    return acc;
  }, {})
);

const view = (row: FaqItem) => {
  router.push(`/study/faq/${row.id}`);
};

const edit = (row: FaqItem) => {
  emit("edit", row);
};

const toggle = async (row: FaqItem) => {
  const target = !row.is_active;
  const ok = await ElMessageBox.confirm(`确认${target ? "启用" : "停用"}此 FAQ?`, "提示").catch(() => null);
  if (!ok) return;
  try {
    await updateFaqItem(row.id, { is_active: target });
    ElMessage.success("操作成功");
    emit("refresh");
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "操作失败");
  }
};
</script>
