/**
 * 用户业务模型
 *
 * @author CaiAoLin
 * @date 2017/6/9
 * @version
 */
const mongoose = require("mongoose");
const Request = require("request");
const BaseModel = require("../../common/base/base_model");
const LogModel = require("./log_model");

class UserModel extends BaseModel {

    /**
     * 企业所在地区
     *
     * @var {object}
     */
    province = ['北京', '天津', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '上海', '江苏', '浙江', '安徽',
        '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '广西', '海南', '重庆', '四川', '贵州', '云南', '西藏',
        '陕西', '甘肃', '青海', '宁夏', '新疆', '台湾', '香港', '澳门',];

    /**
     * 企业类型
     *
     * @var
     */
    companyType = ['建设单位', '设计单位',  '施工单位', '监理单位', '审核单位', '咨询公司', '招标代理', '住建部', '财政', '审计',
        '造价管理站', '学校', '个人', '其他'];

    /**
     * 企业规模
     *
     * @var
     */
    companyScale = ['1-50', '50-100', '100-500', '500+'];

    /**
     * 最近天数
     *
     * @var
     */
    dayMsg = ['所有', '最近24小时', '最近3天', '最近7天', '最近30天'];


    /**
     * 构造函数
     *
     * @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');
                        reject('请求错误');
                    }
                    if (postResponse.statusCode !== 200) {
                        reject('通行证验证失败！');
                    }
                    resolve(body);
                });
            } catch (error) {
                reject([]);
            }
        });
    }

    /**
     * 根据用户手机调用SSO接口获取个人信息
     *
     * @param {string} account
     * @return {object}
     */
    async getInfoFromSSOAccount(account) {
        let postData = {
            url: 'http://sso.smartcost.com.cn/building/api/userinfo',
            form: {account: account},
            encoding: 'utf8'
        };
        return new Promise(function (resolve, reject) {
            try {
                // 请求接口
                Request.post(postData, function (err, postResponse, body) {
                    if (err) {
                        console.log('111');
                        reject('请求错误');
                    }
                    if (postResponse.statusCode !== 200) {
                        reject('通行证验证失败！');
                    }
                    resolve(body);
                });
            } catch (error) {
                reject([]);
            }
        });
    }

    /**
     * 根据用户手机号码调用SSO接口获取信息
     *
     * @param {string} mobile
     * @param {string} login 1为登录，不存在则是查询
     * @param {string} comefrom 1为来自大司空
     * @return {object}
     */
    async getInfoFromSSOMobile(mobile, login = '1') {
        const fromData = {account: mobile, comefrom: 1};
        if (login === '1') {
            fromData.login = 1;
        }
        let postData = {
            url: 'http://sso.smartcost.com.cn/building/api/mobile/login',
            form: fromData,
            encoding: 'utf8'
        };
        return new Promise(function (resolve, reject) {
            try {
                // 请求接口
                Request.post(postData, function (err, postResponse, body) {
                    if (err) {
                        console.log('111');
                        reject('请求错误');
                    }
                    if(!postResponse) reject('请求错误');
                    if (postResponse.statusCode !== 200) {
                        reject('通行证验证失败！');
                    }
                    resolve(body);
                });
            } catch (error) {
                reject([]);
            }
        });
    }

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

    /**
     * 注册sso账号或修改sso的qq信息
     *
     * @param {string} username
     * @param {string} password
     * @return {object}
     */
    async regForSSO(mobile, qq, pwd = '', name = '') {
        let postData = {
            url: 'http://sso.smartcost.com.cn/building/api/reg',
            form: {mobile: mobile, qq: qq, password: pwd, name: name},
            encoding: 'utf8'
        };
        return new Promise(function (resolve, reject) {
            try {
                // 请求接口
                Request.post(postData, function (err, postResponse, body) {
                    if (err) {
                        console.log('111');
                        reject('请求错误');
                    }
                    if (postResponse.statusCode !== 200) {
                        reject('通行证验证失败！');
                    }
                    resolve(body);
                });
            } catch (error) {
                reject([]);
            }
        });
    }

