<template>
  <div class="category-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>分类管理</span>
          <el-button type="primary" :icon="Plus" @click="handleCategoryAdd">
            新增分类
          </el-button>
        </div>
      </template>

      <el-table
        :data="categoryList"
        v-loading="loading"
        stripe
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="分类标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="categoryList.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无分类记录" />
      </div>
    </el-card>

    <el-dialog
      v-model="categoryDialogVisible"
      :title="isEdit ? '编辑分类' : '新增分类'"
      width="700px"
      :close-on-click-modal="false"
      @close="handleCategoryClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="分类标题" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入分类标题"
            clearable
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";

import { getModuleCategory,editModuleCategory } from "@/api/moduleCenter";

interface Category {
  id: number;
  title: string;
  module_name: string;
  module_id?: number;
  status: number;
}

interface ModuleOption {
  id: number;
  name: string;
}

const loading = ref(false);
const categoryList = ref<Category[]>([]);
const categoryDialogVisible = ref(false);
const submitLoading = ref(false);
const isEdit = ref(false);
const editId = ref<number>(0);

const formRef = ref<FormInstance>();

const formData = reactive({
  title: "",
  module_id: null as number | null,
  status: 1
});

const moduleOptions = ref<ModuleOption[]>([]);

const formRules: FormRules = {
  title: [
    { required: true, message: "请输入分类标题", trigger: "blur" }
  ],
  module_id: [
    { required: true, message: "请选择所属模块", trigger: "change" }
  ],
  status: [
    { required: true, message: "请选择状态", trigger: "change" }
  ]
};

const getStatusText = (status: number) => {
  const map: Record<number, string> = {
    0: "禁用",
    1: "启用"
  };
  return map[status] || "未知";
};

const getStatusType = (status: number) => {
  const map: Record<number, any> = {
    0: "info",
    1: "success",
    2: "warning"
  };
  return map[status] || "info";
};

const formatDate = (date: string) => {
  if (!date) return "-";
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  const hours = String(d.getHours()).padStart(2, "0");
  const minutes = String(d.getMinutes()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

const handleCategoryAdd = () => {
  isEdit.value = false;
  editId.value = 0;
  formData.title = "";
  formData.module_id = null;
  formData.status = 1;
  categoryDialogVisible.value = true;
  fetchModuleOptions();
};

const handleEdit = (row: Category) => {
  isEdit.value = true;
  editId.value = row.id;
  formData.title = row.title;
  formData.module_id = row.module_id || null;
  formData.status = row.status;
  categoryDialogVisible.value = true;
  fetchModuleOptions();
};

const handleView = (row: Category) => {
  ElMessage.info("查看分类详情功能开发中");
};

const handleDelete = (row: Category) => {
  ElMessageBox.confirm(`确定要删除分类"${row.title}"吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      // TODO: 调用删除接口
      // await deleteCategory(row.id);
      
      ElMessage.success("删除成功");
      handleRefresh();
    } catch (error) {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }).catch(() => {});
};

const handleCategoryClose = () => {
  formRef.value?.resetFields();
  isEdit.value = false;
  editId.value = 0;
  categoryDialogVisible.value = false;
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;
      try {
        const data = {
          title: formData.title,
          status: formData.status
        };
        
        if (isEdit.value) {
          data.id = editId.value;
          await editModuleCategory(data);
          ElMessage.success("编辑成功");
        } else {
          await editModuleCategory(data);
          ElMessage.success("添加成功");
        }
        handleCategoryClose();
        handleRefresh();
      } catch (error) {
        console.error(isEdit.value ? "编辑失败:" : "添加失败:", error);
        ElMessage.error(isEdit.value ? "编辑失败" : "添加失败");
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const handleRefresh = () => {
  fetchCategoryList();
};

const fetchCategoryList = async () => {
  loading.value = true;
  try {
    const res = await getModuleCategory();
    if (res.code === 200 && res.data) {
      categoryList.value = res.data.list || [];
    }
  } catch (error) {
    console.error("获取分类列表失败:", error);
    ElMessage.error("获取分类列表失败");
  } finally {
    loading.value = false;
  }
};

const fetchModuleOptions = async () => {
  try {
    // TODO: 调用获取模块列表接口
    // const res = await getModules(0);
    // if (res.code === 200) {
    //   moduleOptions.value = res.data.list.map((item: any) => ({
    //     id: item.id,
    //     name: item.title
    //   }));
    // }
    moduleOptions.value = [
      { id: 1, name: "CMS内容管理" },
      { id: 2, name: "用户管理" },
      { id: 3, name: "数据分析" },
      { id: 4, name: "系统设置" }
    ];
  } catch (error) {
    console.error("获取模块列表失败:", error);
  }
};

onMounted(() => {
  fetchCategoryList();
});
</script>

<style scoped lang="less">
.category-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .empty-state {
    padding: 40px 0;
  }
}
</style>
