import * as express from "express";
import { Request, Response } from "express";
import { getConnection } from "typeorm";
import User from "../../entity/User";
import { Role } from "../../entity/Role";
import { SystemMenue } from "../../entity/SystemMenue";
import menueToTree from "../../lib/menueToTree";

const router = express.Router();
let jwt = require("jsonwebtoken");

const secretKey = "myNameIsLiJiaTu";

// 递归获取所有父级菜单的ID
async function getAllParentIds(menuIds: number[]): Promise<number[]> {
  const parentIds = new Set<number>();

  const getParents = async (id: number) => {
    let menueRep = getConnection().getRepository(SystemMenue);
    const menu = await menueRep.findOne({ where: { id } });
    if (menu && menu.parentId !== 0) {
      parentIds.add(menu.parentId);
      await getParents(menu.parentId);
    }
  };

  await Promise.all(menuIds.map((id) => getParents(id)));
  return Array.from(parentIds);
}

router.post("/", async (req: Request, res: Response) => {
  const { name, pwd } = req.body;

  const connection = getConnection();
  const user = connection.getRepository(User);
  if (!(await user.findAndCount())[0].length && name === "admin") {
    let userInstance = new User();
    userInstance = {
      ...userInstance,
      name: "admin",
      pwd: "E10ADC3949BA59ABBE56E057F20F883E",
      role: "1",
      userState: 1,
    };
    userInstance.createDate = userInstance.createDate || new Date();
    userInstance.updateDate = userInstance.updateDate || new Date();

    await connection.getRepository(User).save(userInstance);
  }

  const findUser = await user.findOne({ name });
  if (!findUser) return res.send("该用户不存在，请检查！");

  if (findUser && findUser.pwd !== pwd) return res.send("密码错误，请检查！");
  if (findUser.userState === 0 && findUser.name !== "admin")
    return res.send({ code: 500, msg: "该账号被禁止使用，请联系管理员！" });

  let userRole = findUser.role;
  let roleRep = connection.getRepository(Role);

  if (findUser.name === "admin") {
    let role = await roleRep.findOne({ where: { id: Number(userRole) } });
    role.values = (
      await connection.getRepository(SystemMenue).findAndCount()
    )[0]
      .map((item) => item.id.toString())
      .join(",");
    if (role.values.length !== findUser.role.length) {
      await roleRep.save(role);
    }
  }
  let roleRes = await roleRep
    .createQueryBuilder("role")
    .where("role.id IN (:...userRole)", { userRole: userRole.split(",") })
    .getOne();
  if (roleRes) {
    let menueRep = connection.getRepository(SystemMenue);
    // 在原有查询中增加父级查询
    const selectedMenuIds = roleRes.values.split(",").map(Number); // [34,33,24]
    const parentIds = await getAllParentIds(selectedMenuIds); // 获取所有父级ID（如26）

    const finalMenuIds = Array.from(
      new Set([...selectedMenuIds, ...parentIds])
    ); // 合并选中的ID和父级ID

    let menueList = await menueRep
      .createQueryBuilder("system_menue")
      .where("system_menue.id IN (:...menue)", { menue: finalMenuIds })
      .getMany();

    findUser["routerMenue"] = menueToTree(menueList);
  } else {
    findUser["routerMenue"] = [];
  }

  // 登录成功，生成 JWT
  const token = jwt.sign({ userId: findUser.id }, secretKey, {
    expiresIn: "1h",
  });
  const refreshToken = jwt.sign({ userId: findUser.id }, secretKey, {
    expiresIn: "1d",
  });

  // 过滤密码
  delete findUser.pwd;
  return res.send({
    code: 200,
    msg: "登录成功！",
    data: {
      token: "Bearer " + token,
      refreshToken,
      user: findUser,
    },
  });
});

export default router;
