/**
 * Created by zhang on 2019/1/2.
 */
module.exports={ //先导出后require可以解决循环引用问题
    changeUnitFile:changeUnitFile,
    changeVvTaxFile:changeVvTaxFile,
    changeAssistProductionFeeRate:changeAssistProductionFeeRate,
    addMixRatioForNew:addMixRatioForNew,
    updateMaterialCalc:updateMaterialCalc,
    updateMaterialCalcTasks:updateMaterialCalcTasks,
    updateUserFreight:updateUserFreight,
    getUserFreights:getUserFreights,
    insertElectrovalence:insertElectrovalence,
    updateElectrovalence:updateElectrovalence
};

const mongoose = require('mongoose');
const ProjectModel = require('../../pm/models/project_model').project;
import UnitPriceFileModel from "../models/unit_price_file_model";
import UnitPriceModel from "../models/unit_price_model";
import MixRatioModel from "../models/mix_ratio_model";
import CounterModel from "../models/counter_model";
import GLJListModel from '../../glj/models/glj_list_model';
let std_glj_lib_gljList_model = mongoose.model('std_glj_lib_gljList');
let original_calc_model = mongoose.model('original_calc');
let freight_calc_model = mongoose.model('freight_calc');
let unit_price_model = mongoose.model('unit_price');
let user_freights_model = mongoose.model('user_freights');
let std_glj_lib_model = mongoose.model('std_glj_lib_map');
let com_electrovalence_model = mongoose.model('com_electrovalence');

let ration_glj = require('../../ration_glj/facade/ration_glj_facade');
const uuidV1 = require('uuid/v1');
let  vvTaxModel =  mongoose.model("std_vehicleVesselTax_items");
let gljUtil = require('../../../public/gljUtil');
let _ = require("lodash");

async function changeUnitFile(projectData,unitFile,type,userID) {
    let projectId = projectData.projectID;
    let changeUnitPriceId = unitFile.id;
    let newName = unitFile.name;
    type = parseInt(type);

        let currentUnitPriceId = await ProjectModel.getUnitPriceFileId(projectId);
        let unitPriceFileModel = new UnitPriceFileModel();

        let insertData = null;
        if (type > 0) {
            let currentUnitPrice = await unitPriceFileModel.model.findOne({id: changeUnitPriceId}).lean();
            if (currentUnitPrice === null) {
                throw '不存在对应单价文件';
            }
            // 获取当前项目的rootProjectId
            let projectData = await ProjectModel.getProject(projectId);
            let rootProjectId = projectData.property.rootProjectID !== undefined ? projectData.property.rootProjectID : 0;

            insertData = currentUnitPrice;
            insertData.root_project_id = rootProjectId;
            newName?insertData.name = newName:'';
            insertData.user_id = userID;
            delete insertData._id;
            delete insertData.id;

        }
        // 获取即将更改的单价文件信息
        let targetUnitPriceFile = type === 0 ? await unitPriceFileModel.findDataByCondition({id: changeUnitPriceId}) :
            await unitPriceFileModel.add(insertData);
        if (targetUnitPriceFile === null) {
            throw '没有找到对应的单价文件';
        }

        // 查找对应单价文件的项目工料机数据
        let unitPriceModel = new UnitPriceModel();
        if(type ===1){//从其它项目复制，则先复制一份数据。
            let needCopyList = await unitPriceModel.model.find({unit_price_file_id: changeUnitPriceId}).lean();
            if(needCopyList){
                let copyList = [];
                for(let n of needCopyList){
                    delete n._id;  // 删除原有id信息
                    delete n.id;
                    n.unit_price_file_id = targetUnitPriceFile.id;
                    copyList.push(n);
                }
                copyList.length>0 ? await unitPriceModel.add(copyList):''; 
                //也要复制一份组成物信息和材料计算信息
                let mixRatioModel = new MixRatioModel();
                await mixRatioModel.copyNotExist(changeUnitPriceId, targetUnitPriceFile.id,{},true);//复制组成物
                await unitPriceModel.copyMaterialNotExist(changeUnitPriceId,targetUnitPriceFile.id,{},true);
            }
        }


        let copyResult = await unitPriceModel.copyNotExist(currentUnitPriceId, targetUnitPriceFile.id,projectId);
        // 复制成功后更改project数据
        if (!copyResult) {
            throw '复制数据失败';
        }

        let changeUnitPriceFileInfo = {
            id: targetUnitPriceFile.id,
            name: targetUnitPriceFile.name
        };
        let result = ProjectModel.changeUnitPriceFileInfo(projectId, changeUnitPriceFileInfo);
        if (!result) {
            throw '切换单价文件失败!';
        }
        //处理车船税记录 - 如果直接从其它项目复制，不用管车船税问题
        if(type !==1) await handleVvTaxForChang(targetUnitPriceFile.id,targetUnitPriceFile.vvTaxFileID);
        return changeUnitPriceFileInfo;
}


