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

const router = express.Router();

router.post("/query", async (req, res) => {
  const findUsers = await curd({ entity: User, req }).query();
  if (!findUsers.length) return res.send({ code: 200, data: [] });
  // 过滤密码
  findUsers.map((item) => {
    // @ts-ignore
    delete item.pwd;
    return item;
  });

  return res.send({
    code: 200,
    data: {
      list: findUsers,
    },
  });
});

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

router.post("/add", async (req, res) => {
  const connection = getConnection();
  const bodyData = req.body;

  if (!bodyData.name?.length)
    return res.send({ code: 502, msg: "用户名是必须的！" });

  const userRep = connection.getRepository(User);
  const findUser = await userRep.findOne({ name: bodyData.name });

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

  let userInstance = new User();
  userInstance = { ...userInstance, ...bodyData };
  userInstance.createDate = userInstance.createDate || new Date();
  userInstance.updateDate = userInstance.updateDate || new Date();
  userInstance.pwd = "E10ADC3949BA59ABBE56E057F20F883E"; // 默认用户密码123456
  userInstance.birthday = dayjs(userInstance.birthday).format(
    "YYYY-MM-DD HH:mm:ss"
  ); // 用户默认生日

  await userRep.save(userInstance);

  return res.send({
    code: 200,
    msg: "用户注册成功！",
  });
});

router.post("/update", async (req, res, next) => {
  if (!req.body.id)
    return res.send({ code: 502, msg: "未传入用户ID，请检查数据！" });
  if (!req.body.pwd) delete req.body.pwd;
  const findUser = await curd({ entity: User, req }).update();

  return res.send({
    code: 200,
    msg: "用户修改成功！",
    data: {
      userInfo: findUser,
    },
  });
});

router.get("/delete", async (req, res) => {
  const connection = getConnection();
  const userRep = connection.getRepository(User);
  const { id } = req.query;

  const findUser = await userRep.findOne(id as string);

  if (findUser) {
    await userRep.remove(findUser);
    return res.send({
      code: 200,
      msg: "用户删除成功！",
    });
  } else {
    return res.send({
      code: 401,
      msg: "要删除的用户不存在！",
    });
  }
});

router.get("/resetPwd", async (req, res) => {
  let userRep = getConnection().getRepository(User);
  let { id } = req.query;
  let findUser = await userRep.findOne(id as string);

  if (findUser) {
    findUser.pwd = "E10ADC3949BA59ABBE56E057F20F883E"; // 默认用户密码123456
    await userRep.save(findUser);
    return res.send({ code: 200, msg: "用户密码重置成功！" });
  } else {
    return res.send({ code: 500, msg: "用户不存在！" });
  }
});

export default router;
