'use strict';

/**
 * CLD接口相关控制器
 *
 * @author EllisRan.
 * @date 2018/9/25
 * @version
 */

const CLDModel = require("../models/cld_model");
const UserModel = require("../models/user_model");
const CompilationModel = require("../models/compilation_model");
let online_facade = require('../facade/online_facade')
const SMS = require('../models/sms');

class CLDController {

    /**
     * 获取cld办事处人员信息
     *
     * @param request
     * @param reponse
     * @return {Promise.<void>}
     */
    async getCategoryStaff(request, response) {
        const zongBuCategoryID = 12;
        let category = request.query.category;
        if (!category || category == -1) {
            category = request.session.sessionCompilation && request.session.sessionCompilation.categoryID ? request.session.sessionCompilation.categoryID : zongBuCategoryID;
            console.log(category);
        }
        try {
            let cldModel = new CLDModel();
            let result = await cldModel.getCategoryStaff(category);
            response.json({error: 0, msg: 'success', data: JSON.parse(result)});
        } catch (err) {
            response.json({error: 1, msg: err});
        }
    }

    /**
     * cld 获取建筑用户和编办接口
     *
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async getUsersAndCompilationList(request, response) {
        let mobile = request.query.mobile;
        let ssoID = request.query.ssoID;
        try {
            //获取用户信息
            if (mobile === undefined && ssoID === undefined) {
                throw '传参有误';
            }
            let userModel = new UserModel();
            let userData = '';
            if (mobile !== undefined) {
                userData = await userModel.findDataByMobile(mobile);
            } else {
                userData = await userModel.findDataBySsoId(ssoID);
            }
            if (userData === null || userData === '') {
                throw '不存在该建筑用户';
            }
            let userList = [userData];
            await online_facade.setOnlineTimes(userList, {});
            userData = JSON.parse(JSON.stringify(userData));

            userData.company_scale = userData.company_scale === null || userData.company_scale === undefined || userData.company_scale === -1 ? '' : userModel.companyScale[userData.company_scale] + '人';
            userData.company_type = userData.company_type === null || userData.company_type === undefined || userData.company_type === -1 ? '' : userModel.companyType[userData.company_type];
            userData.province = userModel.province[userData.province];

            let date = new Date(userData.create_time);
            userData.create_time = date.getFullYear() + '年' +
                (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '月' +
                (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日';

            //获取编办列表
            let compilationModel = new CompilationModel();
            let compilationList = JSON.parse(JSON.stringify(await compilationModel.getList()));
            if (userData.upgrade_list !== undefined) {
                let userUpgradeList = userData.upgrade_list;
                for (let i in userUpgradeList) {
                    let oneCompilationIndex = await compilationList.findIndex(function (item) {
                        return item._id === userUpgradeList[i].compilationID;
                    });
                    if (oneCompilationIndex !== -1) {
                        compilationList[oneCompilationIndex].isUpgrade = userUpgradeList[i].isUpgrade;
                        compilationList[oneCompilationIndex].deadline = userUpgradeList[i].deadline;
                        compilationList[oneCompilationIndex].lock = userUpgradeList[i].lock;
                    }
                }
            }
            response.json({error: 0, msg: 'success', data: { userInfo: userData, compilationList: compilationList }});
        } catch (err) {
            response.json({error: 1, msg: err});
        }
    }

    /**
     * 设置用户编办专业版
     *
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async setUsersUpgrade(request, response) {
        let ssoID = request.body.ssoId;
        let compilationID = request.body.cid;
        let deadline = request.body.deadline || '';
        let status = parseInt(request.body.status); // 1.升级、2.降级、3.续期
        let smssend = parseInt(request.body.smssend) || 0;
        let lock = parseInt(request.body.lock) || 0;// 0.默认、1.借出（借用）、2.销售（购买）、3.赠送（借用）
        try {

            let userModel = new UserModel();

            let userData = await userModel.findDataBySsoId(ssoID);

            let compilationModel = new CompilationModel();

            let compilationData = await compilationModel.getCompilationById(compilationID);

            if (compilationData === null || compilationData === undefined) {
                throw '不存在该编办或者编办未发布';
            }

            let upgrade_list = userData.upgrade_list !== undefined ? JSON.parse(JSON.stringify(userData.upgrade_list)) : [];

            let upgradeIndex = upgrade_list.findIndex(function (item) {
                return item.compilationID === compilationID
            });
            let upgradeInfo = {
                compilationID:compilationID,//编办ID
                upgrade_time:new Date().getTime(),
                isUpgrade: status !== 2,
                remark: '',
                deadline: deadline,
                lock: lock,
            };

            if (upgradeIndex === -1) {
                upgrade_list.push(upgradeInfo);
            } else {
                upgrade_list.splice(upgradeIndex, 1, upgradeInfo);
            }

            let condition = {ssoId: ssoID};
            let result = await userModel.updateUser(condition, {upgrade_list: upgrade_list});

            if (result) {
                // 短信发送
                if (smssend) {
                    // 发送短信
                    const Sms = new SMS();
                    await Sms.sendProductMsg(userData.mobile, status, userData.real_name, compilationData.name, deadline);
                }
                response.json({error: 0, msg: 'success'});
            } else {
                throw '更新失败';
            }
        } catch (err) {
            response.json({error: 1, msg: err});
        }
    }

    /**
     * 获取编办列表
     *
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async getCompilationList (request, response) {
        let compilationModel = new CompilationModel();
        const compilationList = await compilationModel.getList();
        response.json({error: 0, msg: 'success', data: compilationList});
    }

    /**
     * 获取个人和已使用编办信息
     * @param request
     * @param response
     * @returns {Promise<void>}
     */
    async getUsersInfo(request, response) {
        let ssoID = request.query.ssoID;
        try {
            //获取用户信息
            if (ssoID === undefined) {
                throw '传参有误';
            }
            let userModel = new UserModel();
            let userData = await userModel.findDataBySsoId(ssoID);
            if (userData === null || userData === '') {
                throw '不存在该建筑用户';
            }
            userData = JSON.parse(JSON.stringify(userData));

            userData.company_scale = userData.company_scale === null || userData.company_scale === undefined ? '' : userModel.companyScale[userData.company_scale] + '人';
            userData.company_type = userData.company_type === null || userData.company_type === undefined ? '' : userModel.companyType[userData.company_type];
            userData.province = userModel.province[userData.province];

            let date = new Date(userData.create_time);
            userData.create_time = date.getFullYear() + '年' +
                (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '月' +
                (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日';
            userData.all_online_times = online_facade.getTimeString(userData.all_online_times).s;

            //获取编办列表
            let compilationModel = new CompilationModel();
            let compilationList = JSON.parse(JSON.stringify(await compilationModel.getList()));
            if (userData.upgrade_list !== undefined) {
                let userUpgradeList = userData.upgrade_list;
                for (let i in userUpgradeList) {
                    let oneCompilationIndex = await compilationList.findIndex(function (item) {
                        return item._id === userUpgradeList[i].compilationID;
                    });
                    if (oneCompilationIndex !== -1) {
                        // compilationList[oneCompilationIndex].isUpgrade = userUpgradeList[i].isUpgrade;
                        userData.upgrade_list[i].name = compilationList[oneCompilationIndex].name;
                        userData.upgrade_list[i].description = compilationList[oneCompilationIndex].description;
                        userData.upgrade_list[i].categoryID = compilationList[oneCompilationIndex].categoryID;
                    }
                }
            }
            response.json({error: 0, msg: 'success', data: { userInfo: userData }});
        } catch (err) {
            response.json({error: 1, msg: err});
        }
    }

    async provinceList(request, response) {
        let userModel = new UserModel();
        let responseData = {
            error: 0,
            msg: '',
            data: userModel.province,
        };
        response.json(responseData);
    }

    /**
     * 获取用户列表分页
     * @param request
     * @param response
     * @returns {Promise<void>}
     */
    async getUserList(request, response) {
        let userModel = new UserModel();
        let total = 0;
        let pageSize = 12;
        let pageData = {};
        let userList = [];
        let compilationList =[];
        let filter = request.query;
        try {
            //获取编办列表
            let  compilationModel = new CompilationModel();
            compilationList = await compilationModel.getCompilationList({_id: 1, name: 1, is_release: 1});
            let condition = userModel.getFilterCondition(request);
            //设置搜索普通用户：
            condition.user_type = 'normal';
            //设置剔除CLD用户列表不显示
            let keyword = request.query.keyword;
            if(keyword === undefined || keyword === '') {
                condition.is_cld = {$in: [null, 0]};
            }

            //获取注册时间
            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);
            }

            // 排序方式
            let sortType = request.query.sortType !== '' && request.query.sortType !== undefined ? request.query.sortType : -1;

            // 排序条件
            let sortField = request.query.sortField;
            let sort = {_id: sortType};
            if (sortField !== '' && sortField !== undefined && sortField === 'latest_login') {
                sort = {latest_login: sortType}
            } else if(sortField !== '' && sortField !== undefined && sortField === 'online_times')  {
                sort = {online_times: sortType}
            }

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

            // 分页数据
            let page = request.query.page === undefined ? 1 : request.query.page;
            pageSize = request.query.pageSize === undefined ? 12 : parseInt(request.query.pageSize);
            pageData = {
                current: page,
                total: total,
                queryData: response.locals.urlQuery
            };
            // console.log("取用户信息=========================");
            // console.log(condition);
            // 获取用户列表
            userList = await userModel.getList(condition, page, pageSize, sort);
            await online_facade.setOnlineTimes(userList,condition);
            userList = JSON.parse(unescape(escape(JSON.stringify(userList))));
            for (const userData of userList) {
                userData.province = userData.province !== -1 ? userModel.province[userData.province] : '';
            }
            response.json({error: 0, msg: 'success', data: {
                    userInfo: userList,
                    pageData: pageData,
                    compilationList:compilationList,
                }});
        } catch (error) {
            response.json({error: 1, msg: error});
        }
    }

    async getUserOnlineInfo(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 getRejectUsers(request, response) {
        let userModel = new UserModel();
        let total = 0;
        let pageSize = 12;
        let pageData = {};
        let userList = [];
        try {
            const condition = {
                user_type: 'normal',
                is_cld: {$exists:true, $ne: 0}
            };
            // 获取用户总数
            total = await userModel.count(condition);
            // 分页数据
            let page = request.query.page === undefined ? 1 : request.query.page;
            pageSize = request.query.pageSize === undefined ? 12 : parseInt(request.query.pageSize);
            userList = await userModel.getList(condition, page, pageSize, {is_cld:-1});
            pageData = {
                current: page,
                total: total,
                queryData: response.locals.urlQuery
            };
            response.json({error: 0, msg: 'success', data: { userList: userList, pageData: pageData }});
        } catch (error) {
            response.json({error: 1, msg: error});
        }
    }
}

module.exports = CLDController;
