/**
 * 单价业务模型
 *
 * @author CaiAoLin
 * @date 2017/6/30
 * @version
 */
import mongoose from "mongoose";
import BaseModel from "../../common/base/base_model"
import GLJTypeConst from "../../common/const/glj_type_const"
import CounterModel from "./counter_model"
import MixRatioModel from "./mix_ratio_model";
import _ from "lodash";
const scMathUtil = require('../../../public/scMathUtil').getUtil();
let collectionName = 'unit_price';
let decimal_facade = require('../../main/facade/decimal_facade');
let gljListModel = mongoose.model("glj_list");
let original_calc_model = mongoose.model('original_calc');
let freight_calc_model = mongoose.model('freight_calc');
let gljUtil = require('../../../public/gljUtil');
const uuidV1 = require('uuid/v1');


class UnitPriceModel extends BaseModel {

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = mongoose.model(collectionName);
        parent.init();
    }

    /**
     * 根据单价文件id获取单价数据
     *
     * @param {Number} fileId
     * @return {Promise}
     */
    async getDataByFileId(fileId) {
        fileId = parseInt(fileId);
        if (isNaN(fileId) || fileId <= 0) {
            return null;
        }

        let unitPriceList = await this.db.model.find({unit_price_file_id: fileId});
        if (unitPriceList.length <= 0) {
            return null;
        }

        // 整理数据
        let result = {};
        for(let tmp of unitPriceList) {
            let index = this.getIndex(tmp,['code','name','specs','unit','type'])
            result[index] = tmp;
        }

        return result;
    }
    /**
     * 设置场景
     *
     * @param {string} scene
     * @return {void}
     */
    setScene(scene = '') {
        switch (scene) {
            // 新增数据的验证规则
            case 'add':
                this.model.schema.path('base_price').required(true);
                this.model.schema.path('market_price').required(true);
                this.model.schema.path('name').required(true);
                this.model.schema.path('code').required(true);
                // this.model.schema.path('unit').required(true);
                this.model.schema.path('type').required(true);
                this.model.schema.path('unit_price_file_id').required(true);
        }
    }

    /**
     * 新增单价数据
     *
     * @param {Object} data
     * @param {Number} unitPriceFileId
     * @param {Number} gljCount
     * @return {Promise} 返回数据以及是否新增
     */
    async addUnitPrice(data, unitPriceFileId,operation='add', gljCount = 0) {
        if (data.original_code===undefined||data.code === undefined || data.project_id === undefined || data.name === undefined
            || data.market_price === undefined) {
            return [null, false];
        }
        // 先查找是否有原始code相同的记录
        let unitPriceData = await this.db.model.find({original_code: data.original_code, unit_price_file_id: unitPriceFileId}).sort('code').exec();
        // 如果有记录，判断是否存在一样的名称，单位...等，有则直接返回数据
        let unitPrice=null;
        if(operation=='add'){//新增操作时，要把code也一起判断，是否完全一样。(新增的时候有可能存在编码一样，但是名称规格等不一样的情况，这种情况的话编码不用改变)
            unitPrice =  this.isPropertyInclude(unitPriceData,['code','name','specs','unit','type'],data);
        }else {//修改操作时，code不用加入判断，因为code是需要改变的
            unitPrice =  this.isPropertyInclude(unitPriceData,['name','specs','unit','type'],data);
        }
        if(unitPrice){
            return [unitPrice, false];
        }

        // 如果不存在基价单价，则在数据源中获取
        if (data.base_price === undefined) {
            let firstUnitPrice = unitPriceData[0] !== undefined ? unitPriceData[0] : [];
            data.base_price = firstUnitPrice.base_price !== undefined ? firstUnitPrice.base_price : 0;
            data.type = firstUnitPrice.type !== undefined ? firstUnitPrice.type : 0;
        }

        let insertData = {
            code: data.code,
            base_price: data.base_price,
            market_price: data.market_price,
            unit_price_file_id: unitPriceFileId,
            name: data.name,
            specs:data.specs?data.specs:'',
            original_code:data.original_code,
            unit:data.unit?data.unit:'',
            type: data.type,
            short_name: data.shortName !== undefined ? data.shortName : '',
            glj_id: data.glj_id,
            is_add:0,
            grossWeightCoe:data.grossWeightCoe,
            purchaseStorageRate:data.purchaseStorageRate,
            offSiteTransportLossRate:data.offSiteTransportLossRate,
            handlingLossRate:data.handlingLossRate
        };
        if(data.from=='cpt') insertData.is_add=1;//如果是来自补充工料机，则都添加新增标记

        if(operation=='add' && insertData.code != insertData.original_code) insertData.is_add=1;//添加的时候如果是复制整块来的，可能在源项目中是新增的工料机，这里也要添上

        if (unitPriceData&&unitPriceData.length>0&&operation!='add') {// 如果原始编码能找到，但不存在一样的编号，名称，单位.型号等，更改code和添加新增标记，新增的时候除外。新增的情况下能到这一步说明有存在编码一致但其它属性不一致的情况，所以不用更改编码
            //insertData.code = data.original_code+"-"+unitPriceData.length;
            insertData.code = data.original_code+"-"+this.getLastNumber(data.original_code,unitPriceData);
            insertData.is_add=1;
        }
        let addPriceResult = await this.add(insertData);
        return [addPriceResult, true];
    }
     getLastNumber(original_code,unitPriceData){
        let codeArray = _.map(unitPriceData,'code');
        let last = 1;
        while (true){
            if(_.includes(codeArray,original_code+"-"+last)){
                last +=1
            }else {
                break;
            }
        }
        return last;
     }
    /**
     * 新增记录
     *
     * @param {object} data
     * @return {Promise}
     */
    async add(data) {
        let counterModel = new CounterModel();
        if (data instanceof Array) {
            // 如果是批量新增
           await this.setIDfromCounter(collectionName,data);
            /* for(let tmp in data) {
                data[tmp].id = await counterModel.getId(collectionName);
            } */
        } else {
            data.id = await counterModel.getId(collectionName);
        }

        this.setScene('add');
        return await this.db.model.create(data);
    }

    /**
     * 判断数据中是否包含某个市场价格的记录
     *
     * @param {Array} data
     * @param {Number} price
     * @return {Number}
     */
    isPriceIncluded(data, price) {
        let index = -1;
        if (data.length <= 0) {
            return index;
        }
        for(let tmp in data) {
            if (data[tmp].market_price === price) {
                index = tmp;
                break;
            }
        }
        return index;
    }

    isPropertyInclude(data,pops,obj){
        let condition={},me = this;
        if (data.length <= 0) {
            return null;
        }
        if(pops instanceof  Array){
            return _.find(data,function (d) {
                return me.getIndex(d,pops) == me.getIndex(obj,pops)
            });
        }else {
            condition[pops]=obj[pops];
            return _.find(data,condition);
        }
    }
    /**
     * 更新市场单价
     *
     * @param {Object} condition
     * @param {Object} updateData
     * @param {String} extend
     * @return {Promise}
     */
    async updatePrice(condition, updateData, extend = '') {
        if (Object.keys(condition).length <= 0 || Object.keys(updateData).length <= 0) {
            return false;
        }
        // 首先查找相应的数据判断工料机类型
        let unitPriceData = await this.findDataByCondition(condition);
        if (!unitPriceData) {
            throw '找不到对应的单价数据';
        }

       /* // 基价单价的计算-----先不考虑同步
        switch (unitPriceData.type) {
            // 主材、设备自动赋值基价单价=市场单价
            case GLJTypeConst.MAIN_MATERIAL:
            case GLJTypeConst.EQUIPMENT:
                updateData.base_price = updateData.market_price;
                break;
        }*/

        // 额外更新数据
        if (extend !== '') {
            extend = JSON.parse(extend);
            let indexList = ['code','name','specs','unit','type'];
            for (let conKey in extend) {
                let extendUpdateData = {
                    market_price: extend[conKey].market_price,
                };
                let tmpCondition = {
                    unit_price_file_id: unitPriceData.unit_price_file_id,
                };
                let keyList = conKey.split("|-|");
                for(let i = 1;i<keyList.length;i++){
                    if(keyList[i]!='null'){
                        tmpCondition[indexList[i]]=keyList[i];
                    }
                }
                let extendResult = await this.db.update(tmpCondition, extendUpdateData);
                if (!extendResult) {
                    throw '更新额外数据，编码为' + code + '的数据失败!';
                }
            }
        }

        let result = await this.db.update(condition, updateData);
        return result.ok !== undefined && result.ok === 1;
    }

    async updateUnitPrice(data){
        //查找并更新单价
        let doc={},newValueMap={};
        doc[data.field]=data.newval;
        newValueMap[data.id]=doc;
        let unitPrice = await this.db.findAndModify({id:data.id,unit_price_file_id:data.unit_price_file_id},doc);
        if(!unitPrice){
            throw "没有找到对应的单价";
        }
        let rList=await this.checkAndUpdateParent(unitPrice,data.field,data.project_id,newValueMap);
        if(data.ext){
            let elecPrice = await this.db.findAndModify({id:data.ext.id,unit_price_file_id:data.ext.unit_price_file_id},data.ext.doc);
            let nm = {};
            nm[data.ext.id] = data.ext.doc;
            let erList=await this.checkAndUpdateParent(elecPrice,"market_price",data.project_id,nm);
            rList = rList.concat(erList);
        }
        return rList;
    }

    async updateCalcMaterial(data){
        let doc = data.ext?data.ext:{};
        doc[data.updateField] = data.value;
        let unitPrice = await this.db.findAndModify({id:data.id,unit_price_file_id:data.unit_price_file_id},doc);
        if(data.updateField == 'calcMaterial' && doc['calcMaterial'] == 0){//标记为0即删除材料计算标记，要删除其下挂的原价计算，运费计算，定额计算
            let connect_key = gljUtil.getIndex(unitPrice);
            await original_calc_model.deleteMany({unit_price_file_id:data.unit_price_file_id,connect_key:connect_key});
            await freight_calc_model.deleteMany({unit_price_file_id:data.unit_price_file_id,connect_key:connect_key});
            //to do 删除定额计算
        }
        if(!unitPrice){
            throw "没有找到对应的单价";
        }
        return unitPrice;
    }
    needUpdateParent(connect_key){
        let noNeedUpdateType = ["202","203","204"];//父类型为混凝土、砂浆，配合比，类型的，不用更新价格
        let keyList = connect_key.split("|-|");
        return noNeedUpdateType.indexOf(keyList[4]) == -1
    }
    async checkAndUpdateParent(unitPrice,field,project_id,newValueMap,batchUpdate=false){//检查是否属于某个工料机的组成物，如果是，并且不是批量更新的情况下，直接更新，如果是批量更新，返回更新任务
        //查找是否是属于某个项目工料机的组成物
        let mixRatioModel = new MixRatioModel();
        let condition = {unit_price_file_id:unitPrice.unit_price_file_id, code:unitPrice.code,name: unitPrice.name, specs: unitPrice.specs,unit:unitPrice.unit,type:unitPrice.type};
        let mixRatioList = await mixRatioModel.findDataByCondition(condition, null, false);
        let connectKeyMap={};
        //找到则计算项目工料机组成物的价格并更新
        let rList= [];
        if(mixRatioList&&mixRatioList.length>0){
            for(let m of mixRatioList){
                // 父类型不为混凝土、砂浆，配合比，类型的，才要更新价格
                if(this.needUpdateParent(m.connect_key) && !connectKeyMap.hasOwnProperty(m.connect_key)){//为了去重复，组成物会与其它项目同步，所以有可能重复。
                    rList.push(await this.updateParentUnitPrice(m,field,project_id,newValueMap,batchUpdate));
                    connectKeyMap[m.connect_key]=true;
                }
            }
        }
        return rList;
    }
    async batchUpdatePrices(data){//批量更新
        let tasks = [];
        let parentTask = [];
        let newValueMap = {};
        let needCheckDatas= [];
        for(let d of data){//第一次循环生成更新提交的记录，并生成一个新值的映射表，为更新父节点使用
            let condition = {id:d.unit_price.id,unit_price_file_id:d.unit_price.unit_price_file_id};
            let doc = d.ext?d.ext:{};
            if(d.field){//共用接口后有可能只更新其它属性，不更新价格
              doc[d.field]=d.newval;
              newValueMap[d.unit_price.id] = doc;
              needCheckDatas.push(d);
            }
            tasks.push(this.generateUpdateTask(condition,doc));
        }
        for(let d of needCheckDatas){//第二次更新父节点
           let rList = await this.checkAndUpdateParent(d.unit_price,d.field,d.project_id,newValueMap,true);
           parentTask = parentTask.concat(rList);
        }
        tasks = tasks.concat(parentTask);
        tasks.length>0?this.model.bulkWrite(tasks):'';
        return parentTask;
    }

    async updateParentUnitPrice(mixRatio,fieid,project_id,newValueMap,batchUpdate){//batchUpdate 批量更新标记，如果true,只生成task
        let  decimalObject =project_id?await decimal_facade.getProjectDecimal(project_id):null;
        let quantity_decimal = (decimalObject&&decimalObject.glj&&decimalObject.glj.quantity)?decimalObject.glj.quantity:3;
        let price_decimal = (decimalObject&&decimalObject.glj&&decimalObject.glj.unitPrice)?decimalObject.glj.unitPrice:2;
        //查找该工料机所有组成物
        let indexList = ['code','name','specs','unit','type'];
        let mixRatioModel = new MixRatioModel();
        let mixRatioMap = await mixRatioModel.findDataByCondition({unit_price_file_id:mixRatio.unit_price_file_id,connect_key:mixRatio.connect_key}, null, false,indexList);
        //查找对应的价格
        let codeList = [];
        let nameList = [];
        let specsList= [];
        let typeList = [];
        let unitList = [];
        for(let mk in mixRatioMap){
            codeList.push(mixRatioMap[mk].code);
            nameList.push(mixRatioMap[mk].name);
            specsList.push(mixRatioMap[mk].specs);
            typeList.push(mixRatioMap[mk].type);
            unitList.push(mixRatioMap[mk].unit);
        }
        let condition = {unit_price_file_id: mixRatio.unit_price_file_id,code: {"$in": codeList}, name: {"$in": nameList},specs:{"$in": specsList},type:{"$in": typeList},unit:{"$in": unitList}};
        let priceMap = await this.findDataByCondition(condition, {_id: 0}, false, indexList);
        let sumPrice=0;
        for(let pk in priceMap){
            let price = scMathUtil.roundForObj(priceMap[pk][fieid],price_decimal);
            let consumption = scMathUtil.roundForObj(mixRatioMap[pk].consumption,quantity_decimal);
            if(newValueMap[priceMap[pk].id]){//是需要更新的记录，取当前新的值
                price = scMathUtil.roundForObj(newValueMap[priceMap[pk].id][fieid],price_decimal);
            }
            sumPrice +=scMathUtil.roundForObj(price*consumption,price_decimal);
        }
        sumPrice= scMathUtil.roundForObj(sumPrice,price_decimal);
        if(sumPrice<=0){
            return null;
        }
        //更新父价格
        let keyList = mixRatio.connect_key.split("|-|");
        let pcondition = {
            unit_price_file_id:mixRatio.unit_price_file_id,
            code:keyList[0]
        };
        for(let i = 1;i<keyList.length;i++){
            if(keyList[i]!='null'){
                pcondition[indexList[i]]=keyList[i];
            }
        }
        let doc={};
        doc[fieid]=sumPrice;
        if(batchUpdate == true){
            return this.generateUpdateTask(pcondition,doc);
        }else {
            let uprice =  await this.db.findAndModify(pcondition,doc,{new: true});
            //uprice[fieid]=sumPrice;
            return uprice;
        }
    }

    generateUpdateTask(condition,doc) {
        let task = {
            updateOne:{
                filter:condition,
                update:doc
            }
        };
        return task
}

    /**
     * 复制单价文件数据
     *
     * @param {Number} currentUnitPriceId
     * @param {Number} changeUnitPriceId
     * @return {Promise}
     */
    async copyNotExist(currentUnitPriceId, changeUnitPriceId,projectId) {
        let result = false;
        // 首先查找原单价文件id下的数据
        let currentUnitList = await this.model.find({unit_price_file_id: currentUnitPriceId}).lean();
        if (currentUnitList === null) {
            return result;
        }

        let gljList = await gljListModel.find({'project_id':projectId}).lean();
        let gljMap = {};//用来记录glj的映射表，本项目有使用的工料机才需要copy过去
        for(let g of gljList){
            let g_index = this.getIndex(g,['code','name','specs','unit','type']);
            gljMap[g_index] = g;
        }

        let codeList = [];
        let nameList =[];
        for (let tmp of currentUnitList) {
            if (codeList.indexOf(tmp.code) >= 0) {
                continue;
            }
            codeList.push(tmp.code);
            if(nameList.indexOf(tmp.name)>=0){
                continue
            }
            nameList.push(tmp.name);
        }

        // 查找即将更替的单价文件是否存在对应的工料机数据 -- （这里只根据code和名称初步过滤，因为其它的几项更改的概率不大，在下一步的比较中再精确匹配）
        let condition = {unit_price_file_id: changeUnitPriceId, code: {"$in": codeList},name:{"$in": nameList}};
        let targetUnitList = await this.findDataByCondition(condition, null, false, ['code','name','specs','unit','type']);

        // 如果没有重叠的数据则原有的数据都复制一份
        let insertData = [];
        for (let tmp of currentUnitList) {
            let t_index = this.getIndex(tmp,['code','name','specs','unit','type']);
            if (targetUnitList !== null && targetUnitList[t_index] !== undefined) {
                continue;
            }
            if(gljMap[t_index]){//如果本项目有用到才复制
                delete tmp._id;  // 删除原有id信息
                delete tmp.id;
                tmp.unit_price_file_id = changeUnitPriceId;
                insertData.push(tmp);
            }
        }
        let uResult = insertData.length > 0 ? await this.add(insertData) : true;
        let mixRatioModel = new MixRatioModel();
        let mResult = await mixRatioModel.copyNotExist(currentUnitPriceId, changeUnitPriceId,gljMap);//复制组成物
        let cResult = await this.copyMaterialNotExist(currentUnitPriceId, changeUnitPriceId,gljMap);

        return uResult&&mResult&&cResult;

    }
    async copyMaterialNotExist(currentUnitPriceId, changeUnitPriceId,gljMap,newFile = false){
        await  this.copyCalcNotExist(currentUnitPriceId, changeUnitPriceId,gljMap,original_calc_model,newFile);//复制原价计算
        await  this.copyCalcNotExist(currentUnitPriceId, changeUnitPriceId,gljMap,freight_calc_model,newFile);//复制运费计算
        return true;
    }

    async  copyCalcNotExist(currentUnitPriceId, changeUnitPriceId,gljMap,model,newFile){
        let currentMap = {},targetMap = {}, insertData = [];
        //取原单价文件所有的原价、运费计算计录
        let currentList = await model.find({'unit_price_file_id':currentUnitPriceId}).lean();
        currentMap = _.groupBy(currentList,"connect_key");

        //切换后的单价文件所有的的组成物
        let targetList = await model.find({'unit_price_file_id':changeUnitPriceId});
        targetMap =  _.groupBy(targetList,"connect_key");
        for(let ckey in currentMap){
            if(targetMap[ckey]){//如果切换后已经存在，则不用复制
                continue;
            }
            if(gljMap[ckey] || newFile == true){//在本项目中有用到 或者 新建的文件
                for(let c of  currentMap[ckey]){
                    delete c._id;  // 删除原有id信息
                    c.ID = uuidV1();
                    c.unit_price_file_id = changeUnitPriceId;
                    //更改下挂的定额工料机与项目工料机的关联关系
                    if(c.ration_gljs){
                      for(let rg of c.ration_gljs){
                        rg.ID = uuidV1();
                      }
                    }

                    if(c.rations){
                      for(let r of c.rations){
                        r.ID = uuidV1(); 
                      }
                    }

                    insertData.push(c);
                }
            }
        }
        if(insertData.length > 0)  await model.create(insertData);
    }


}

export default UnitPriceModel;