<template>
  <el-table :data="items" v-loading="loading" style="width: 100%" @row-click="onRowClick">
    <el-table-column prop="question" label="问题" min-width="200">
      <template #default="scope">
        <el-link type="primary" :underline="false" class="question-link">
          {{ scope.row.question }}
        </el-link>
      </template>
    </el-table-column>
    <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="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">
      <template #default="scope">{{ displayDateTime(scope.row.updated_at) }}</template>
    </el-table-column>
    <el-table-column prop="status" label="状态" width="120">
      <template #default="scope">
        <el-tag :type="statusTagType(scope.row.status)" size="small">{{ statusLabel(scope.row.status) }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180">
      <template #default="scope">
        <el-button v-if="canDelete(scope.row)" type="text" size="small" class="danger" @click="remove(scope.row)">
          删除
        </el-button>
        <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 { deleteFaqItem, updateFaqItem } from "../api/faqs";
import type { FaqItem, FaqCategory } from "../api/faqs";
import PermissionAction from "./PermissionAction.vue";
import { displayDateTime } from "../utils/display";
import { useAuthStore } from "../store/auth";

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

const router = useRouter();
const auth = useAuthStore();

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

const view = (row: FaqItem) => {
  router.push(`/knowledge/medical-consult/${row.id}`);
};

const onRowClick = (row: FaqItem, column: any, event: MouseEvent) => {
  if (column?.property !== "question") return;
  view(row);
};

const statusLabel = (status?: string) => {
  if (status === "RESOLVED") return "已解决";
  if (status === "PROCESSING") return "处理中";
  return "待回答";
};

const statusTagType = (status?: string) => {
  if (status === "RESOLVED") return "success";
  if (status === "PROCESSING") return "warning";
  return "info";
};

const canDelete = (row: FaqItem) => props.canEdit || row.created_by === auth.user?.id;


const toggle = async (row: FaqItem) => {
  const target = !row.is_active;
  const ok = await ElMessageBox.confirm(`确认${target ? "启用" : "停用"}此咨询?`, "提示").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 || "操作失败");
  }
};

const remove = async (row: FaqItem) => {
  const ok = await ElMessageBox.confirm(`确认删除咨询「${row.question}」？`, "提示").catch(() => null);
  if (!ok) return;
  try {
    await deleteFaqItem(row.id);
    ElMessage.success("问题已删除");
    emit("refresh");
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "删除失败");
  }
};
</script>

<style scoped>
.danger {
  color: #f56c6c;
}
.question-link {
  cursor: pointer;
}
</style>
