/**
 * 用户相关控制器
 *
 * @author CaiAoLin
 * @date 2017/6/13
 * @version
 */
const UserModel = require("../models/user_model");
const BaseController = require("../../common/base/base_controller");
const LogType = require("../../common/const/log_type_const");
const LogModel = require("../models/log_model");
const SettingModel = require("../models/setting_model");
const SettingType = require("../../common/const/setting_type_const");
const CompilationModel = require("../models/compilation_model");
const mongoose = require("mongoose");
const moment = require("moment");
const userData = mongoose.model('user');

class UserController extends BaseController {

    /**
     * 用户信息页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async info(request, response) {
        // 获取当前用户数据
        let sessionUser = request.session.sessionUser;

        let userModel = new UserModel();
        let userData = await userModel.findDataBySsoId(sessionUser.ssoId);
        userData = Object.keys(userData).length <= 0 ? [] : userData;

        let renderData = {
            userData: userData,
            provinceList: userModel.province,
            companyTypeList: userModel.companyType,
            companyScaleList: userModel.companyScale,
            compilationName: request.session.sessionCompilation.name,
            versionName: request.session.compilationVersion,
        };
        response.render('users/html/user-info', renderData);
    }

    /**
     * 保存个人数据
     *
     * @param {object} request
     * @param {object} response
     * @return
     */
    async saveData(request, response) {
        try {
            let updateData = {
                real_name: request.body.real_name,
                province: request.body.province,
                company: request.body.company,
                version: request.body.version ? request.body.version : null,
                company_type: request.body.company_type ? request.body.company_type : null,
                company_scale: request.body.company_scale ? request.body.company_scale : null,
            };
            let sessionUser = request.session.sessionUser;
            // 切换验证场景
            let userModel = new UserModel();
            let condition = {ssoId: sessionUser.ssoId};
            userModel.setScene('saveInfo');
            let result = await userModel.updateUser(condition, updateData);
            //更新session
            for(let attr in sessionUser){
                sessionUser[attr] = updateData[attr] ? updateData[attr] : sessionUser[attr];
            }
            if (result.ok !== 1) {
                throw '用户数据保存失败';
            }
        } catch (error) {
            return response.redirect(request.headers.referer);
        }

        response.redirect('/pm');
    }

    /**
     * 账号安全页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async safe(request, response) {
        let userData = [];
        let logList = [];
        let pageData = {};
        try {
            // 获取当前用户信息
            let sessionUser = request.session.sessionUser;
            console.log(sessionUser);
            let userModel = new UserModel();
            userData = await userModel.findDataBySsoId(sessionUser.ssoId);
            console.log(userData);

            let page = request.query.page === undefined ? 1 : request.query.page;

            // 获取登录信息
            let logModel = new LogModel();
            let logCount = await logModel.count();
            logCount = logCount > 30 ? 30 : logCount;
            let pageSize = 10;
            logList = await logModel.getLog(sessionUser.id, LogType.LOGIN_LOG, page, pageSize);

            // 分页数据
            pageData = {
                current: page,
                total: parseInt(logCount / pageSize),
                queryData: response.locals.urlQuery
            };
        } catch (error) {
            console.log(error);
        }

        let renderData = {
            userData: userData,
            logList: logList,
            pages: pageData,
            compilationName: request.session.sessionCompilation.name,
            versionName: request.session.compilationVersion,
        };
        response.render('users/html/user-safe', renderData);
    }

    /**
     * 产品激活页面
     *
     * @param request
     * @param response
     * @return {void}
     */
    async buy(request, response) {
        let userData = [];
        let compilationList = [];
        try {
            // 获取编办信息
            let compilationModel = new CompilationModel();
            compilationList = await compilationModel.getList();

            // 获取当前用户信息
            let sessionUser = request.session.sessionUser;
            let userModel = new UserModel();
            userData = await userModel.findDataBySsoId(sessionUser.ssoId);
            if (userData.upgrade_list !== undefined) {
                let userUpgradeList = userData.upgrade_list;
                for (let index in userUpgradeList) {
                    let oneCompilationIndex = compilationList.findIndex(function (item) {
                        return item.id === userUpgradeList[index].compilationID;
                    });
                    if (oneCompilationIndex !== -1) {
                        compilationList[oneCompilationIndex].isUpgrade = userUpgradeList[index].isUpgrade;
                        compilationList[oneCompilationIndex].deadline = userUpgradeList[index].deadline;
                        compilationList[oneCompilationIndex].lock = userUpgradeList[index].lock;
                    }
                }
            }
        } catch(error) {
            console.log(error);
        }

        let renderData = {
            userData: userData,
            compilationList: compilationList,
            compilationName: request.session.sessionCompilation.name,
            versionName: request.session.compilationVersion,
        };
        response.render('users/html/user-buy', renderData);
    }

