const createError = require('http-errors');
const express = require('express');
const router = express.Router();
const models = require('../../../models');
const utils = require('../../../libs/utils');
const auth = require('../../../libs/auth');

const isOwner = (item, req) => item.user && item.user._id == req.session.user._id;

router.get('/pager/headers', auth.need('read:own', 'role'), utils.pager.getHeadersBuilder(models.Role));
router.get('/pager', auth.need('read:own', 'role'), (req, res, next) => {
  (async () => {
    let ac = await auth.getAc(req);
    if (!ac.can('user').readAny('role').granted) {
      req.query.base = { user: req.session.user._id };
    }
    next();
  })().catch(next)
}, utils.pager.getListBuilder(models.Role, [{ path: 'user', select: 'username' }], isOwner));


router.get('/options', auth.need('read:own', 'user'), function (req, res, next) {
  (async function () {
    let ac = await auth.getAc(req);
    if (ac.can('user').createAny('user').granted) { //all roles
      let roles = await models.Role.find().select('name').lean()
      res.json(roles.map(r => ({ label: r.name, value: r._id })));
    } else {
      //用户创建的角色
      let roles = await models.Role.find({ user: req.session.user._id }).select('name').lean()
      //用户拥有的角色
      let userDoc = await models.User.findById(req.session.user._id).populate({ path: 'roles', select: 'name' }).lean();
      roles = roles.concat(userDoc.roles);
      console.log('roles:', roles);
      //去除重复
      let result = roles.filter((role, index) => {
        let myIndex = roles.findIndex(r => r._id.equals(role._id));
        console.log(index, myIndex);
        return myIndex === index;
      }).map(r => ({ label: r.name, value: r._id }))

      res.json(result);
    }
  })().catch(next);
});


// 直接取角色对应的用户列表
router.get('/options2', auth.need('read:own', 'user'), function (req, res, next) {
  (async function () {
    let ac = await auth.getAc(req);
    if (ac.can('user').createAny('user').granted) { //all roles
      let roles = await models.Role.find().select('name').lean()
      for (let ro of roles) {
        let users = await models.UserRole.find({ 'role': ro._id }).lean() || [];
        users = users.map(e => e.user);
        ro.users = users;
      }
      res.json(roles.map(r => ({ label: r.name, value: r.users })));
    }
  })().catch(next);
});




router.post('/', auth.need('create:own', 'role'), function (req, res, next) {
  (async function () {
    //await utils.async.delay(500);
    let data = req.body;
    let { name, grants } = data;
    if (!name || !grants)
      throw createError(400, '参数错误');
    let user = req.session.user._id;
    let role = models.Role({ name, grants, user })
    role = await role.save();
    res.json({ msg: 'ok' });
  })().catch(next);
});


router.patch('/:id', auth.need('update:own', 'role'), function (req, res, next) {
  (async function () {
    //await utils.async.delay(500);
    let { id } = req.params;
    utils.validators.validateId(id);
    let role = await models.Role.findById(id);
    if (!role) throw createError(404, '角色不存在');
    let ac = await auth.getAc(req);
    if (!ac.can('user').updateAny('role').granted && role.user != req.session.user._id) {
      throw createError(403, '没有权限');
    }
    let { name, grants } = req.body;
    if (!name || !grants)
      throw createError(400, '参数错误');
    role.set({ name, grants });
    role = await role.save();
    res.json({ msg: 'ok' });
  })().catch(next);
});


router.delete('/:id', auth.need('delete:own', 'role'), function (req, res, next) {
  (async function () {
    //await utils.async.delay(500);
    let { id } = req.params;
    utils.validators.validateId(id);
    let role = await models.Role.findById(id);
    if (!role) throw createError(404, '角色不存在');
    let ac = await auth.getAc(req);
    if (!ac.can('user').deleteAny('role').granted && role.user != req.session.user._id) {
      throw createError(403, '没有权限');
    }
    if (!role.user)
      throw createError(400, '预定义角色不能删除')
    await role.delete();
    res.json(role)
  })().catch(next);
});


router.get('/:id', auth.need('read:own', 'role'), function (req, res, next) {
  (async function () {
    //await utils.async.delay(500);
    let { id } = req.params;
    utils.validators.validateId(id);
    let role = await models.Role.findById(id).lean();
    let ac = await auth.getAc(req);
    if (!ac.can('user').deleteAny('role').granted && role.user != req.session.user._id) {
      throw createError(403, '没有权限');
    }
    if (!role) throw createError(404, '角色不存在');
    res.json(role)
  })().catch(next);
});


router.get('/auth/config', auth.need('read:own', 'role'), function (req, res, next) {
  (async function () {
    let { resources, actions, possessions } = auth.base;
    res.json({ resources, actions, possessions });
  })().catch(next);
});





module.exports = router;
