/**
 * 用户业务模型
 *
 * @author CaiAoLin
 * @date 2017/6/9
 * @version
 */
import userSchema from "./schema/user";
import Request from "request";
import BaseModel from "../../common/base/base_model"
import LogModel from "./log_model";

class UserModel extends BaseModel {

    /**
     * 企业所在地区
     *
     * @var {object}
     */
    province = ['广东省', '北京市'];

    /**
     * 企业类型
     *
     * @var
     */
    companyType = ['设计', '施工'];

    /**
     * 企业类型
     *
     * @var
     */
    companyScale = ['1-20', '20-50', '50-100', '100+'];


    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = userSchema;
        parent.init();
    }

    /**
     * 根据用户名密码调用SSO接口获取信息
     *
     * @param {string} username
     * @param {string} password
     * @return {object}
     */
    async getInfoFromSSO(username, password) {
        let postData = {
            url: 'http://sso.smartcost.com.cn/api/jzlogin',
            form: {username: username, userpasswd: password},
            encoding: 'utf8'
        };
        return new Promise(function (resolve, reject) {
            try {
                // 请求接口
                Request.post(postData, function (err, postResponse, body) {
                    if (err) {
                        throw '请求错误';
                    }
                    if (postResponse.statusCode !== 200) {
                        throw '通行证验证失败！';
                    }
                    resolve(body);
                });
            } catch (error) {
                reject([]);
            }
        });
    }

    /**
     * 标记用户
     *
     * @param {object} userData
     * @param {Object} request
     * @return {Promise}
     */
    async markUser(userData, request = null) {
        let userDataFromDb = await this.findDataByName(userData.username);
        let result = false;

        if (userDataFromDb === null) {
            // 不存在用户则入库
            result = await this.addUser(userData);
            userDataFromDb = result;
        } else {
            // 存在则新增登录信息
            let logModel = new LogModel();
            result = await logModel.addLoginLog(userDataFromDb._id, request);
        }
        request.session.sessionUser.id = userDataFromDb._id;

        return result;
    }

    /**
     * 选择场景
     *
     * @param {string} scene
     */
    setScene(scene = '') {
        switch (scene) {
            case 'saveInfo':
                this.model.schema.path('real_name').required(true);
                this.model.schema.path('company').required(true);
                this.model.schema.path('province').required(true);
                this.model.schema.path('version').required(true);
                break;
        }
    }

    /**
     * 根据用户名查找数据
     *
     * @param {string} username
     * @return {object}
     */
    findDataByName(username) {
        return this.db.findOne({username: username});
    }

    /**
     * 新增用户
     *
     * @param {object} userData
     * @return {Promise|boolean}
     */
    addUser(userData) {
        let insertData = {
            username: userData.username,
            email: userData.email,
            mobile: userData.mobile,
            create_time: new Date().getTime(),
        };
        return this.db.create(insertData);
    }

    /**
     * 更新用户数据
     *
     * @param {object} updateData
     * @return {Promise}
     */
    updateUser(condition, updateData) {
        if (Object.keys(condition).length <= 0 || Object.keys(updateData).length <= 0) {
            return null;
        }
        return this.db.update(condition, updateData);
    }

}

export default UserModel;