async function changeVvTaxFile(data){//对于车船税，现在只是在组成物表中插入信息，取项目工料机时虚拟一条车船况的记录。 因为车船税涉及到切换，清空，单价文件共用等复杂的情况，虚拟一条记录相对好一点。以后不合适可再修改
    let unitFileID = data.unitFileID,newVvTaxFileID = data.newVvTaxFileID;
    let unitPriceFileModel = new UnitPriceFileModel();
    //先更新单价文件中车船税文件ID
    await unitPriceFileModel.model.update({id:unitFileID},{vvTaxFileID:newVvTaxFileID});
    await handleVvTaxForChang(unitFileID,newVvTaxFileID);
}

async function changeAssistProductionFeeRate(data){
    let unitFileID = data.unitFileID,assistProductionFeeRate = data.assistProductionFeeRate;
    let unitPriceFileModel = new UnitPriceFileModel();
    await unitPriceFileModel.model.update({id:unitFileID},{assistProductionFeeRate:assistProductionFeeRate});
}

async function handleVvTaxForChang(unitFileID,newVvTaxFileID) {//切换车船税，选择共用的单价文件时调用
    let mixRatioModel = new MixRatioModel();
    if(!newVvTaxFileID || newVvTaxFileID == ''){//如果新的车船税ID为空，则删除组成物表中车船税的记录
        await mixRatioModel.model.deleteMany({unit_price_file_id:unitFileID,code:'80CCS'});
    }else {//如果是从空选择车船税或者是切换车船税，则要插入或修改车船税组成物信息
        let vvTaxItems = await vvTaxModel.find({libID:newVvTaxFileID});
        if(vvTaxItems.length <=0) return;
        let allMixRatio = await mixRatioModel.model.find({unit_price_file_id:unitFileID});//先查出所有组成物
        let mxiMap =  _.groupBy(allMixRatio,"connect_key");
        let counterModel = new CounterModel();
        let useMap = {},tasks = [];
        for(let item of vvTaxItems){
            let connect_key = gljUtil.getIndex(item);
            if(mxiMap[connect_key]){//如果存在，说明要插入或更新车船税
                let ccs = _.find(mxiMap[connect_key],{'code':'80CCS'});
                if(ccs){//存在且不相等则更新
                   if(ccs.consumption != item.vehicleVesselTax)  tasks.push({updateOne: {filter: {id: ccs.id}, update: {consumption: item.vehicleVesselTax}}});
                }else {//不存在则插入
                    let id = await counterModel.getId('mix_ratio');
                    let newM = gljUtil.getBaseCCSMixRatio(unitFileID,item.vehicleVesselTax,connect_key);
                    newM.id = id;
                    tasks.push({insertOne: {document: newM}});
                }
                useMap[connect_key] = true;
            }
        }
        //找出旧的车船税文件有的，新的车船税文件没有的，则删除该记录
        for(let ckey in mxiMap){
            if(useMap[ckey]) continue;
            let deccs = _.find(mxiMap[ckey],{'code':'80CCS'});
            if(deccs){
                tasks.push( {deleteOne:{filter:{id: deccs.id}}});
            }
        }
        if(tasks.length > 0) await mixRatioModel.model.bulkWrite(tasks);
    }
}

//新增单价文件的同时，在项目工料机和空白的单价文件中先插入机械组成物等信息
async function addMixRatioForNew(projectID,unitFileId,engineerID,ext){
/*    1050001机械工	工日	机上人工/ 3003001	重油	kg	普通材料/ 3003002 汽油	93号	kg	普通材料
    3003003	柴油	0号，-10号，-20号	kg	普通材料/  3003004	丙烷	kg	普通材料/ 3005001	煤	t	普通材料
    3005002	电	kW·h   267 电 kW·h （浙江2005编号不同）	   普通材料/  3005004	水	m3	普通材料/ 3005005	液化天然气	m3	普通材料
     02JXF	折旧费	元	机械组成物/ 03WHF	检修费	元	机械组成物/    04ACFZF	维护费	元	机械组成物
  05QT	安拆辅助费	元	机械组成物/ 80CCS	车船税	元	机械组成物*/
    let mixCodes = ['1051001','3003001','3003002','3003003','3003004','3005001','3005002','3005004','3005005','02JXF','03WHF','04ACFZF','05QT','80CCS','267'];
    let libID = await ration_glj.getGLJLibByEngineerID(engineerID);
    let stdGljs = await std_glj_lib_gljList_model.find({'repositoryId':libID,'code':{'$in':mixCodes}});
    let projectGljModel = new GLJListModel();
    for (let glj of stdGljs){
        let tem = {projectID:projectID};
        ration_glj.setPropertyFromStd(tem,glj);
        await projectGljModel.addList(ration_glj.getGLJSearchInfo(tem),unitFileId,ext);
    }
}