    /**
     * 偏好设置页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async preferences(request, response) {
        let sessionUserData = request.session.sessionUser;
        let preferenceSetting = {};
        let compilationList = [];
        try {
            // 获取配置信息
            let settingModel = new SettingModel();
            preferenceSetting = await settingModel.getPreferenceSetting(sessionUserData.id);

            // 获取编办信息
            let compilationModel = new CompilationModel();
            compilationList = await compilationModel.getList();

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

        let renderData = {
            preferenceSetting: preferenceSetting,
            compilationList: compilationList,
            compilationName: request.session.sessionCompilation.name,
            versionName: request.session.compilationVersion,
        };
        response.render('users/html/user-set', renderData);
    }

    /**
     * 保存偏好设置
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async savePreferences(request, response) {
        let loginAsk = request.body.login_ask;
        loginAsk = parseInt(loginAsk);
        let selectVersion = request.body.select_version;
        let sessionUserData = request.session.sessionUser;

        try {
            let data = {
                login_ask: loginAsk,
                select_version: loginAsk === 0 ? selectVersion : ''
            };
            let settingModel = new SettingModel();
            let result = await settingModel.save(sessionUserData.id, SettingType.PREFERENCE, data);
            if (!result) {
                throw '保存失败';
            }

            // 保存编办信息到session
            if (data.login_ask === 1) {
                // 查找对应编办
                let compilationModel = new CompilationModel();
                let compilationData = await compilationModel.getCompilationById(selectVersion);
                // 判断当前用户的是使用免费版还是专业版
                let userModel = new UserModel();
                let compilationVersion = await userModel.getVersionFromUpgrade(sessionUserData.ssoId, compilationData._id);
                request.session.compilationVersion = compilationVersion.version;
                request.session.sessionUser.compilationLock = compilationVersion.lock;
                request.session.sessionCompilation = compilationData;
            }
        } catch (error) {
            console.log(error);
        }

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

    /*
    * 版本激活
    * */
    async activateVersion(request, response){
        try{
            let userModel = new UserModel();
            let sessionUser = request.session.sessionUser;
            let data = JSON.parse(request.body.data);
            let activateCode = data.activateCode,
                compilationId = data.compilationId;
            let isActivated = true;//调激活接口
            if(!isActivated){
                throw '激活失败';
            }
            //激活成功，更新入库
            let userObjId = mongoose.Types.ObjectId(sessionUser.id);
            let versionInfo = {};
            versionInfo.compilationId = compilationId;
            versionInfo.activatedDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
            //失效信息{invalid: boolean, invalidDate: String}
            versionInfo.invalidInfo = null;
            await userModel.addVersion({_id: userObjId}, versionInfo);
            response.json({error: 0, msg: 'success'});
        }
        catch (error){
            response.json({error: 1, msg: error})
        }
    }
    /*
    * 更新版本状态
    * */
    async updateVersionState(request, response){
        try{
            let userModel = new UserModel();
            let activated = request.body.activated,
                userId = request.body.userId,
                compilationId = request.body.compilationId;
            if(activated){
                let versionInfo = {};
                versionInfo.compilationId = compilationId;
                versionInfo.activatedDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
                versionInfo.invalidInfo = null;
                await userModel.addVersion({_id: mongoose.Types.ObjectId(userId)}, versionInfo);
            }
            else{
                await userModel.removeVersion(userId, compilationId);
            }
            response.json({error: 0, msg: 'success'});
        }
        catch (error){
            response.json({error: 1, msg: error});
        }
    }

