/**
 * 前台用户相关数据模型
 *
 * @author CaiAoLin
 * @date 2017/6/12
 * @version
 */
import mongoose from "mongoose";
import Moment from "moment";
import BaseModel from "../../common/base/base_model";
const projectModel = mongoose.model('projects');
const unitPriceFileModel = mongoose.model('unit_price_file');
const feeRateFileModel = mongoose.model('fee_rate_file');
const optionsModel = mongoose.model('options');
const settingModel = mongoose.model('setting');
const messageModel = mongoose.model('user_message');
const logModel = mongoose.model('log');
const rptCfgModel =  mongoose.model("rpt_cfg");
const rptCusCfgModel = mongoose.model("rpt_customize_cfg");
const comRationSecTreeModel  = mongoose.model('complementary_ration_section_tree');
const blockLibModel =  mongoose.model('blockLibsModel');
const comGLJLibMode =  mongoose.model('complementary_glj_lib');
const comGLJSectionModel = mongoose.model('complementary_glj_section');
const comRationItemsModel = mongoose.model('complementary_ration_items');
const comRationCoeModel = mongoose.model('complementary_ration_coe_list');
const comRationInstalModel = mongoose.model('complementary_ration_installation');
const comRationInstalSectionModel = mongoose.model('complementary_ration_installationSection');
const rptTplTreeMode =  mongoose.model("rpt_tpl_tree");
let sysSchedule = require('../../sys_tools/models/sys_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('users');
        parent.init();
    }

    /**
     * 获取用户信息
     *
     * @param {object} condition
     * @param {number} page
     * @param {Number} pageSize
     * @return {promise}
     */
    async getByID(condition) {
        let user = await this.db.findOne(condition);
        //企业所在省份、类型、规模等转换
        if(this.isDef(user.province)) user._doc.province = this.province[user.province];
        if(this.isDef(user.company_type)) user._doc.company_type = this.companyType[user.company_type];
        if(this.isDef(user.company_scale)) user._doc.company_scale = this.companyScale[user.company_scale];
        if(this.isDef(user.create_time)) user._doc.create_time = Moment(user.create_time).format('YYYY-MM-DD HH:mm:ss');
        if(this.isDef(user.last_login)) user._doc.last_login = Moment(user.last_login).format('YYYY-MM-DD HH:mm:ss');
        return user;
    }



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

        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 keyword = request.query.keyword;
        if (keyword !== '' && keyword !== undefined) {
            condition.$or = [{real_name : {$regex: keyword}},{email : {$regex: keyword}},{mobile : {$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};
    }

    /**
     * 获取daymsg
     *
     */
    getDayMsg(index){
        return this.dayMsg[index];
    }
    async deleteUser(userID,managerID){
        //把用户的项目，单价文件，费率文件标记为真删除状态，然后统一调用清除项目数据的方法
        let deleteInfo = {
            deleted:true,
            deleteDateTime : new Date(),
            deleteBy:managerID,
            completeDeleted:true
        };
        //标记删除
        await unitPriceFileModel.updateMany({"user_id":userID},{"deleteInfo":deleteInfo});
        await feeRateFileModel.updateMany({"userID":userID},{"deleteInfo":deleteInfo});
        await projectModel.updateMany({"userID":userID},{"deleteInfo":deleteInfo});
        //删除项目相关数据
        await sysSchedule.clearJunkData();

        //删除用户私有数据
        await optionsModel.deleteMany({"user_id":userID});
        await settingModel.deleteMany({"user_id":userID});
        await messageModel.deleteMany({"user_id":userID});
        await logModel.deleteMany({"user_id":userID});

        await rptCfgModel.deleteMany({"userId":userID});
        await rptCusCfgModel.deleteMany({"userId":userID});
        await comRationSecTreeModel.deleteMany({"userId":userID});
        await comGLJLibMode.deleteMany({"userId":userID});
        await rptTplTreeMode.deleteMany({"userId":userID});
        await comGLJSectionModel.deleteMany({"userId":userID});
        await comRationItemsModel.deleteMany({"userId":userID});
        await comRationCoeModel.deleteMany({"userId":userID});
        await comRationInstalModel.deleteMany({"userId":userID});
        await comRationInstalSectionModel.deleteMany({"userId":userID});
        await blockLibModel.deleteMany({"userID":userID});

        //最后删除用户信息：
        await this.db.model.deleteOne({_id:mongoose.Types.ObjectId(userID)});
        return "success";
    }

}

export default UserModel;