/**
 * 用户管理控制器
 *
 * @author CaiAoLin
 * @date 2017/6/7
 * @version
 */
import BaseController from "../../common/base/base_controller";
import UserModel from "../models/user_model";
import Config from "../../../config/config";
import CompilationModel from "../models/compilation_model";
let config = require("../../../config/config.js");
let _ = require("lodash");
let online_facade = require('../facade/online_facade')

class UserController extends BaseController {

    /**
     * 最近注册列表(最近登录前台用户列表)
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async normalUsers(request, response) {//取普通用户
        let userModel = new UserModel();
        let total = 0;
        let pageData = {};
        let userList = [];
        let compilationList =[];
        let compilationString ='';
        let compilationMap = {};
        let filter = request.query;
        try {
            //获取编办列表
            let  compilationModel = new CompilationModel();
            compilationList = await compilationModel.getCompilationList({_id: 1, name: 1, is_release: 1});
            compilationString = JSON.stringify(compilationList);
            compilationMap = _.keyBy(compilationList,'_id');//4.17后的版本没有indexBy方法，改成了keyBy
            let condition = userModel.getFilterCondition(request);
            //设置搜索普通用户：
            condition.user_type = 'normal';

            //获取注册时间
            let regtime = request.query.regtime;
            if(regtime !== '' && regtime !== undefined){
                filter.regtimeMsg = userModel.getDayMsg(regtime);
            }

            //获取注册时间
            let loginTime = request.query.loginTime;
            if(loginTime !== '' && loginTime !== undefined){
                filter.loginMsg = userModel.getDayMsg(loginTime);
            }

            // 获取用户总数
            total = await userModel.count(condition);

            // 分页数据
            let page = request.query.page === undefined ? 1 : request.query.page;
            pageData = {
                current: page,
                total: Math.ceil(total / Config.pageSize),
                queryData: response.locals.urlQuery
            };
            // console.log("取用户信息=========================");
            // console.log(condition);
            // 获取用户列表
            userList = await userModel.getList(condition, page, Config.pageSize);
            await online_facade.setOnlineTimes(userList,condition);
            // console.log(userList)
        } catch (error) {
            console.log(error);
        }

        // 用户管理二级菜单独立出来
        let secondMenu = response.locals.secondMenu;
        let userMenu = [];
        for (let second in secondMenu) {
            userMenu.push(secondMenu[second]);
        }

        // 渲染数据
        let renderData = {
            compilationList:compilationList,
            compilationString:compilationString,
            compilationMap:compilationMap,
            adminName:request.session.managerData?request.session.managerData.real_name:'',
            userList: userList,
            pages: pageData,
            total: total,
            filter: filter,
            model: userModel,
            userMenu: userMenu,
            layout: 'users/views/layout/layout',
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };
        response.render('users/views/user/index', renderData);
    }


    async testUsers(request,response){
        let userModel = new UserModel();
        let total = 0;
        let pageData = {};
        let userList = [];
        let compilationList =[];
        let compilationString ='';
        let compilationMap = {};
        let filter = request.query;
        try {
            //获取编办列表
            let  compilationModel = new CompilationModel();
            compilationList = await compilationModel.getCompilationList({_id: 1, name: 1, is_release: 1});
            compilationString = JSON.stringify(compilationList);
            compilationMap = _.keyBy(compilationList,'_id');
            let condition = userModel.getFilterCondition(request);
            //设置搜索普通用户：
            condition.user_type = 'normal';

            //获取注册时间
            let regtime = request.query.regtime;
            if(regtime !== '' && regtime !== undefined){
                filter.regtimeMsg = userModel.getDayMsg(regtime);
            }

            //获取注册时间
            let loginTime = request.query.loginTime;
            if(loginTime !== '' && loginTime !== undefined){
                filter.loginMsg = userModel.getDayMsg(loginTime);
            }

            // 获取用户总数
            total = await userModel.count(condition);

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

            // 获取用户列表
            userList = await userModel.getList(condition, page, Config.pageSize);
        } catch (error) {
            console.log(error);
        }

        // 用户管理二级菜单独立出来
        let secondMenu = response.locals.secondMenu;
        let userMenu = [];
        for (let second in secondMenu) {
            userMenu.push(secondMenu[second]);
        }

        // 渲染数据
        let renderData = {
            compilationList:compilationList,
            compilationString:compilationString,
            compilationMap:compilationMap,
            adminName:request.session.managerData?request.session.managerData.real_name:'',
            userList: userList,
            pages: pageData,
            total: total,
            filter: filter,
            model: userModel,
            userMenu: userMenu,
            layout: 'users/views/layout/layout',
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };
        response.render('users/views/user/test_user', renderData);
    }


    /**
     * 获取搜索用户json
     *
     * @param {object} request
     * @param {object} response
     * @return {string}
     */
    async search(request, response) {
        let userModel = new UserModel();
        let responseData = {
            error: 0,
            msg: '',
            data: null
        };
        try{
            let keyword = request.query.keyword;
            if(keyword === undefined || keyword === '') {
                throw { code: 1, err: '参数有误或为空'};
            }
            let condition = userModel.getFilterCondition(request);
            let userList = await userModel.getList(condition);
            responseData.data = userList;
        } catch (error) {
            console.log(error);
            responseData.error = error.code;
            responseData.msg = error.err;
        }

        response.json(responseData);
    }

