/**
 * Created by chen on 2017/7/6.
 */

let mongoose = require('mongoose');
const uuidV1 = require('uuid/v1')
let consts = require('../../main/models/project_consts');
let commonConsts = consts.commonConst;
let _=require("lodash");
let async_n = require("async");
let coeMolde = mongoose.model('std_ration_lib_coe_list');
let ration_coe = mongoose.model('ration_coe');
let glj_calculate_facade = require('./glj_calculate_facade');
const scMathUtil = require('../../../public/scMathUtil').getUtil();


module.exports={
    save:save,
    getData:getData,
    delete_ration_coe:delete_ration_coe
}
let operationMap={
    'ut_create':create_ration_coe,
    'ut_update':update_ration_coe,
    'ut_delete':delete_ration_coe
};
let updateFunctionMap = {
    'normalUpdate':normalUpdate,
    'updateCustomerCoe':updateCustomerCoe,
    'adjustUpdate':adjustUpdate
}

function create_ration_coe(user_id,datas) {
    return function (callback) {
        console.log(`datas====================================================================================================`);
        console.log(datas);
        let ration_coe_list=datas.ration_coe_list;
        var tasks=[];
        for(let i=0;i<ration_coe_list.length;i++){
            ration_coe_list[i].ID = uuidV1();
            ration_coe_list[i].seq = i;
            tasks.push(get_lib_coe_info(ration_coe_list[i]));
        }
        async_n.parallel(tasks,(err,results)=>{
            if(err){
                callback(err,results)
            }else {
                ration_coe.insertMany(results,(err,doc)=>{
                    if(err){
                        callback(err,null);
                    }else {
                        let returndata ={
                            updateTpye:commonConsts.UT_CREATE,
                            moduleName:'ration_coe',
                            data:results
                        }
                        callback(null,returndata)
                    }
                });
            }
        })
    }
}

function update_ration_coe(user_id,datas) {
    if(datas.updateFunction){
        return updateFunctionMap[datas.updateFunction](user_id,datas);
    }else {
        return normalUpdate(user_id,datas);
    }
}

function normalUpdate(user_id,datas) {
    return function(callback) {
        ration_coe.update(datas.query,datas.doc,(err,result)=>{
            if(err){
                callback(err,'');
            }else {
                let returndata ={
                    moduleName:'ration_coe',
                    data:{
                        updateTpye:commonConsts.UT_UPDATE,
                        query:datas.query,
                        doc:datas.doc
                    }
                }
                callback(null,returndata);
            }
        })
    }
}

function updateCustomerCoe(user_id,datas) {
    return function(callback) {
        doCustomerCoeUpdateTasks(datas).then((result)=>{
            if(result.err){
                callback(result.err,'');
            }else {
                let coeReturn = {
                    moduleName:'ration_coe',
                    data:{
                        updateTpye:commonConsts.UT_UPDATE,
                        query:result.coeResult.query,
                        doc:result.coeResult.doc
                    }
                }
                let ration_glj_data ={
                    moduleName:'ration_glj',
                    data:{
                        updateTpye:commonConsts.UT_UPDATE,
                        quantityRefresh:true,
                        glj_result:result.cal_result.glj_result
                    }
                };
                let ration_data ={
                    moduleName:'ration',
                    data:{
                        updateTpye:commonConsts.UT_UPDATE,
                        stateRefresh:true,
                        rationID:result.cal_result.rationID,
                        adjustState:result.cal_result.adjustState
                    }
                };
                callback(null,[coeReturn,ration_glj_data,ration_data]);
                console.log('update end');
            }
        })

    }
}

 function adjustUpdate(user_id,datas) {
    return function(callback) {
        doAdjustUpdate(datas).then((result)=>{
            if(result.err){
                callback(result.err,'');
            }else {
                let coeReturn = {
                    moduleName:'ration_coe',
                    data:{
                        updateTpye:commonConsts.UT_UPDATE,
                        query:datas.query,
                        doc:datas.doc
                    }
                }
                let ration_glj_data ={
                    moduleName:'ration_glj',
                    data:{
                        updateTpye:commonConsts.UT_UPDATE,
                        quantityRefresh:true,
                        glj_result:result.cal_result.glj_result
                    }
                };
                let ration_data ={
                    moduleName:'ration',
                    data:{
                        updateTpye:commonConsts.UT_UPDATE,
                        stateRefresh:true,
                        rationID:result.cal_result.rationID,
                        adjustState:result.cal_result.adjustState
                    }
                };
                callback(null,[coeReturn,ration_glj_data,ration_data]);
                console.log('update end');
            }
        })
    }
}

