import * as express from "express";
import { getConnection } from "typeorm";
import ServiceCategory from "../../entity/ServiceCategory";
import curd from "@/lib/curd/curd";

const router = express.Router();

router.get("/list", async (req, res) => {
  req.body.pageSize = "1000";
  req.query.pageSize = "1000";

  try {
    if (req.query.all) {
      req.body.pageSize = "1000";
      req.query.pageSize = "1000";
      const result = await curd({ entity: ServiceCategory, req }).queryList();
      return res.send({ code: 200, data: result });
    }
    // 查询数据库中的所有分类数据
    const result = await curd({ entity: ServiceCategory, req }).queryList();
    // 将数据转换为树形结构
    const buildTree = (items, parentId = 0) => {
      return items
        .filter((item) => item.parentId === parentId)
        .map((item) => ({
          ...item,
          children: buildTree(items, item.id), // 递归构建子节点
        }));
    };

    const treeData = buildTree(result.list);

    result.list = treeData;

    res.send({ code: 200, data: result });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

router.post("/query", async (req, res) => {
  try {
    // 查询数据库中的所有分类数据
    const result = await curd({ entity: ServiceCategory, req }).queryList();

    // 将数据转换为树形结构
    // const buildTree = (items, parentId = 0) => {
    //   return items
    //     .filter((item) => item.parentId === parentId)
    //     .map((item) => ({
    //       ...item,
    //       children: buildTree(items, item.id), // 递归构建子节点
    //     }));
    // };

    // const treeData = buildTree(result.list);

    // result.list = treeData;

    res.send({ code: 200, data: result });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

// 添加商品分类
router.post("/add", async (req, res) => {
  const { name } = req.body;

  if (!name) {
    return res.send({ code: 400, msg: "商品分类名称不能为空！" });
  }

  try {
    const connection = getConnection();
    const categoryRepository = connection.getRepository(ServiceCategory);

    // 校验是否已存在相同名称的商品分类
    const existingCategory = await categoryRepository.findOne({
      where: { name },
    });

    if (existingCategory) {
      return res.send({ code: 400, msg: "商品分类名称已存在，请勿重复添加！" });
    }

    let newCategory = new ServiceCategory();
    newCategory = {
      ...newCategory,
      ...req.body,
    };

    await categoryRepository.save(newCategory);
    res.send({ code: 200, msg: "商品分类添加成功", data: newCategory });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

// 更新商品分类
router.post("/update", async (req, res) => {
  const { id } = req.body;

  if (!id) {
    return res.send({ code: 400, msg: "商品分类ID不能为空！" });
  }

  try {
    const connection = getConnection();
    const categoryRepository = connection.getRepository(ServiceCategory);

    // 查找商品分类
    let category = await categoryRepository.findOne(Number(id));
    if (!category) {
      return res.send({ code: 400, msg: "商品分类不存在！" });
    }

    // 更新字段
    category = {
      ...category,
      ...req.body,
    };

    await categoryRepository.save(category);
    res.send({ code: 200, msg: "商品分类更新成功", data: category });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

// 删除商品分类
router.get("/delete", async (req, res) => {
  const { id } = req.query;

  if (!id) {
    return res.send({ code: 400, msg: "商品分类ID不能为空！" });
  }

  try {
    const connection = getConnection();
    const categoryRepository = connection.getRepository(ServiceCategory);

    const category = await categoryRepository.findOne(Number(id));
    if (!category) {
      return res.send({ code: 400, msg: "商品分类不存在！" });
    }

    await categoryRepository.remove(category);
    res.send({ code: 200, msg: "商品分类删除成功" });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

export default router;