    /*
    * 获取用户版本信息
    * */
    async getVersionInfo(request, response){
        try{
            let userModel = new UserModel();
            let userId = request.session.sessionUser.id;
            let userData = await userModel.findDataById(userId);
            let versionInfo = userData ? userData.versionInfo ? userData.versionInfo : [] : [];
            response.json({error: 0, msg: 'success', data: versionInfo});
        }
        catch(error){
            response.json({error: 1, msg: error, data: null});
        }
    }

    /*
    * 获取用户信息
    * */
    async getUserByMobile(req, res){
        try{
            let userModel = new UserModel();
            let data = JSON.parse(req.body.data);
            let userData = await userModel.findDataByMobile(data.mobile);
            res.json({error: 0, msg: 'success', data: userData});
        }
        catch (err){
            res.json({error: 1, msg: err, data: null});
        }
    }
    async getUsers(req, res){
        try{
            let data = JSON.parse(req.body.data);
            let userObjIDs = [];
            for(let userID of data.userIDs){
                userObjIDs.push(mongoose.Types.ObjectId(userID));
            }
            let users = await userData.find({_id: {$in: userObjIDs}});
            res.json({error: 0, msg: 'success', data: users});
        }
        catch (err){
            res.json({error: 1, msg: err, data: null});
        }
    }

    /*
    * 更改用户账号登录方式
    * */
    async changeIsSmsLogin(request, response) {
        try{
            let status = request.body.status;
            let userModel = new UserModel();
            let userId = request.session.sessionUser.id;
            let result = await userModel.updateUser({ _id: userId }, { isSmsLogin: status });
            if (result) {
                response.json({error: 0, msg: 'success', data: null});
            } else {
                throw '更新失败';
            }
        }
        catch(error){
            response.json({error: 1, msg: error, data: null});
        }
    }

    /*
    * 更改异常登录通知
    * */
    async changeIsLoginValid(request, response) {
        try{
            let status = request.body.status;
            let userModel = new UserModel();
            let userId = request.session.sessionUser.id;
            let result = await userModel.updateUser({ _id: userId }, { isLoginValid: status });
            if (result) {
                response.json({error: 0, msg: 'success', data: null});
            } else {
                throw '更新失败';
            }
        }
        catch(error){
            response.json({error: 1, msg: error, data: null});
        }
    }

    async isFree(req, res) {
        try {
            const sessionVersion = req.session.compilationVersion;
            const userModel = new UserModel();
            const isFree = userModel.isFreeFromSession(sessionVersion);
            res.json({ error: 0, msg: 'success', data: { isFree } });
        } catch (err) {
            res.json({ error: 1, msg: String(err), data: null });
        }
    }

    // /**
    //  * 是否时免费版用户
    //  */
    // async isFree(request, response) {
    //     try{
    //         const compilationId = request.session.sessionCompilation.compilationId;
    //         const userModel = new UserModel();
    //         const userId = request.session.sessionUser.ssoId;
    //         const userData = await userModel.findDataBySsoId(userId);
    //         const upgrade_list = userData ? userData.upgrade_list : [];
    //         let free = false;
    //         if (upgrade_list && upgrade_list.length > 0) {
    //             const upgrade = upgrade_list.find(function (item) {
    //                 return item.compilationID === compilationId && item.isUpgrade === true;
    //             });
    //             if (upgrade) {
    //                free = true;
    //             }
    //         }
    //         response.json({error: 0, data: free});
    //     }
    //     catch(error){
    //         response.json({error: 1, msg: error, data: null});
    //     }
    // }
}

module.exports = UserController;
