/**
 * 后台用户管理控制器
 *
 * @author CaiAoLin
 * @date 2017/6/2
 * @version
 */
import BaseController from "../../common/base/base_controller";
import ManagerModel from "../models/manager_model";
import PermissionModel from "../models/permission_model";
import PermissionGroupModel from "../models/permission_group_model";
import Config from "../../../config/config";
let config = require("../../../config/config.js");
import {default as category, List as categoryList} from "../../common/const/category_const.js";

class ManagerController extends BaseController {

    /**
     *  账号管理(管理员列表)
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async index(request, response) {
        let pageData = {};
        let managerList = [];
        let permissionGroupList = [];
        let filter = request.query;
        try {
            // 查找管理员用户列表
            let managerModel = new ManagerModel();
            let total = await managerModel.count({super_admin: 0});

            // 分页数据
            let page = request.query.page === undefined ? 1 : request.query.page;
            pageData = {
                current: page,
                total: parseInt(total / Config.pageSize),
                queryData: response.locals.urlQuery
            };

            // 获取管理员列表
            let condition = managerModel.getFilterCondition(request);
            condition.super_admin = 0;
            managerList = JSON.parse(JSON.stringify(await managerModel.getList(condition, page)));

            let permissionGroupModel = new PermissionGroupModel();
            let permissionModel = new PermissionModel();

            // 添加特定数据到filter里
            if (request.query.office !== undefined && request.query.office !== '') {
                let officeInfo = await categoryList.find(function (item) {
                    return item.id === parseInt(request.query.office);
                });
                filter.officeName = officeInfo.name
            }
            if (request.query.permission !== undefined && request.query.permission !== '0') {
                let permissionGroupInfo = await permissionGroupModel.findDataByCondition({_id: request.query.permission});
                filter.permissionGroupName = permissionGroupInfo.name;
            }

            // 获取权限组列表
            permissionGroupList = JSON.parse(JSON.stringify(await permissionGroupModel.getList()));
            if (permissionGroupList.length > 0) {
                for (let tmp in permissionGroupList) {
                    let topPermissionList = [];
                    if (permissionGroupList[tmp].permission !== undefined && permissionGroupList[tmp].permission !== '') {
                        let groupPermissionList = JSON.parse(permissionGroupList[tmp].permission);
                        for (let p in groupPermissionList) {
                            if (p === 'top') {
                                for (let t of groupPermissionList[p]) {
                                    let topInfo = await permissionModel.findDataByCondition({_id:t});
                                    topPermissionList.push(topInfo.name);
                                }
                                break;
                            }
                        }
                    }
                    permissionGroupList[tmp].top_name = topPermissionList.join(',');
                }
            }

            // 整理数据
            if (managerList.length > 0) {
                for (let tmp in managerList) {
                    let cate = await categoryList.find(function (item) {
                        return item.id === managerList[tmp].office;
                    });
                    managerList[tmp].officeName = cate !== undefined ? cate.name : '';

                    let groupInfo = managerList[tmp].permission !== '' ? await permissionGroupModel.findDataByCondition({_id:managerList[tmp].permission}) : '';
                    managerList[tmp].permissionName = groupInfo !== undefined && groupInfo !== '' ? groupInfo.name : '';
                }
            }
        } catch (error) {
            console.log(error);
        }

        let permissionGroupList2 = JSON.stringify(permissionGroupList);
        let renderData = {
            managerList: managerList,
            pages: pageData,
            categoryList: categoryList,
            permissionGroupList: permissionGroupList,
            permissionGroupList2: permissionGroupList2,
            layout: 'users/views/layout/layout',
            filter: filter,
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };
        response.render('users/views/manager/index', renderData);
    }

    /**
     * 权限组分配(管理员页面)
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async groupSave(request, response) {
        let id = request.body.manager_id;
        let permission = request.body.permission !== '0' ? request.body.permission : '';
        let managerModel = new ManagerModel();
        let result = await managerModel.updateById(id, {permission: permission});

        if (!result) {
            throw '修改失败';
        }
        response.redirect(request.headers.referer);
    }

    /**
     * 保存管理员
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    // async modify(request, response) {
    //     let permission = request.body.permission;
    //     let canLogin = request.body.login;
    //     let id = request.params.id;
    //
    //     let responseData = {
    //         err: 0,
    //         msg: ""
    //     };
    //     try {
    //         if (id === '' || id === undefined) {
    //             throw 'id有误';
    //         }
    //         let managerModel = new ManagerModel();
    //         let result = await managerModel.updateById(id, {permission: permission, can_login: canLogin});
    //
    //         if (!result) {
    //             throw '修改失败';
    //         }
    //
    //     } catch (error) {
    //         responseData.err = 1;
    //         responseData.msg = error;
    //     }
    //
    //     response.json(responseData);
    // }

    /**
     * 删除管理员
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async delete(request, response) {
        let id = request.params.id;
        let managerModel = new ManagerModel();
        let result = await managerModel.deleteById(id, true);

        // 删除成功
        if (result) {

        }
        response.redirect(request.headers.referer);
    }

    /**
     * 操作管理员（启用和停用）
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async modify(request, response) {
        let canLogin = request.params.login;
        let id = request.params.id;

        let managerModel = new ManagerModel();
        let result = await managerModel.updateById(id, {can_login: canLogin});

        // 修改成功
        if (!result) {
            throw '修改失败';
        }
        response.redirect(request.headers.referer);
    }

    /**
     * 超级管理员修改
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async admin(request, response) {
        let adminData = {};
        try {
            // 查找对应超级管理员数据
            let managerModel = new ManagerModel();
            adminData = await managerModel.findDataByCondition({username: 'admin'});

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

        let renderData = {
            adminData: adminData,
            layout: 'users/views/layout/layout',
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };
        response.render('users/views/manager/save', renderData);
    }

    /**
     * 超级管理员修改提交
     *
     * @param {object} request
     * @param {object} response
     * @return
     */
    async adminSubmit(request, response) {
        let newPassword = request.body.newPassword.toString();
        let password = request.body.password.toString();
        let managerModel = new ManagerModel();
        let responseData = {
            err: 0,
            msg: ''
        };
        try {
            if (!newPassword || !password) {
                throw '内容有误';
            }
            // 更改密码操作
            managerModel.setScene('changPassword');
            let result = await managerModel.changePassword('admin', password, newPassword);
            if (!result) {
                throw '更新错误';
            }
        } catch (error) {
            console.log(error);
            responseData.err = 40002;
            responseData.msg = error;
        }

        response.json(responseData);
    }

