import * as express from "express";
import { getConnection } from "typeorm";
import { SystemMenue } from "../../entity/SystemMenue";
import pagination from "../../lib/pagination/pagination";
import dayjs from "dayjs";
import { filterObjEmptyVal } from "../../util/globalMethods";

const router = express.Router();

router.get("/list", async (req, res) => {
  let isAll = req.query.all;
  req.query.pageSize = "1000";
  req.body.pageSize = "1000";
  let data = await pagination(SystemMenue, req);
  let dataList = [];
  for (let i = 0; i < data.list.length; i++) {
    let item = data.list[i];
    item.children = [];

    for (let j = 0; j < data.list.length; j++) {
      let tempItem = data.list[j];
      if (tempItem.parentId === item.id) {
        item.children.push(tempItem);
      }
    }
    // 只添加父级
    if (!item.parentId || isAll) dataList.push(item);
  }
  data.list = dataList;
  data.total = dataList.length;
  return res.send({
    code: 200,
    data,
  });
});

router.post("/query", async (req, res) => {
  let params = req.body;
  let data = await pagination(SystemMenue, req, filterObjEmptyVal(params));
  return res.send({
    code: 200,
    data,
  });
});

router.post("/add", async (req, res) => {
  let menueRep = getConnection().manager.getRepository(SystemMenue);
  let body = req.body;
  let findMenue = await menueRep.findOne({ where: { name: body.name } });

  if (findMenue) return res.send({ code: 403, msg: `${body.name}已经存在了` });

  let menueInstance = new SystemMenue();
  menueInstance = body;
  menueInstance.createDate = dayjs().format("YYYY-MM-DD HH:mm:ss");
  await menueRep.save(menueInstance);

  return res.send({
    code: 200,
    msg: "菜单增加成功！",
  });
});

router.post("/update", async (req, res) => {
  let menueRep = getConnection().manager.getRepository(SystemMenue);
  let body = req.body as SystemMenue;

  let filterMenue = await menueRep.findOne({ where: { name: body.name } });
  if (
    filterMenue &&
    filterMenue.id !== body.id &&
    body.name === filterMenue.name
  ) {
    return res.send({ code: 500, msg: "菜单名已经存在" });
  }

  let findMenue = await menueRep.findOne({ where: { id: body.id } });

  findMenue = { ...findMenue, ...body };
  findMenue.updateDate = dayjs().format("YYYY-MM-DD HH:mm:ss");

  await menueRep.save(findMenue);

  return res.send({
    code: 200,
    msg: "菜单修改成功！",
  });
});

router.get("/delete", async (req, res) => {
  let menueRep = getConnection().manager.getRepository(SystemMenue);
  let { id } = req.query;
  let findMnue = await menueRep.find({ where: { id } });

  if (!findMnue)
    return res.send({ code: 500, msg: "删除菜单不存在，请检查！" });

  await menueRep.remove(findMnue);
  return res.send({ code: 200, msg: "删除成功！" });
});

export default router;
