'use strict';

/**
 *
 *
 * @author Zhong
 * @date 2018/5/24
 * @version
 */

import mongoose from 'mongoose';
import async from 'async';
import moment from 'moment';
// const SMS = require('../../users/models/sms');
const projectModel = mongoose.model('projects');
const projSettingModel = mongoose.model('proj_setting');
const calcProgramModel = mongoose.model('calc_programs');
const labourCoeModel = mongoose.model('labour_coes');
const billsModel = mongoose.model('bills');
const rationModel = mongoose.model('ration');
const projGljModel = mongoose.model('glj_list');
const rationGljModel = mongoose.model('ration_glj');
const rationCoeMolde = mongoose.model('ration_coe');
const installationModel = mongoose.model('installation_fee');
const rationInstallationModel = mongoose.model('ration_installation');
const rationTemplateModel  = mongoose.model('ration_template');
const quantityDetailModel = mongoose.model('quantity_detail');
const unitPriceFileModel = mongoose.model('unit_price_file');
const unitPriceModel = mongoose.model('unit_price');
const mixRatioModel = mongoose.model('mix_ratio');
const feeRateFileModel = mongoose.model('fee_rate_file');
const feeRateModel = mongoose.model('fee_rates');
const compleRationSection = mongoose.model('complementary_ration_section_tree');
const evaluateListModel = mongoose.model("evaluate_list");
const bidListModel = mongoose.model("bid_evaluation_list");
const contractorListModel = mongoose.model("contractor_list");
const shareListModel = mongoose.model('share_list');
const userModel = mongoose.model('users');
// const compilationModel = mongoose.model('compilation');