    async create(request, response) {
        let managerModel = new ManagerModel();
        let result = managerModel.changePassword('admin', 'admin123', 'admin123');
        // let result = await managerModel.createManager();
        response.end('success');
    }

    /**
     * 权限组页面
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async authority(request, response) {
        let pageData = {};
        let groupList = [];
        let topPermissionList = [];
        let permissionList = [];
        try {
            // 获取最高级权限列表
            let permissionModel = new PermissionModel();
            topPermissionList = await permissionModel.getList({pid:0});

            // 获取所有权限列表，按排序
            permissionList = topPermissionList;
            for (let index in permissionList) {
                let count = await permissionModel.count({pid:permissionList[index].ID});
                if (count > 0) {
                    permissionList[index].secondPermissionList = await permissionModel.getList({pid: permissionList[index].ID});
                } else {
                    permissionList[index].secondPermissionList = [];
                }
                permissionList[index].count = count;
            }

            // 获取权限组列表
            let permissionGroupModel = new PermissionGroupModel();
            let total = await permissionGroupModel.count();

            // 分页数据
            let page = request.query.page === undefined ? 1 : request.query.page;
            pageData = {
                current: page,
                total: parseInt(total / Config.pageSize),
                queryData: response.locals.urlQuery
            };

            // 获取管理员列表
            groupList = JSON.parse(JSON.stringify(await permissionGroupModel.getList(null, page)));

            // 整理数据
            if (groupList.length > 0) {
                let managerModel = new ManagerModel();
                for (let tmp in groupList) {
                    let managerCount = await managerModel.count({permission: groupList[tmp]._id});
                    groupList[tmp].manager_count = managerCount;
                    let groupPermissionList = JSON.parse(groupList[tmp].permission);
                    for (let p in groupPermissionList) {
                        if (p === 'top') {
                            let topPermissionList = [];
                            for (let t of groupPermissionList[p]) {
                                let topInfo = await permissionModel.findDataByCondition({_id:t});
                                topPermissionList.push(topInfo.name);
                            }
                            groupList[tmp].top_name = topPermissionList.join(',');
                        }
                    }
                }
            }
        } catch (error) {

        }
        let renderData = {
            groupList: groupList,
            topPermissionList: topPermissionList,
            permissionList: permissionList,
            pages: pageData,
            layout: 'users/views/layout/layout',
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };
        response.render('users/views/manager/authority', renderData);
    }

    /**
     * 权限组添加
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async authorityAdd(request, response) {
        let permissionGroupModel = new PermissionGroupModel();
        let result = await permissionGroupModel.createPermissionGroup(request.body);
        if (!result) {
            throw '添加失败';
        }
        response.redirect(request.headers.referer);
    }

    /**
     * 权限组修改保存
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async authoritySave(request, response) {
        let permissionGroupModel = new PermissionGroupModel();
        let result = await permissionGroupModel.savePermissionGroup(request.body);
        if (!result) {
            throw '修改失败';
        }
        response.redirect(request.headers.referer);
    }

    /**
     * 权限组删除
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async authorityDelete(request, response) {
        let id = request.body.id;
        try {
            let permissionGroupModel = new PermissionGroupModel();
            await permissionGroupModel.deleteById(id, true);
            // 并清空用户所在权限组
            let managerModel = new ManagerModel();
            await managerModel.updateByPermission(id);
        } catch(err) {
            throw err;
        }
        response.redirect(request.headers.referer);
    }

    /**
     * 权限添加接口
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async permissionAdd(request, response) {
        let permissionModel = new PermissionModel();
        let responseData = {
            err: 0,
            msg: ''
        };
        try {
            permissionModel.setScene('insert');
            let result = await permissionModel.createPermission(request.body);
            if (!result) {
                throw '添加失败';
            }
        } catch (error) {
            console.log(error);
            responseData.err = 1;
            responseData.msg = error;
        }

        response.json(responseData);
    }
}

export default ManagerController;