/**
 * Created by jimiz on 2017/4/1.
 */
let mongoose = require("mongoose");
let async = require("async");
let counter = require("../../../public/counter/counter.js");
let consts = require('./project_consts');
let projectConsts = consts.projectConst;
let commonConsts = consts.commonConst;
let quantity_detial = require('../facade/quantity_detail_facade');
let projectModel = mongoose.model('projects');
let rationModel = mongoose.model('ration');
let rationGljModel = mongoose.model('ration_glj');
let rationCoeModel = mongoose.model('ration_coe');
let rationInstModel = mongoose.model('ration_installation');
let quantityDelModel = mongoose.model('quantity_detail');
const { fixedFlag } = require('../../../public/common_constants');

let bills = mongoose.model("bills");
let baseModel = require('./base_model');
const uuidV1 = require('uuid/v1');
const billType ={
    DXFY:1,//大项费用
    FB:2,//分部
    FX:3,//分项
    BILL:4,//清单
    BX:5//补项
};

class billsModel extends baseModel {
    constructor () {
        super(bills);
    };

    getData (projectID, callback) {
        //已经改成真删除了 {'$or': [{projectID: projectID, deleteInfo: null}, {projectID: projectID, 'deleteInfo.deleted': {$in: [null, false]}}]}
        this.model.find({projectID: projectID}, '-_id', function(err, datas){
            if (!err) {
                callback(0, projectConsts.BILLS, datas);
            } else {
                callback(1, projectConsts.BILLS, null);
            };
        });
    };

    save (user_id, datas, callback) {
        let functions = [];
        let data;

        function saveOne(doc) {
            return function (cb) {
                switch (doc.updateType) {
                    case commonConsts.UT_UPDATE:
                        async.parallel([      // CSL,2018.01.10 如果是总造价清单，要将4个汇总金额写到projects表中
                            function (asyncCB) {
                                bills.update({projectID: doc.updateData.projectID, ID: doc.updateData.ID,deleteInfo: null}, doc.updateData, asyncCB);
                            },
                            function (asyncCB) {
                                if (doc.updateData.summaryFees){
                                    // console.log('%%%%%%%%%%%%%%%%%%%  ' + doc.updateData.projectID + ' | ' + JSON.stringify(doc.updateData.summaryFees));
                                    projectModel.update({ID: doc.updateData.projectID}, {"summaryFees": doc.updateData.summaryFees}, asyncCB);
                                }else {
                                    asyncCB(null, {});
                                };
                            }
                        ], function(err,result){
                            cb(err, {});
                        });
                        break;
                    case commonConsts.UT_CREATE:
                        bills.create(doc.updateData, cb);
                        break;
                    case commonConsts.UT_DELETE:
                        doc.updateData.deleteInfo = {deleted: true, deleteDateTime: new Date(), deleteBy: user_id};
                       //bills.update({projectID: doc.updateData.projectID, ID: doc.updateData.ID}, doc.updateData, cb);
                        bills.deleteOne({projectID: doc.updateData.projectID, ID: doc.updateData.ID},cb);
                        break;
                }
            }
        }
        for (let i = 0; i < datas.length; i++){
            data = datas[i];
            functions.push(saveOne(data));
            quantity_detial.quantityEditChecking(data,'bills',functions);
        }
        async.parallel(functions, function(err,result){
            let returnData = {
                moduleName:'bills',
                data:result
            };
            callback(err, returnData);
        });
    };

    getItemTemplate (callback) {
        let data = new bills;
        /* to do: 需要根据标准配置库填充fees和flags字段，是否需要更多的参数？ */
        callback(0, '', data);
    };

    allocIDs (IDStep, callback) {
        counter.counterDAO.getIDAfterCount(counter.moduleName.bills, IDStep, function(err, highID){
            let lowID = highID - IDStep + 1;
            callback(0, '', {lowID: lowID, highID: highID});
        });
    };
    //zhong 2017-9-1
    updateCharacterContent(findSet, updateObj, txtObj, callback) {
        let updateSet = {};
        updateSet[updateObj.field] = updateObj.updateArr;
        if(txtObj && typeof txtObj !== 'undefined'){
            updateSet[txtObj.field] = txtObj.text;
        }
       bills.update(findSet, updateSet, function (err) {
           if(err){
               callback(1, '更新失败');
           }
           else{
               callback(0, '更新成功');
           }
       });
    };
    async updateBills(updateDatas){
        let bulk = [];
        for(let updateData of updateDatas){
            bulk.push({updateOne: {filter: updateData.findSet, update: {$set: updateData.updateData}}});
        }
        await bills.bulkWrite(bulk);
    };
    async updateBill(findSet, updateData) {
        let update = {};
        if (!updateData instanceof Array) {
            return false;
        }

        for (const tmp of updateData) {
            if (tmp === undefined) {
                continue;
            }
            update[tmp.field] = tmp.value;
        }

        if (Object.keys(update).length <= 0) {
            return false;
        }

        return bills.update(findSet, update);
    };
    async importBills(bills){
        let operations = [];
        for(let bill of bills){
            operations.push({insertOne: {document: bill}});
        }
        return await this.model.bulkWrite(operations);
    }
    //删除清单节点的所有子节点及其他附带数据
    async deepDeleteBill(bills, userID){
        let bill_ids = [],
            ration_ids = [];
        let me = this;
        async function findBillsChildren(bills){
            if(bills.length > 0){
                let ids = getIDs(bills);
                bill_ids = bill_ids.concat(ids);
                let findBills = await me.model.find({ParentID: {$in: ids}, deleteInfo: null});
                await findBillsChildren(findBills);
            }
        }
        function getIDs(datas){
            let ids = [];
            for(let data of datas){
                ids.push(data.ID);
            }
            return ids;
        }
        await findBillsChildren(bills);
        //剔除第一个节点
        bill_ids = bill_ids.slice(1);
        //获取删除清单下的所有定额
        let rations = await rationModel.find({billsItemID: {$in: bill_ids}, deleteInfo: null}, 'ID');
        ration_ids = ration_ids.concat(getIDs(rations));
        //deep delete datas
        let deleteInfo = {deleted: true, deleteDateTime: new Date(), deleteBy: userID};
        if(bill_ids.length > 0){
            //删除bills
            await me.model.deleteMany({ID: {$in: bill_ids}});
            //删除bill-quantity_detail
            await quantityDelModel.deleteMany({billID: {$in: bill_ids}});
        }
        if(ration_ids.length > 0){
            //删除rations
            await rationModel.deleteMany({ID: {$in: ration_ids}});
            //删除ration-glj
            await rationGljModel.deleteMany({rationID: {$in: ration_ids}});
            //删除ration-coe
            await rationCoeModel.deleteMany({rationID: {$in: ration_ids}});
            //删除ration-quantity_detail
            await quantityDelModel.deleteMany({rationID: {$in: ration_ids}});
        }
        return {bill: bill_ids, ration: ration_ids};
    }
}

module.exports = new billsModel();