var express = require("express");
var app = express();
var router = express.Router();
var { Config } = require("./lib/Config");
var weChatMini = require("./utils/wechatMini.js");
var QyWeChat = require("./utils/qyWechat.js");
var QyWeChatLocal = require("./utils/qyWechatLocal.js");
var QyWeChatBhu = require("./utils/qyWechatBhu.js");
var path = require("path");
var fs = require("fs");

var WeChat = require("./utils/wechat.js");
var WeShao = require("./utils/weshao.js");
var JmuSSO = require("./utils/jmuSSO.js");
var HnustSSO = require("./utils/hnustSSO.js");
var DD = require("./utils/dd.js");
var Campus = require("./utils/todayCampus.js");
var sitSSO = require("./utils/sitSSO");
const YunSchool = require("./utils/yunSchool.js");

/* 
1. 拿accessToken，并缓存起来
2. 接收code
3. 请求userId
4. 请求用户信息
*/

var qyWechat;
var wechat = new WeChat();
var weshao = new WeShao();
var jmuSSO = new JmuSSO();
var hnustSSO = new HnustSSO();
var dd = new DD();
var campus = new Campus();
var yunSchool = new YunSchool();

switch (Config.qyWechatType) {
    case "local":
        qyWechat = new QyWeChatLocal();
        break;
    case "bhu":
        qyWechat = new QyWeChatBhu();
        break;
    default:
        qyWechat = new QyWeChat();
        break;
}

if (Config.corpid) {
    qyWechat.GetAccessToken().then(
        (success) => {
            console.log("初始化获取accessToken成功");
        },
        (failure) => {
            console.log("初始化获取accessToken失败");
        },
    );
}

// if (Config.yunSchoolAppid && Config.yunSchoolSecret) {

//     yunSchool.GetAccessToken().then(
//         (success) => {
//             console.log("初始化获取云校 accessToken 成功");
//         },
//         (failure) => {
//             console.log("初始化获取云校 accessToken 失败");
//         },
//     );
// }

if (Config.ddAppKey) {
    dd.GetAccessToken().then(
        (success) => {
            console.log("初始化获取accessToken成功");
        },
        (failure) => {
            console.log("初始化获取accessToken失败");
        },
    );
}

if (Config.campusClientId) {
    campus.GetAccessToken().then(
        (success) => {
            console.log("初始化今日校园 accessToken 成功");
        },
        (failure) => {
            console.log("初始化今日校园 accessToken 失败");
        },
    );
}

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Credentials", true);
    res.header(
        "Access-Control-Allow-Methods",
        "PUT, GET, POST, DELETE, OPTIONS",
    );
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    next();
});

router.get("/qyWechatLogin", function (req, res, next) {
    let query = req.query;
    if (query.code) {
        let code = query.code;
        console.log(code);
        qyWechat.GetUserId(code).then((r) => {
            qyWechat.GetUserInfo().then((r) => {
                res.send(r);
            });
        });
    } else {
        res.send("请求失败");
    }
});

router.get("/yunSchoolLogin", async function (req, res, next) {
    try {
        let query = req.query;
        if (query.code) {
            let code = query.code;
            const resToken = await yunSchool.GetAccessToken(code);
            const info = await yunSchool.GetUserInfo(code);
            res.send({code:1,...info});
        } else {
            res.send("请求失败");
        }
    } catch (error) {
        res.send({code:0,msg:error});
    }
});

router.get("/wechatLogin", function (req, res, next) {
    let query = req.query;
    console.log(query.code);
    if (query.code) {
        let code = query.code;
        wechat
            .GetAccessToken(code)
            .then(
                (success) => {
                    console.log("初始化获取accessToken成功");
                },
                (failure) => {
                    console.log("初始化获取accessToken失败");
                },
            )
            .then(() => {
                wechat.GetUserInfo().then(
                    (info) => {
                        res.send(info);
                    },
                    (failure) => {
                        console.log("获取用户信息失败");
                    },
                );
            });
    } else {
        res.send("code is null");
    }
});

router.get("/ddLogin", function (req, res, next) {
    let query = req.query;
    if (query.code) {
        let code = query.code;
        console.log(code);
        dd.GetUserId(code).then((r) => {
            dd.GetUserInfo().then((r) => {
                res.send(r);
            });
        });
    } else {
        res.send("请求失败");
    }
});

router.get("/weshaoLogin", function (req, res, next) {
    let query = req.query;
    console.log(query.code);
    if (query.code && query.redirect_uri) {
        let code = query.code;
        let redirectUri = query.redirect_uri;
        weshao
            .GetToken(code, redirectUri)
            .then(
                (success) => {
                    console.log("初始化获取accessToken成功");
                },
                (failure) => {
                    console.log("初始化获取accessToken失败");
                },
            )
            .then(() => {
                weshao.GetUserInfo().then(
                    (info) => {
                        res.send(info);
                    },
                    (failure) => {
                        console.log("获取用户信息失败");
                    },
                );
            });
    } else {
        res.send("code is null");
    }
});

