import * as express from "express";
import login from "./login/login";
import user from "./user/user";
import systemMenue from "./system-menue/system-menue";
import role from "./role/role";
import deceased from "./deceased/deceased";
import serviceItem from "./serviceList/serviceItem";
import serviceCategory from "./serviceList/serviceCategory";
import deceasedRetail from "./deceasedRetail/deceasedRetail";
import checkout from "./checkout/checkout";
import retailCheckout from "./retailCheckout/retailCheckout";
import noDeceasedRetail from "./noDeceasedRetail/noDeceasedRetail";
import cancleExamine from "./cancle/cancleExamine";
import CheckoutRetail from "./CheckoutRetail/CheckoutRetail";
import publicList from "./public/public";
import Stats from "./stats/stats";

let jwt = require("jsonwebtoken");

let router = express.Router();
const secretKey = "myNameIsLiJiaTu";

// 统一请求入口
router.use("/", (req, res, next) => {
  const token = req.headers.authorization;
  const refreshToken = req.headers.refreshtoken;
  // 非登录并且无token证明用户未登录，禁止操作，不需要这个，注释即可
  if (!token && !refreshToken && req.path !== "/login")
    return res.send({ code: 401, msg: "未登录，禁止操作访问！" });

  if (token) {
    jwt.verify(token, secretKey, (err, decoded) => {
      if (err) {
        if (!refreshToken) {
          return res.status(401).send({ code: 401, msg: "请重新登录" });
        }
        jwt.verify(refreshToken, secretKey, (refErr, refDecoded) => {
          if (refErr) {
            return res
              .status(401)
              .send({ code: 401, msg: "登录已失效，请重新登录。" });
          } else {
            let userId = refDecoded.userId;
            const newToken = jwt.sign({ userId }, secretKey, {
              expiresIn: "1h",
            });
            res.setHeader("refreshToken", newToken);
            next();
          }
        });
      } else {
        next();
      }
    });
  } else {
    next();
  }
});
router.use("/login", login);
router.use("/user", user);
router.use("/system-menue", systemMenue);
router.use("/role", role);
router.use("/public/", publicList);
router.use("/deceased", deceased);
router.use("/deceased-retail", deceasedRetail);
router.use("/service-item", serviceItem);
router.use("/service-category", serviceCategory);
router.use("/checkout", checkout);
router.use("/retail-checkout", retailCheckout);
router.use("/no-deceased-retail", noDeceasedRetail);
router.use("/cancel", cancleExamine);
router.use("/checkout-retail", CheckoutRetail);
router.use("/stats", Stats);

export default router;