    /**
     * 标记用户
     *
     * @param {object} userData
     * @param {Object} request
     * @return {Promise}
     */
    async markUser(userData, request = null) {
        let userDataFromDb = await this.findDataBySsoId(userData.ssoId);
        // let userDataFromDb = await this.findDataByName(userData.username);  //后面新增的账号可淘汰这方法，当前使用是为了兼容旧的账号
        let result = false;
        userData.latest_login = new Date().getTime();
        if (userDataFromDb === null) {
            // 不存在用户则入库
            this.setScene();//恢复场景，用户有可能公司real_name等信息为空，不能设置为必填
            result = await this.addUser(userData);
            userDataFromDb = result;
        } else {
            // 存在则新增登录信息并更新账号信息
            let condition = {ssoId: userData.ssoId};
            // let condition = {username: userData.username};
            let UpdateData = {
                email : userData.email,
                mobile : userData.mobile,
                // ssoId : userData.ssoId,
                qq: userData.qq,
                latest_login:userData.latest_login,
                isUserActive: userData.isUserActive,
                token: userData.token
            };
            console.log("updateUser 开始 -------------------------------");
            let updateResult = await this.updateUser(condition,UpdateData);
            console.log("updateUser 完成 -------------------------------");
            if (updateResult.ok === 1) {
                let logModel = new LogModel();
                result = await logModel.addLoginLog(userDataFromDb._id, request);
                console.log("addLoginLog 完成 -------------------------------");
            }
        }
        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, fields) {
        const objId = mongoose.Types.ObjectId(id);
        return fields ? await this.db.findOne({_id: objId}, fields) : await this.db.findOne({_id: objId});
    }

    /**
     * 验证用户token正确性
     * 一个账号不允许多处同时在线，每次登陆都会更新session和数据库的token，每个请求都会比对session和数据库的token
     * @param {String} id - 用户ID
     * @param {String} token - 登陆生成的token
     * @return {Boolean}
     */
    async checkToken(id, token) {
        const user = await this.findDataById(id, '-_id token');
        if (!user.token) { // 兼容第一次上线，已登陆的用户还没token，需要返回验证正确
            return true;
        }
        return user.token === token;
    }

    async findDataByAccount(account) {
        let userinfo = await this.db.findOne({mobile: account});
        let userinfo2 = await this.db.findOne({email: account});
        if (userinfo) {
            return userinfo;
        } else if (userinfo2) {
            return userinfo2;
        } else {
            return false;
        }
    }