    async findByID(request, response) {
        let params = JSON.parse(request.body.data),
            userIds = params.ID;
        let userModel = new UserModel();
        let responseData = {
            error: 0,
            msg: '',
            data: null
        };
        try{
            if(userIds === undefined || userIds === '') {
                throw { code: 1, err: '参数有误或为空'};
            }
            let user = await userModel.getByID({ _id: userIds});
            responseData.data = user;
        } catch (error) {
            console.log(error);
            responseData.error = error.code;
            responseData.msg = error.err;
        }
        response.json(responseData);
    }

    async getOnlineInfo(request, response){
        let filter = JSON.parse(request.body.data);
        let responseData = {
            error: 0,
            msg: '',
            data: null
        };
        try{
            let info = await online_facade.getOnlineInfo(filter);
            responseData.data = info;
        } catch (error) {
            console.log(error);
            responseData.error = error.code;
            responseData.msg = error.err;
        }
        response.json(responseData);
    }

    async updateUser(request, response) {
        let data = JSON.parse(request.body.data);
        let userModel = new UserModel();
        let responseData = {
            error: 0,
            msg: '',
            data: null
        };
        try{
            if(data.ID === undefined || data.ID === '') {
                throw { code: 1, err: '参数有误或为空'};
            }
            let user = await userModel.updateById(data.ID,data.updateData);
            responseData.data = user;
        } catch (error) {
            console.log(error);
            responseData.error = error.code;
            responseData.msg = error.err;
        }
        response.json(responseData);
    }
    async deleteUser(request, response) {
        let data = JSON.parse(request.body.data);
        let userModel = new UserModel();
        let responseData = {
            error: 0,
            message: '',
            data: null
        };
        try{
            let manager = request.session.managerData;
            if(manager.superAdmin !=1 ){
                throw { code: 1, message: '没有删除用户权限'};
            }
            responseData.data =  await userModel.deleteUser(data.userID,manager.userID);
        } catch (error) {
            console.log(error);
            responseData.error = error.code;
            responseData.message = error.message;
        }
        response.json(responseData);
    }

    /**
     * 根据用户id列表获取用户信息列表 json
     *
     * @param {object} request
     * @param {object} response
     * @return {string}
     */
    async getUserList(request, response) {
        let params = JSON.parse(request.body.params),
            userIds = params.userIds;
        let userModel = new UserModel();
        let responseData = {
            error: 0,
            msg: '',
            data: null
        };
        try{
            if(userIds === undefined || userIds === '') {
                throw { code: 1, err: '参数有误或为空'};
            }
            let condition = {
                _id: {$in:userIds}
            };
            let userList = await userModel.getList(condition);
            responseData.data = userList;
        } catch (error) {
            console.log(error);
            responseData.error = error.code;
            responseData.msg = error.err;
        }

        response.json(responseData);
    }
}

export default UserController;