//删除垃圾数据
async function clearJunkData(callback){
    let functions = [];
    //获取彻底删除了的项目
    let junkProjs = await projectModel.find({'deleteInfo.deleted': true, 'deleteInfo.completeDeleted': true}, '-_id ID').lean();
    let junkProjIds = [];
    for(let jProj of junkProjs){
        junkProjIds.push(jProj.ID);
    }
    if(junkProjIds.length > 0){
        //清除proj_setting
        functions.push(function(cb){
            projSettingModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除calcProgram
        functions.push(function(cb){
            calcProgramModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除labourCoe
        functions.push(function(cb){
            labourCoeModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除bills
        functions.push(function(cb){
            billsModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除ration
        functions.push(function(cb){
            rationModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除project_glj
        functions.push(function(cb){
            projGljModel.remove({project_id: {$in: junkProjIds}}, cb);
        });
        //清除ration_glj
        functions.push(function(cb){
            rationGljModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除ration_coe
        functions.push(function(cb){
            rationCoeMolde.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除installation_fee
        functions.push(function(cb){
            installationModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除ration_installation
        functions.push(function(cb){
            rationInstallationModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除ration_installation
        functions.push(function(cb){
            rationTemplateModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除quantity_detail
        functions.push(function(cb){
            quantityDetailModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除暂估材料
        functions.push(function(cb){
            evaluateListModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除评标材料
        functions.push(function(cb){
            bidListModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
        //清除承包材料
        functions.push(function(cb){
            contractorListModel.remove({projectID: {$in: junkProjIds}}, cb);
        });
    }
    //彻底删除了的单价文件
    let junkUFs = await unitPriceFileModel.find({'deleteInfo.deleted': true, 'deleteInfo.completeDeleted': true});
    let junkUFIds = [];
    for(let jUF of junkUFs){
        junkUFIds.push(jUF.id);
    }
    if(junkUFIds.length > 0){
        functions.push(function(cb){
            unitPriceModel.remove({unit_price_file_id: {$in: junkUFIds}}, cb);
        });
        functions.push(function(cb){
            mixRatioModel.remove({unit_price_file_id: {$in: junkUFIds}}, cb);
        });
    }
    //彻底删除了的费率文件
    let junkFFs = await feeRateFileModel.find({'deleteInfo.deleted': true, 'deleteInfo.completeDeleted': true});
    let junkFFIds = [];
    for(let jFF of junkFFs){
        junkFFIds.push(jFF.feeRateID);
    }
    if(junkFFIds.length > 0){
        functions.push(function(cb){
            feeRateModel.remove({ID: {$in: junkFFIds}}, cb);
        });
    }
    //清除
    if(functions.length > 0){
        async.parallel(functions, async function(err, result){
            if(!err){
                //清除项目
                await projectModel.remove({ID: {$in: junkProjIds}});
                // 删除分享信息
                await shareListModel.remove({projectID: {$in: junkProjIds}});
                //清除单价文件
                await unitPriceFileModel.remove({id: {$in: junkUFIds}});
                //清除费率文件
                await feeRateFileModel.remove({feeRateID: {$in: junkFFIds}});
            } else {
                console.log(err);
            }
            if(callback) callback(err);
        });
    }
    else {
        if(callback) callback(0);
    }
}



//删除假删除数据
/*
* 1.之前的删除造价书数据，都是做的假删除，这部分数据会一直存在并且随着项目重复使用越来越多，现要改为真删除，所以做这个清除功能。
* 2.原假删除包括清单的所有类型(大项费用、分部、分项、补项、清单)、定额的所有类型(定额、数量单价、与定额同级的人材机)
* */
async function clearFakeData(callback) {
    let functions = [];
    //删除清单
    functions.push(function (cb) {
        billsModel.remove({deleteInfo: {$exists: true}}, cb);
    });
    //删除定额
    functions.push(function (cb) {
        rationModel.remove({deleteInfo: {$exists: true}}, cb);
    });
    //删除补充定额章节树
    functions.push(function (cb) {
        compleRationSection.remove({deleteInfo: {$exists: true}}, cb);
    });
    async.parallel(functions, async function(err, result){
        if(callback){
            callback(err);
        }
    });
}

/*
* 每天定时清理用户限期的专业版编办，降为免费公用版。
* */
async function checkUserCompilationStatus(callback) {
    let functions = [];
    let today = moment(new Date()).format('YYYY-MM-DD');
    let userList = await userModel.find({upgrade_list: {$elemMatch:{ deadline: today }}});
    if (userList.length > 0) {
        for (let user of userList) {
            let ssoId = JSON.parse(JSON.stringify(user)).ssoId; // 坑啊，没法直接获取到user.ssoId，要转义
            for (let cul of user.upgrade_list) {
                if (cul.deadline === today) {
                    // cul.deadline = '';
                    cul.isUpgrade = false;
                }
            }
            functions.push(function (cb) {
                userModel.update({ssoId: ssoId}, {upgrade_list: user.upgrade_list}, { safe: true }, cb);
            });
        }
    }
    if(functions.length > 0){
        async.parallel(functions, async function(err, result){
            if(callback){
                callback(err);
            }
        });
    } else {
        if(callback) callback(0);
    }

}

/*
* 为每天降为免费公用版的用户发送降级短信。
* */
// async function sendCompilationStatusSms(callback) {
//     let functions = [];
//     let today = moment(new Date()).format('YYYY-MM-DD');
//     let userList = await userModel.find({upgrade_list: {$elemMatch:{ deadline: today }}});
//     if (userList.length > 0) {
//         const Sms = new SMS();
//         for (let user of userList) {
//             // let ssoId = JSON.parse(JSON.stringify(user)).ssoId;
//             for (let cul of user.upgrade_list) {
//                 if (cul.deadline === today) {
//                     // cul.deadline = '';
//                     // cul.isUpgrade = false;
//                     // 发送短信
//                     let compilationData = await compilationModel.findOne({_id: cul.compilationID});
//                     await Sms.sendProductMsg(user.mobile, 2, user.real_name, compilationData.name, '');
//                 }
//             }
//             // functions.push(function (cb) {
//             //     userModel.update({ssoId: ssoId}, {upgrade_list: user.upgrade_list}, { safe: true }, cb);
//             // });
//         }
//     }
//     if(functions.length > 0){
//         async.parallel(functions, async function(err, result){
//             if(callback){
//                 callback(err);
//             }
//         });
//     } else {
//         if(callback) callback(0);
//     }
// }

const sysSchedule = {
    clearJunkData,
    clearFakeData,
    checkUserCompilationStatus,
    // sendCompilationStatusSms,
};

//export {sysSchedule as default}
module.exports = sysSchedule;
