let Parse = global.Parse
const router = require('express').Router();
let bodyParser = require('body-parser')
const pgp = require('pg-promise')();

router.use(bodyParser.json({ limit: '10mb' }))
router.use(bodyParser.urlencoded({ extended: false }))

router.use("/test", async (req, res, next) => {
    res.json({
        code: 200,
        data: "test"
    })
})


router.post("/login", async (req, res, next) => {
    goWrong(res, "接口已停止维护");
    return
    let id = req.body.id;
    if (!id) {
        goWrong(res, "参数不完整，请检查");
        return
    }
    // 检查用户信息
    let query = new global.Parse.Query("_User");
    query.equalTo("objectId", id);
    let user = query.first({ useMasterKey: true });
    if (user?.id) {
        let token = await setMobileSessionToken(user)
        res.json({
            code: 200,
            msg: '登录成功',
            data: {
                userId: user.id,
                username: user.get("username"),
                mobile: user.get("mobile"),
                token: token?.get("sessionToken")
            }
        })
        return
    }
    goWrong(res, "用户不存在，请先注册")
})


router.post("/register", async (req, res, next) => {
    let company = req.body.company;
    let mobile = req.body.mobile;
    let code = req.body.code;
    let password = req.body.password
    if (!company || !mobile || !code) {
        goWrong(res, "参数不完整，请检查");
        return
    }
    // 检查用户信息
    let user;
    user = await getUserByMobile(mobile, company);
    if (user) {
        // goWrong(res, "用户已存在，请登录")
        let token = await setMobileSessionToken(user)
        res.json({
            code: 200,
            msg: '用户已存在，请登录',
            data: {
                userId: user.id,
                username: user.get("username"),
                mobile: user.get("mobile"),
                token: token?.get("sessionToken")
            }
        })
        return
    }
    try {
        let _User = Parse.Object.extend("_User")
        let User = new _User
        User.set("username", company + mobile)
        User.set("password", company + mobile)
        User.set("company", {
            __type: 'Pointer',
            className: 'Company',
            objectId: company
        })
        User.set("mobile", mobile)
        User.set("status", 'normal')
        let saveUser = await User.save({ useMasterKey: true })
        let token = await setMobileSessionToken(saveUser)
        res.json({
            code: 200,
            msg: '注册成功',
            data: {
                userId: saveUser.id,
                username: saveUser.get("username"),
                mobile: saveUser.get("mobile"),
                token: token?.get("sessionToken")
            }
        })

    } catch (error) {
        console.log(error)
        return
    }

})

function goWrong(response, msg) {
    response.status(500)
    response.json({
        code: 500,
        mess: msg
    })
    return
}
/* 检查用户是否存在 */
function getUserByMobile(mobile, company) {
    let query = new global.Parse.Query("_User");
    query.equalTo("mobile", mobile);
    query.equalTo("company", company);
    return query.first({ useMasterKey: true });
}
/* 创建_Session并返回 */
import {pgClient} from "../../db/pg-instance";

async function setMobileSessionToken(user, reset) {
    try {
        // let Session = global.Parse.Object.extend('_Session');
        if (user) {
            //获取最后一次的token，如果过期时间大于未来2小时直接返回，若不是重置
            let nowTime = new Date().getTime() + (1000 * 60 * 120)
            let query = new Parse.Query('_Session')
            query.equalTo('user', user.id)
            query.descending('expiresAt')
            query.greaterThan('expiresAt', new Date(nowTime))
            query.select('expiresAt', 'sessionToken')
            let reqSessionToken = await query.first({ useMasterKey: true })
            if (reqSessionToken?.id && reqSessionToken.get('sessionToken')) {
                return reqSessionToken
            }
            let username = user?.username || user?.get('username')
            let sessionToken = "r:" + username + (new Date().getTime() / 1000).toFixed();
            // 创建新Session登录系统
            let Session = Parse.Object.extend('_Session');
            let session = new Session()
            let r = await session.save(null, {
                useMasterKey: true
            })
            const objectId = r.id;
            let now = new Date();
            let expiresAt = (now.getFullYear() + 1) + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' 12:00:00'
            console.log(expiresAt);
            let sql = `INSERT INTO "_Session" ("objectId","user", "sessionToken", "expiresAt", "createdWith")
            VALUES
            ('${objectId}','${user.id}', '${sessionToken}','${expiresAt}','{"action": "login","authProvider": "appPassword"}')
            ON CONFLICT("objectId") DO UPDATE
            SET 
            "user" = excluded."user",
            "sessionToken" = excluded."sessionToken",
            "expiresAt"=excluded."expiresAt",
            "createdWith"=excluded."createdWith"
            `
            const data = await pgClient().any(sql);
            console.log('_Session', data)
            let doneObj = {
                get(field = 'sessionToken') {
                    if (field = 'sessionToken') return sessionToken
                }
            }
            // let session = new Session();
            // session.set("user", {
            //     __type: 'Pointer',
            //     className: '_User',
            //     objectId: user.id
            // });
            // session.set("sessionToken", sessionToken);
            // let now = new Date();
            // now.setFullYear(now.getFullYear() + 1);
            // let expiresAt = now;
            // session.set("expiresAt", expiresAt);
            // session.set("createdWith", {
            //     "action": "login",
            //     "authProvider": "appPassword"
            // })
            // session.set("restricted", false)
            // let doneObj = await session.save(null, {
            //     useMasterKey: true
            // })
            // if (!doneObj) {
            //     return false
            // }
            return doneObj
        }
    } catch (err) {
        console.log(err)
        return false
    }
}
module.exports = router;
export const textbookRouter = router;