async function updateUnitPrice(unitPrice) {//同时支持单个或多个更新
    if(Array.isArray(unitPrice)){
        let tasks = [];
        for(let u of unitPrice){
            if(u && !_.isEmpty(u.doc)) tasks.push({updateOne: {filter: {id: u.id,unit_price_file_id:u.unit_price_file_id}, update: u.doc}});
        }
        if(tasks.length > 0)  await unit_price_model.bulkWrite(tasks);
    }else {
        if(unitPrice && !_.isEmpty(unitPrice.doc)){
            await unit_price_model.findOneAndUpdate({id:unitPrice.id,unit_price_file_id:unitPrice.unit_price_file_id},unitPrice.doc);
        }
    }

}

async function updateUserFreight(data,req) {
    let datas = [];
    if(data.action == "add"){
        for(let f of data.freights){
            f.ID =  uuidV1();
            f.compilationID = req.session.sessionCompilation._id;
            f.userID = req.session.sessionUser.id;
            datas.push(f);
        }
        console.log(datas);
       return await user_freights_model.create(datas);
    }else if(data.action == "update"){//暂时做成只支持单个更新
        return await user_freights_model.update({"ID":data.ID},data.doc);
    }
}

async function getUserFreights(req) {
    return await user_freights_model.find({"userID":req.session.sessionUser.id,"compilationID": req.session.sessionCompilation._id}).lean();
}

//插入综合电价中的属性
async function insertElectrovalence(data,compilationID) {
    let result = {};
    let projectGljModel = new GLJListModel();
    let lib = await std_glj_lib_model.findOne({compilationId:compilationID}).lean();
    let stdGLJs = await std_glj_lib_gljList_model.find({'repositoryId':lib.ID,'code':data.code}).lean();
    for(let std of stdGLJs){
        let sIndex = projectGljModel.getIndex(std,['code','specs','unit','gljType']);//机械台班下拉列表名字里kw和数据库里名字kw大小写不一致，忽略名字做对应
        if(sIndex == projectGljModel.getIndex(data,['code','specs','unit','type'])){
            let tem = {projectID:data.projectID};
            ration_glj.setPropertyFromStd(tem,std);
            result.projetcGLJData =  await projectGljModel.addList(ration_glj.getGLJSearchInfo(tem));
        }
    }

    return result;
}

//更新或新建综合电价信息
async function updateElectrovalence(data) {
    let elec = data["electrovalence"];
    if(elec){
        let actionType = elec.actionType;
        if(actionType == "add"){
            await com_electrovalence_model.create(elec.doc);
        }else if(actionType == "update"){
            await com_electrovalence_model.updateOne({'ID':elec.ID},elec.doc);
        }
    }
    if(data["unitPrice"]) await updateUnitPrice(data["unitPrice"]);

}


async function updateMaterialCalcTasks(data) {
    let freightTasks = [];
    let priceTasks = [];
    for(let key in data){
        if(key == "freight"){
            let fu = data[key];
            genTasks(fu,freightTasks);
        }
        if(key =="price"){
            let pu = data[key];
            genTasks(pu,priceTasks);
        }
    }
    console.log(priceTasks)
    if(freightTasks.length > 0) await freight_calc_model.bulkWrite(freightTasks);
    if(priceTasks.length > 0) await original_calc_model.bulkWrite(priceTasks);
    if(data["unitPrice"]) await updateUnitPrice(data["unitPrice"]);


    function genTasks(obj,tasks) {
        for(let key in obj){
            if(key == "update"){
                let u = obj[key];
                for(let ID in u ){
                    tasks.push({updateOne: {filter: {ID: ID}, update: u[ID]}})
                }
            }
            if(key == "add"){
                let a = obj[key];
                for(let d of a){
                   // d.ID = uuidV1(); 改成在前端自动生成
                    tasks.push({insertOne: {document: d}});
                }
            }
            if(key == "delete"){
                let r = obj[key];
                for(let ID in r){
                    tasks.push({deleteOne: {filter:{ID: ID}}});
                }
            }
        }
    }

}


async function updateMaterialCalc(data) {
    if(data.tasks.length > 0) await unit_price_model.bulkWrite(data.tasks);
    return {}
}