/**
 * 用户相关控制器
 *
 * @author CaiAoLin
 * @date 2017/6/13
 * @version
 */
import UserModel from "../models/user_model";
import BaseController from "../../common/base/base_controller";
import LogType from "../../common/const/log_type_const";
import LogModel from "../models/log_model";
import SettingModel from "../models/setting_model";
import SettingType from "../../common/const/setting_type_const";
import CompilationModel from "../models/compilation_model";

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.findDataByName(sessionUser.username);
        userData = Object.keys(userData).length <= 0 ? [] : userData;

        let renderData = {
            userData: userData,
            provinceList: userModel.province,
            companyTypeList: userModel.companyType,
            companyScaleList: userModel.companyScale
        };
        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,
                company_type: request.body.company_type,
                company_scale: request.body.company_scale,
                version: request.body.version
            };
            let sessionUser = request.session.sessionUser;
            // 切换验证场景
            let userModel = new UserModel();
            let condition = {email: sessionUser.email};
            userModel.setScene('saveInfo');
            let result = await userModel.updateUser(condition, updateData);

            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;
            let userModel = new UserModel();
            userData = await userModel.findDataByName(sessionUser.username);

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

            // 获取登录信息
            let logModel = new LogModel();
            let logCount = await logModel.count();
            let pageSize = 3;
            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
        };
        response.render('users/html/user-safe', 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
        };
        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);

                request.session.sessionCompilation = compilationData;
            }
        } catch (error) {
            console.log(error);
        }

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

}

export default UserController;
