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

const router = express.Router();

// 查询服务项目列表（支持分页）
// router.get("/list", async (req, res) => {
//   try {
//     const result = await curd({ entity: ServiceItem, req }).queryList();
//     res.send({ code: 200, data: result });
//   } catch (err) {
//     res.status(500).send({ code: 500, msg: err.message });
//   }
// });

router.get("/list", async (req, res) => {
  if (req.query.all) {
    req.body.pageSize = "1000";
    req.query.pageSize = "1000";
  }
  let data = await curd({ entity: ServiceItem, req }).queryList();
  return res.send({
    code: 200,
    data,
  });
});

router.post("/query", async (req, res) => {
  let data = await curd({ entity: ServiceItem, req }).queryList();
  return res.send({
    code: 200,
    data,
  });
});

// 添加服务项目
router.post("/add", async (req, res) => {
  const { name } = req.body;
  if (!name) {
    return res.send({ code: 400, msg: "服务项目名称不能为空！" });
  }
  const connection = getConnection();
  const itemRepository = connection.getRepository(ServiceItem);
  if (await itemRepository.findOne({ name })) {
    return res.send({ code: 400, msg: "服务项目名称已存在！" });
  }
  try {
    const newDeceased = await curd({ entity: ServiceItem, req }).add();
    res.send({ code: 200, msg: "服务项目添加成功", data: newDeceased });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

// 更新服务项目
router.post("/update", async (req, res) => {
  const { id, name } = req.body;

  if (!id) {
    return res.send({ code: 400, msg: "服务项目ID不能为空！" });
  }
  const connection = getConnection();
  const itemRepository = connection.getRepository(ServiceItem);
  try {
    // 查找服务项目
    let serviceItem = await itemRepository.findOne({ id });
    if (!serviceItem) {
      return res.send({ code: 400, msg: "服务项目不存在！" });
    }
    if (serviceItem.id !== id && serviceItem.name === name) {
      return res.send({ code: 400, msg: "服务项目名称已存在！" });
    }
    serviceItem = {
      ...serviceItem,
      ...req.body,
      parentId: req.body.parentId ?? 0,
    };

    await itemRepository.save(serviceItem);
    res.send({ code: 200, msg: "服务项目更新成功", data: serviceItem });
  } 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 itemRepository = connection.getRepository(ServiceItem);

    const item = await itemRepository.findOne(Number(id));
    if (!item) {
      return res.send({ code: 400, msg: "服务项目不存在！" });
    }

    await itemRepository.remove(item);
    res.send({ code: 200, msg: "服务项目删除成功" });
  } catch (err) {
    res.status(500).send({ code: 500, msg: err.message });
  }
});

export default router;
