var express = require('express');
var createError = require('http-errors')
const bcrypt = require('bcryptjs');

const models = require('../../../models');
const utils = require('../../../libs/utils');
const authChecker = require('../../../libs/auth/checker');
const auth = require('../../../libs/auth');

const router = express.Router();

router.get('/guard', authChecker.checkLogin, function (req, res, next) {
  (async function () {
    res.json({
      msg: 'ok'
    })
  })().catch(next)
});

router.get('/profile', authChecker.checkLogin, function (req, res, next) {
  (async function () {
    res.json(req.session.user);
  })().catch(next)
});

router.get('/sign-out', authChecker.checkLogin, function (req, res, next) {
  (async function () {
    //delete req.session.user;
    req.session.destroy();
    res.status(200)
      .clearCookie('test_sid', { path: '/' })
      .json({
        msg: 'ok'
      })
  })().catch(next)
});

router.post('/sign-in', function (req, res, next) {
  (async function () {
    let { username, password } = req.body;
    if (!username || !password) throw createError(401, 'Invalid params.');
    username = username.trim();
    password = password.trim();

    let doc = await models.User.findOne({ username });
    if (!doc) throw createError(401, '用户名或者密码错误');
    let match = await bcrypt.compare(password, doc.password);
    if (!match) throw createError(401, '用户名或者密码错误');
    if (doc.disabled) throw createError(401, '账户已停用，请联系管理员');
    doc.dateLastSignin = new Date();
    doc.ipLastSignin = req.ip;
    await doc.save();
    req.session.user = doc.toObject();
    res.json({
      msg: 'ok'
    })
  })().catch(next)
});


router.patch('/password', authChecker.checkLogin, function (req, res, next) {
  (async function () {
    let userId = req.session.user._id;
    let { password } = req.body;
    if (!password) throw createError(400, 'Invalid params.');
    let doc = await models.User.findById(userId);
    if (!doc) throw createError('系统错误');
    let salt = await bcrypt.genSalt(10);
    doc.password = await bcrypt.hash(password, salt);
    await doc.save();
    res.json({
      msg: 'ok'
    })
  })().catch(next)
});


router.get('/grants', authChecker.checkLogin, function (req, res, next) {
  (async function () {
    let doc = await models.User.findById(req.session.user._id).populate('roles');
    let grants = [];
    if (['chengen', 'guoziyun'].includes(doc.username)) {
      grants = auth.base.fullGrants();
    } else {
      doc.roles.forEach(role => {
        grants = grants.concat(role.grants);
      })
    }
    res.json(grants);
  })().catch(next)
});



router.post('/template', function (req, res, next) {
  (async function () {
    throw createError(404, 'YOUR SHOULD NOT SEE THIS');
  })().catch(next)
});




module.exports = router;