    /**
     * 新增用户
     *
     * @param {object} userData
     * @return {Promise|boolean}
     */
    addUser(userData) {
        let insertData = {
            ssoId: userData.ssoId,
            username: userData.username,
            email: userData.email,
            mobile: userData.mobile,
            qq: userData.qq,
            create_time: new Date().getTime(),
            latest_login: new Date().getTime(),
            isUserActive: userData.isUserActive,
            token: userData.token,
            real_name: userData.real_name ? userData.real_name : '',
            province: userData.province ? userData.province : -1,
            company: userData.company ? userData.company : '',
        };
        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 lock = 0;
        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 = '大司空云计价(专业版)';
                if (compilationInfo.lock !== undefined && compilationInfo.lock !== '') {
                    lock = compilationInfo.lock;
                }
            }
        }
        return {version: version, lock: lock};
    }

    /**
     * 判断用户是免费版还是专业版用户
     */
    async isFree(ssoId, compilationId) {
        const userData = await this.findDataBySsoId(ssoId);
        if (!userData) {
            throw '不存在此用户';
        }
        const upgrade_list = userData.upgrade_list;
        let free = true;
        if (upgrade_list && upgrade_list.length > 0) {
            const upgrade = upgrade_list.find(function (item) {
                return item.compilationID === compilationId && item.isUpgrade === true;
            });
            if (upgrade) {
                free = false;
            }
        }
        return free
    }

    /**
     * 从session中判断用户是否是免费版
     * @param {String} sessionVersion
     * @return {Boolean}
     */
    isFreeFromSession(sessionVersion) {
        if (!sessionVersion) {
            return true;
        }
        return sessionVersion.indexOf('免费') >= 0;
    }

    /*
    * 添加联系人，互相添加
    */
    async addContact(userID, contactID) {
        const data = [
            { user: userID, contact: contactID },
            { user: contactID, contact: userID }
        ];
        const task = [];
        for (const { user, contact } of data) {
            const hasThisContact = await this.model.count({_id: mongoose.Types.ObjectId(user), 'contacts.userID': contact});
            // 没有则添加
            if (!hasThisContact) {
                task.push(this.model.update({_id: mongoose.Types.ObjectId(user)}, {$push: {contacts: {userID: contact}}}));
            }
        }
        if (task.length) {
            await Promise.all(task);
        }
    }

    async getContacts(userID) {
        const user = await this.model.findOne({_id: mongoose.Types.ObjectId(userID)}, 'contacts').lean();
        if (!user || !user.contacts || !user.contacts.length) {
            return [];
        }
        const userIDList = user.contacts.map(item => mongoose.Types.ObjectId(item.userID));
        const users = await this.model.find({_id: {$in: userIDList}}, 'real_name mobile company');
        return users;
    }

    /**
     * 获取列表
     *
     * @param {object} condition
     * @param {number} page
     * @param {Number} pageSize
     * @return {promise}
     */
    async getList(condition = null, page = 1, pageSize = 30, sort = {_id:-1}) {
        page = parseInt(page);
        page = page <= 1 ? 1 : page;
        let option = {pageSize: pageSize, offset: parseInt((page - 1) * pageSize), sort: sort};
        console.log(condition, option);

        let userList = await this.db.find(condition, null, option);
        userList = userList.length > 0 ? userList : [];

        return userList;
    }

    /**
     * 获取过滤条件
     *
     * @return {Object}
     */
    getFilterCondition(request) {
        let condition = {};
        let regtime = request.query.regtime;
        regtime = regtime !== '' && regtime !== undefined ? parseInt(regtime) : 0;
        if (regtime !== 0) {
            condition.create_time = this.getTimestamp(regtime);
        }

        //最近登录时间
        let loginTime = request.query.loginTime;
        loginTime = loginTime !== '' && loginTime !== undefined ? parseInt(loginTime) : 0;
        if (loginTime !== 0) {
            condition.latest_login = this.getTimestamp(loginTime);
        }

        let version = request.query.version;
        if(version !== '' && version !== undefined) {
            condition.version = version;
        }
        // 已升级费用定额
        let upGrade = request.query.upGrade;
        if(upGrade !== '' && upGrade !== undefined){
            condition.upgrade_list = {"$elemMatch":{"compilationID":upGrade,"isUpgrade":true}};
        }

        // 最近使用费用定额
        let latestUsed = request.query.latestUsed;
        if(latestUsed !== '' && latestUsed !== undefined){
            condition.latest_used = latestUsed;
        }

        // 最近登录时长
        let onlineTimes = request.query.onlineTimes;
        onlineTimes = onlineTimes !== '' && onlineTimes !== undefined ? parseInt(onlineTimes) : 0;
        if (onlineTimes !== 0) {
            condition.online_times = this.getOnlineTimestamp(onlineTimes);
        }

        // 企业所在地区
        let province = request.query.province;
        province = province !== '' && province !== undefined ? parseInt(province) - 1 : -1;
        if (province !== -1) {
            condition.province = province;
        }

        let keyword = request.query.keyword;
        if (keyword !== '' && keyword !== undefined) {
            condition.$or = [{real_name : {$regex: keyword}},{email : {$regex: keyword}},{mobile : {$regex: keyword}},{qq : {$regex: keyword}},{company : {$regex: keyword}}];
        }

        return condition;
    }

    /**
     * 获取时间戳区间
     *
     * @return {Object}
     */
    getTimestamp(type) {
        let startTime = '';
        switch (type) {
            case 1 :
                startTime = Date.parse(new Date())-86400*1000;
                break;
            case 2 :
                startTime = Date.parse(new Date())-86400*1000*3;
                break;
            case 3 :
                startTime = Date.parse(new Date())-86400*1000*7;
                break;
            case 4 :
                startTime = Date.parse(new Date())-86400*1000*30;
                break;
            default :
                break;
        }
        let endTime =  Date.parse(new Date());
        return startTime === '' ? '' : {'$gte': startTime, '$lt': endTime};
    }

    /**
     * 获取时间戳区间
     *
     * @return {Object}
     */
    getOnlineTimestamp(type) {
        let startTime = 0;
        switch (type) {
            case 1 :
                startTime = 1800*1000;
                break;
            case 2 :
                startTime = 3600*1000;
                break;
            case 3 :
                startTime = 3600*1000*2;
                break;
            case 4 :
                startTime = 3600*1000*3;
                break;
            default :
                break;
        }
        return startTime === 0 ? '' : {'$gte': startTime};
    }

    /**
     * 获取daymsg
     *
     */
    getDayMsg(index){
        return this.dayMsg[index];
    }
}

module.exports = UserModel;
