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

let router = express.Router();

router.get("/list", async (req, res) => {
  let data = await pagination(Role, req);
  return res.send({
    code: 200,
    data,
  });
});

router.post("/add", async (req, res) => {
  let body = req.body;
  let roleRep = getConnection().manager.getRepository(Role);
  let findRole = await roleRep.findOne({ where: { name: body.name } });
  if (findRole) return res.send({ code: 500, msg: "角色名已存在！" });

  await curd({ entity: Role, req }).add();

  return res.send({ code: 200, msg: "角色添加成功！" });
});

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

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

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

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

router.post("/update", async (req, res, next) => {
  if (!req.body.id)
    return res.send({ code: 502, msg: "未传入角色ID，请检查数据！" });

  const bodyData = req.body;

  const roleRep = getConnection().manager.getRepository(Role);
  let findRole = await roleRep.findOne({ where: { id: bodyData.id } });

  findRole = { ...findRole, ...bodyData };
  findRole.updateDate = new Date();

  await roleRep.save(findRole);

  return res.send({
    code: 200,
    msg: "角色修改成功！",
    data: findRole,
  });
});

export default router;
