/**
 * 后台用户管理控制器
 *
 * @author CaiAoLin
 * @date 2017/6/2
 * @version
 */
import BaseController from "../../common/base/base_controller";
import ManagerModel from "../models/manager_model";
import Config from "../../../config/config";
let config = require("../../../config/config.js");

class ManagerController extends BaseController {

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

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

            // 获取管理员列表
            managerList = await managerModel.getList(null, page);

            // 整理数据
            if (managerList.length > 0) {
                for (let tmp in managerList) {
                    let permission = managerList[tmp].permission;
                    permission = permission.split(',');

                    if (permission.length <= 0) {
                        continue;
                    }

                    let permissionString = [];
                    for (let name of permission) {
                        if (managerModel.permission[name] === undefined) {
                            continue;
                        }
                        permissionString.push(managerModel.permission[name]);
                    }
                    permissionString = permissionString.join(',');
                    managerList[tmp].permissionStr = permissionString;
                }
            }
        } catch (error) {

        }

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

    /**
     * 保存管理员
     *
     * @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 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');
    }
}

export default ManagerController;