/**
 * 用户业务模型
 *
 * @author CaiAoLin
 * @date 2017/6/9
 * @version
 */
import mongoose from "mongoose";
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-50', '50-100', '100-500', '500+'];


    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = mongoose.model('user');
        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) {
                        console.log('111');
                        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 userDataFromDb2 = await this.findDataBySsoId(userData.ssoId);
        let userDataFromDb = await this.findDataByName(userData.username);  //后面新增的账号可淘汰这方法，当前使用是为了兼容旧的账号
        let result = false;
        userData.latest_login = new Date().getTime();
        if (userDataFromDb === null && userDataFromDb2 === null) {
            // 不存在用户则入库
            this.setScene();//恢复场景，用户有可能公司real_name等信息为空，不能设置为必填
            result = await this.addUser(userData);
            userDataFromDb = result;
        } else {
            // 存在则新增登录信息并更新账号信息
            // let condition = {ssoId: sessionUser.ssoId};
            let condition = {username: userData.username};
            let UpdateData = {
                email : userData.email,
                mobile : userData.mobile,
                ssoId : userData.ssoId,
                latest_login:userData.latest_login
            };
            let updateResult = await this.updateUser(condition,UpdateData);
            if (updateResult.ok === 1) {
                let logModel = new LogModel();
                result = await logModel.addLoginLog(userDataFromDb._id, request);
            }
        }
        request.session.sessionUser.id = userDataFromDb._id;
        request.session.sessionUser.real_name = userDataFromDb.real_name;
        request.session.sessionUser.latest_used = userDataFromDb.latest_used;//设置最近使用的编办

        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;
            case '':
                this.model.schema.path('real_name').required(false);
                this.model.schema.path('company').required(false);
                this.model.schema.path('province').required(false);
                this.model.schema.path('version').required(false);
        }*/
    }

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

    /**
     * 根据ssoID查找数据
     *
     * @param {string} ssoId
     * @return {object}
     */
    findDataBySsoId(ssoId) {
        return this.db.findOne({ssoId: ssoId});
    }

    /**
     * 根据手机号查找数据
     *
     * @param {string} mobile
     * @return {object}
     */
    findDataByMobile(mobile) {
        return this.db.findOne({mobile: mobile});
    }

    /**
     * 根据userId查找数据
     *
     * @param {string} ssoId
     * @return {object}
     */
    async findDataById(id) {
        let objId = mongoose.Types.ObjectId(id);
        return await this.db.findOne({_id: objId});
    }

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

    //更新最近使用编办ID
    async updateLatestUsed(userID,compilationID){
        if(userID && compilationID){
            return await this.db.update({'_id':userID},{'latest_used':compilationID});
        }
    }

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

    async addVersion(condition, versionInfo){
        return await this.db.findOneAndUpdate(condition, {$addToSet: {versionInfo: versionInfo}});
    }

    async removeVersion(userId, compilationId){
        let userObjId = mongoose.Types.ObjectId(userId);
        return await this.db.findOneAndUpdate({_id: userObjId}, {$pull: {versionInfo: {compilationId: compilationId}}});
    }

    /**
     * 判断用户使用免费版还是专业版
     *
     * @param ssoId
     * @param compilationId
     * @return {version}
     */
    async getVersionFromUpgrade(ssoId, compilationId){
        let version = '免费版';
        let userData = await this.findDataBySsoId(ssoId);
        if (userData.upgrade_list !== undefined) {
            let compilationInfo = userData.upgrade_list.find(function (item) {
                return item.compilationID === compilationId;
            });
            if (compilationInfo !== undefined && compilationInfo.isUpgrade === true) {
                version = '专业版';
            }
        }
        return version;
    }

}

export default UserModel;