/**
 * 用户相关控制器
 *
 * @author CaiAoLin
 * @date 2017/6/13
 * @version
 */
import UserModel from "../models/user_model";
import BaseController from "../../common/base/base_controller";

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 = userData.length <= 0 ? [] : userData[0];

        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,
                area: request.body.area
            };
            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 sessionUser = request.session.sessionUser;
        let userModel = new UserModel();
        let userData = await userModel.findDataByName(sessionUser.username);
        userData = userData.length <= 0 ? [] : userData[0];

        let renderData = {
            userData: userData,
        };
        response.render('users/html/user-safe', renderData);
    }

}

export default UserController;