router.get("/fwQyUserInfo", function (req, res, next) {
    let query = req.query;
    if (query.token) {
        let token = query.token;
        qyWechat.getFwQywxUser(token).then((r) => {
            res.send(r);
        });
    } else {
        res.send("请求失败");
    }
});

router.get("/wechatUserInfo", function (req, res, next) {
    let query = req.query;
    console.log(query.code);
    if (query.code) {
        let code = query.code;
        wechat.jsCode2Session(code).then((r) => {
            console.log(r);
            res.send(r);
        });
    } else {
        res.send("code is null");
    }
});

router.get("/getJsApiTicket", function (req, res, next) {
    qyWechat
        .getJsApiTicket()
        .then((r) => {
            res.send(r);
        })
        .catch((e) => {
            res.send(e);
        });
});

router.get("/wechatJsApiTicket", function (req, res, next) {
    wechat
        .getJsApiTicket()
        .then((r) => {
            res.send(r);
        })
        .catch((e) => {
            res.send(e);
        });
});

router.get("/ddJsApiTicket", function (req, res, next) {
    dd.getJsApiTicket()
        .then((r) => {
            res.send(r);
        })
        .catch((e) => {
            res.send(e);
        });
});

router.get("/jmu-login", function (req, res, next) {
    const redirectUrl = "http://10.9.1.8/fridayh5";
    const headers = req.headers;
    const query = req.query;
    const userToken =
        headers["userToken"] ||
        headers["usertoken"] ||
        query["userToken"] ||
        query["usertoken"];
    if (userToken) {
        jmuSSO
            .GetUserInfo(userToken)
            .then((user) => {
                console.log(user);
                if (user && user.sub) {
                    res.redirect(redirectUrl + "?card_no=" + user.sub);
                } else {
                    res.send("获取用户信息失败");
                }
            })
            .catch((error) => {
                console.log("获取用户信息失败");
                console.log(error);
            });
    } else {
        res.send("userToken is null");
    }
});

router.get("/hnust-login", function (req, res, next) {
    const headers = req.headers;
    const query = req.query;
    const userToken =
        headers["userToken"] ||
        headers["usertoken"] ||
        query["userToken"] ||
        query["usertoken"];
    if (userToken) {
        hnustSSO
            .GetUserInfo(userToken)
            .then((user) => {
                console.log(user);
                if (user && user.sub) {
                    res.send({ refNo: user.sub });
                } else {
                    res.send("获取用户信息失败");
                }
            })
            .catch((error) => {
                console.log("获取用户信息失败");
                console.log(error);
            });
    } else {
        res.send("userToken is null");
    }
});
router.get("/sitLogin", async function (req, res, next) {
    const query = req.query;
    const code = query.code;
    if (code) {
        try {
            const result = await sitSSO.sitLogin(code);
            if (result.data && result.code == 0) {
                res.send(result.data);
            } else {
                res.send(result.msg);
            }
        } catch (err) {
            res.send(`ERROR:${JSON.stringify(err)}`);
        }
    } else {
        res.send("userCode is null");
    }
});

router.get("/campusLogin", async function (req, res, next) {
    const query = req.query;
    const url = query.url;
    if (url) {
        try {
            const result = await campus.GetJsSdkConfig(url);
            if (result) {
                res.send(result.data);
            } else {
                res.send(result.msg);
            }
        } catch (err) {
            res.send(`ERROR:${JSON.stringify(err)}`);
        }
    } else {
        res.send("url is null");
    }
});

router.get("/wechatMiniCode",async function (req, res, next) {
    const query = req.query;
    const eqId = query.eqId;
    if (eqId) {
        try {
            const result = await weChatMini.get_equipment_code(eqId);
            if (result) {
                res.send(result);
            } else {
                res.send("获取小程序码失败");
            }
        } catch (err) {
            res.send(`ERROR:${JSON.stringify(err)}`);
        }
    } else {
        res.send("eqId is null");
    }
})

app.use('/qrcodes', express.static(path.join(__dirname, 'qrcodes')));

// 添加获取图片接口
router.get("/getQRImage", function (req, res, next) {
    const query = req.query;
    const imageName = query.name;
    
    if (!imageName) {
        return res.status(400).send("图片名称不能为空");
    }
    
    // 图片存储路径
    const imagePath = path.join(__dirname, 'qrcodes', imageName);
    
    // 检查文件是否存在
    fs.access(imagePath, fs.constants.F_OK, (err) => {
        if (err) {
            return res.status(404).send("找不到请求的图片");
        }
        
        // 返回图片
        res.sendFile(imagePath);
    });
});





app.use("/", router);

app.listen(3080);