async function doAdjustUpdate (datas){
    let result = {
        err:null
    }
    try{
        await ration_coe.update(datas.query,datas.doc);
        let cal_result = await glj_calculate_facade.calculateQuantity({projectID:datas.query.projectID,rationID:datas.query.rationID});
        result.cal_result =cal_result;
        return result;
    }catch (err){
        result.err = err;
        console.log(err);
        return result;
    }
}

async function doCustomerCoeUpdateTasks(datas) {
    let result = {
        err:null
    }
    try{
        let doc =datas.doc;
        doc.isAdjust = 1;
        doc.content = generationContent(doc.coes);
        let query = {
            ID:datas.query.ID,
            projectID:datas.query.projectID
        }
        await ration_coe.update(query,datas.doc);
        result.coeResult ={
                query:query,
                doc:doc
        };
        let cal_result = await glj_calculate_facade.calculateQuantity({projectID:datas.query.projectID,rationID:datas.query.rationID});
        result.cal_result =cal_result;
        return result;
    }catch (err){
        result.err = err;
        console.log(err);
        return result;
    }
}

function generationContent(coes) {
    let rationAmount = coes[0].amount;
    let string ='';
    if(_.every(coes,'amount',rationAmount)){
        string = coes[0].coeType + 'x'+rationAmount;
    }else {
        let context_arr =[];
        for(let i =1;i<coes.length;i++){
            context_arr.push( coes[i].coeType + 'x'+coes[i].amount);
        }
        string = context_arr.join(',');

    }
    return string;
}


function delete_ration_coe(data) {
    return function (callback) {
        ration_coe.deleteMany({projectID: data.projectID, rationID: data.ID},(err,result)=>{
            commonCallback(callback,result,err)
        });
    }
}


function get_lib_coe_info(ration_coe) {
    return function (cb) {
        if(ration_coe.coeID == -1){//自定义系数
            cb(null,ration_coe);
        }else {
           let query ={
                "libID": ration_coe.libID,
                "ID": ration_coe.coeID,
                "$or": [{"isDeleted": null}, {"isDeleted": false}]
            };
            coeMolde.findOne(query,(err,coe)=>{
                if(err){
                    cb(err,'')
                }else {
                    ration_coe.name = coe.name;
                    ration_coe.content = coe.content;
                    ration_coe.isAdjust=0;
                    ration_coe.coes = coe.coes;
                    cb(null,ration_coe);
                }
            })
        }
    }
}



function getData(projectID, callback) {
    ration_coe.find({'projectID':projectID}).sort('seq').exec((err,datas)=>{
        if(err){
            callback(1, '', null);
        }else {
            callback(0, consts.projectConst.RATION_COE, datas);
        }
    })
}

function save (user_id, datas, callback) {
    let operations=[];
    if(_.isArray(datas)){
        for(let i=0;i<datas.length;i++){
            operations.push(operationMap[datas[i].updateType](user_id,datas[i]));
        }
    }else {
        operations.push(operationMap[datas.updateType](user_id,datas));
    }
    async_n.parallel(operations,function (err,results) {
        if(err){
            callback(err,'');
        }else {
            if(results.length==1){
                callback(null,results[0])
            }else {
                callback(null,results)
            }
        }
    })
}

function commonCallback(callback,result,err) {
    if(err){
        callback(err,'');
    }else {
        callback(null,result);
    }
}