/**
 * Created by CSL on 2019/09/11.  浙江计算程序、基数 等覆盖。
 */

let isZJ2005 = true;
// 一般计税取不含税市场价、不含税定额价。简易计税取含税市场价、含税定额价。打开项目时，4个价格根据计税类型只载入其二，所以这里可不作区分。
function overwriteRationCalcBases(taxType) {
    if (typeof rationCalcBases == 'undefined') return;
    for (let key in rationCalcBases) delete rationCalcBases[key];
    // let isJY = taxType == '2';

    rationCalcBases['人工费'] = function (node, isTender) {
        return calcTools.rationBaseFee(node, [gljType.LABOUR], priceTypes.ptMarketPrice, isTender);
    };
    rationCalcBases['材料费'] = function (node, isTender) {
        return calcTools.rationBaseFee(node, baseMaterialTypes, priceTypes.ptMarketPrice, isTender);
    };
    rationCalcBases['施工机械使用费'] = function (node, isTender) {
        return calcTools.rationBaseFee(node, baseMachineTypes, priceTypes.ptMarketPrice, isTender);
    };
};

(function overwriteFeeTypes() {
    if (typeof cpFeeTypes == 'undefined') return;
    cpFeeTypes = [
        { type: 'directWork', name: '直接工程费' },
        { type: 'direct', name: '直接费' },
        { type: 'marketLabour', name: '人工费' },
        { type: 'marketMaterial', name: '材料费' },
        { type: 'marketMachine', name: '施工机械使用费' },
        { type: 'otherDirect', name: '其他直接费' },
        { type: 'local', name: '现场经费' },
        { type: 'indirect', name: '间接费' },
        { type: 'profit', name: '计划利润' },
        { type: 'tax', name: '税金' },
        { type: 'composite', name: '年度经费综合费' },
        { type: 'common', name: '养护工程费' }
    ];
})();

// 清单基数
const progression = ['养护工程管理费'];
const deficiency = {};
if (typeof baseFigureMap !== 'undefined') {
    const { fixedFlag } = commonConstants;
    const budgetMap = {
        // 除清单固定类别是“建筑安装工程费”的以外部分可显示
        '公路养护工程费': {
            base: 'GLYHGCF',
            fixedFlag: fixedFlag.CONSTRUCTION_INSTALL_FEE,
            filter: [fixedFlag.CONSTRUCTION_INSTALL_FEE],
            pick: false,
        },
        // 除清单固定类别是“建筑安装工程费”、“设备购置费”的以外部分可显示
        '设备购置费用': {
            base: 'SBGZFY',
            fixedFlag: fixedFlag.EQUIPMENT_ACQUISITION_FEE,
            filter: [fixedFlag.CONSTRUCTION_INSTALL_FEE, fixedFlag.EQUIPMENT_ACQUISITION_FEE],
            pick: false,
        },
        // 除清单固定类别是“建筑安装工程费”、“设备购置费”、“养护工程其他费用”的以外部分可显示
        '公路养护工程其他费用': {
            base: 'GLYHGCQTFY',
            fixedFlag: fixedFlag.MAINTENANCE_EXPENSES,
            filter: [fixedFlag.CONSTRUCTION_INSTALL_FEE, fixedFlag.EQUIPMENT_ACQUISITION_FEE, fixedFlag.MAINTENANCE_EXPENSES],
            pick: false,
        },
        // 只有清单固定类别是“养护工程其他费用”部分可显示
        '养护工程管理经费': {
            progressiveName: '养护工程管理费', // 累进库里配置的名称与基数名称应该是一样的，但是这里不一样且已经在yun上线。特殊处理
            isProgressive: true,
            base: 'YHGCGLJF',
            fixedFlag: null,
            filter: [fixedFlag.MAINTENANCE_EXPENSES],
            pick: true,
        },
        // 除清单固定类别是“建筑安装工程费”、“设备购置费”、“养护工程其他费用”、“一二三部分合计”的以外部分可显示
        '一二三部分合计': {
            base: 'YESBFHJ',
            fixedFlag: fixedFlag.ONE_TO_THREE_TOTAL,
            filter: [fixedFlag.CONSTRUCTION_INSTALL_FEE, fixedFlag.EQUIPMENT_ACQUISITION_FEE, fixedFlag.MAINTENANCE_EXPENSES, fixedFlag.ONE_TO_THREE_TOTAL],
            pick: false,
        },
        // 只有清单固定类别是“预备费”部分可显示
        '工程造价增涨预留费': {
            base: 'GCZJZZYLF',
            fixedFlag: null,
            filter: [fixedFlag.BUDGET_FEE],
            pick: true,
    
        }
    };
    const boqMap = {
        //仅允许用于固定类别是“第100章至700章清单”以外的清单
        '各章清单合计': {
            base: 'GZQDHJ',
            fixedFlag: fixedFlag.ONE_SEVEN_BILLS,
            filter: [fixedFlag.ONE_SEVEN_BILLS],
            pick: false
        },
        //仅允许用于固定类别是“第100章至700章清单”以外的清单
        '专项暂定合计': {
            base: 'ZXZDHJ',
            fixedFlag: null,
            filter: [fixedFlag.ONE_SEVEN_BILLS],
            pick: false
        },
        /*
        *  清单固定行[第100章至700章清单]下的[第100章清单]需要允许清单可使用基数{100章以外合计}
        *  因此{100章以外合计}不设置关联的清单固定行
        * */
        //仅允许用于固定类别为“100章清单”引用
        '100章以外清单合计': {
            base: 'YBZYHQDHJ',
            fixedFlag: null,
            filter: [fixedFlag.ONE_HUNDRED_BILLS],
            pick: true
        }
    };
    baseFigureMap.budget = budgetMap;
    baseFigureMap.boq = boqMap;
}

if (typeof baseFigureTemplate !== 'undefined') {
    const { fixedFlag } = commonConstants;
    baseFigureTemplate.budget = {
        // 公路养护工程费：取清单固定类别是“建筑安装工程费”的金额
        GLYHGCF(tender) {
            const feeField = 'common';
            const subFeeField = tender ? 'tenderTotalFee' : 'totalFee';
            return cbTools.getBillsFee(calcBase.fixedFlag.CONSTRUCTION_INSTALL_FEE, feeField, subFeeField);
        },
        // 设备购置费用：取清单固定类别是“设备购置费”的金额
        SBGZFY(tender) {
            const feeField = 'common';
            const subFeeField = tender ? 'tenderTotalFee' : 'totalFee';
            return cbTools.getBillsFee(calcBase.fixedFlag.EQUIPMENT_ACQUISITION_FEE, feeField, subFeeField);
        },
        // 公路养护工程其他费用：取清单固定类别是“养护工程其他费用”的金额。
        GLYHGCQTFY(tender) {
            const feeField = 'common';
            const subFeeField = tender ? 'tenderTotalFee' : 'totalFee';
            return cbTools.getBillsFee(calcBase.fixedFlag.MAINTENANCE_EXPENSES, feeField, subFeeField);
        },
        // 养护工程管理经费：取清单固定类别是“建筑安装工程费”金额为基数，采用累进办法计算
        YHGCGLJF(tender) {
            const baseFee = this['GLYHGCF'](tender);
            if (!tender) {
                calcBase.baseProgressiveFee = baseFee;
            }
            return calculateUtil.getProgressiveFee(baseFee, '养护工程管理费', projectObj.project.property.progressiveInterval, decimalObj.bills.totalPrice, deficiency);
        },
        // 一二三部分合计：取清单固定类别是“一二三部分合计”的金额
        YESBFHJ(tender) {
            const feeField = 'common';
            const subFeeField = tender ? 'tenderTotalFee' : 'totalFee';
            return cbTools.getBillsFee(calcBase.fixedFlag.ONE_TO_THREE_TOTAL, feeField, subFeeField);
        },
        // 工程造价增涨预留费：以{公路养护工程费}为基数，= P * [(1+i)^(n-1) -1]
        // P:公路养护工程费总额（元）
        // i:年造价增长率（%）(项目属性已有字段)
        // N：增涨计费年限(项目属性已有字段)
        GCZJZZYLF(tender) {
            const baseFee = this['GLYHGCF'](tender);
            //年造价增涨
            const costGrowthRate = calcBase.project.property.costGrowthRate
                ? calcBase.project.property.costGrowthRate
                : 0;
            //增涨计费年限
            const growthPeriod = projectObj.project.property.growthPeriod
                ? calcBase.project.property.growthPeriod
                : 0;
            return (baseFee * (Math.pow(1 + costGrowthRate, growthPeriod - 1) - 1)).toDecimal(decimalObj.bills.totalPrice);
        }
    };

    baseFigureTemplate.boq = {
        //{各章清单合计}
        // 取清单固定类别是“第100章至700章清单”的金额
        'GZQDHJ': function (tender) {
            let feeField = 'common',
                subFeeField = tender ? 'tenderTotalFee' : 'totalFee';
            return cbTools.getBillsFee(calcBase.fixedFlag.ONE_SEVEN_BILLS, feeField, subFeeField);
        },
        //{专项暂定合计}
        // 汇总专项暂定列有值的清单的金额
        'ZXZDHJ': function (tender) {
            let rst = 0,
                feeField = 'common',
                subFeeField = tender ? 'tenderTotalFee' : 'totalFee';
            let billsData = calcBase.project.Bills.datas,
                filterData = billsData.filter(function (data) {
                    return data.specialProvisional;
                });
            for (let data of filterData) {
                if (cbTools.isUnDef(data.feesIndex) || _.isEmpty(data.feesIndex) ||
                    cbTools.isUnDef(data.feesIndex[feeField]) || cbTools.isUnDef(data.feesIndex[feeField][subFeeField])) {
                    continue;
                }
                rst += data.feesIndex[feeField][subFeeField];
            }
            return rst.toDecimal(decimalObj.bills.totalPrice);
        },
        //{100章以外清单合计}
        // 取清单固定清单[第100章至700章清单]的金额，但扣除清单100章下的金额。
        // 如果是固定清单[第100章至700章清单]下100章以外清单引用此基数，要排除自身(目前只允许100章的清单使用，所以暂时不需要此判断)
        'YBZYHQDHJ': function (tender) {
            let oneToSeven = cbTools.findNodeByFlag(fixedFlag.ONE_SEVEN_BILLS);
            if (!oneToSeven) {
                return 0;
            }
            //100-700章固定节点的所有子节点
            let allChildren = [];
            function getChildren(nodes) {
                allChildren = allChildren.concat(nodes);
                for (let node of nodes) {
                    if (node.children.length > 0) {
                        getChildren(node.children);
                    }
                }
            }
            getChildren(oneToSeven.children);
            //扣除的节点：100章的节点[100-200)
            let deductNodes = allChildren.filter(cbTools.withingOneHundred);
            //计算金额
            let fullFeeField = tender ? 'common.tenderTotalFee' : 'common.totalFee';
            return projectObj.project.calcProgram.getTotalFee([oneToSeven], deductNodes, fullFeeField).toDecimal(decimalObj.bills.totalPrice);
        }
    };
}

if (typeof gljOprObj !== 'undefined') {
    // 添加、替换工料机界面工料机排序
    gljOprObj.sortSelectViewGLJ = function (data) {
        // 工料机编码：按“-”前的数值排序
        const reg = /[^-]+/;
        data.sort((a, b) => {
            const orgCodeA = a.code;
            const orgCodeB = b.code;
            const regCodeA = orgCodeA.match(reg);
            const regCodeB = orgCodeB.match(reg);
            const compareCodeA = regCodeA
                ? +regCodeA[0]
                    ? +regCodeA[0]
                    : regCodeA[0]
                : orgCodeA;
            const compareCodeB = regCodeB
                ? +regCodeB[0]
                    ? +regCodeB[0]
                    : regCodeB
                : orgCodeB;
            return isNaN(compareCodeA) && isNaN(compareCodeB)
                ? compareCodeA.localeCompare(compareCodeB)
                : compareCodeA - compareCodeB;
        });
        // 工料机类型排序：人工、机上人工、混凝土、砂浆、配合比、普通材料、商品混凝土、商品砂浆、外购砼构件、绿化苗木、机械台班、机械组成物、设备。
        const TypeMap = {
            1: 1,
            303: 2,
            202: 3,
            203: 4,
            204: 5,
            201: 6,
            205: 7,
            206: 8,
            208: 9,
            209: 10,
            301: 11,
            302: 12,
            5: 13,
        };
        data.sort((a, b) => {
            const typeA = TypeMap[a.gljType];
            const typeB = TypeMap[b.gljType];
            return typeA - typeB;
        });
    }

}

if (typeof gljUtil !== 'undefined') {
    gljUtil.getCodeSortMath = getCodeSortMath;
    gljUtil.getElecCoe = function () {
        return 0.24;
    }
    gljUtil.getElecCode = function () {
        return "267";
    }
}


if (typeof electrovalenceObj !== 'undefined') {
    electrovalenceObj.options = [
        { code: "270", name: "电网电", specs: "", unit: "kW·h", type: "201" },
        { code: "905", name: "5kW以内柴油发电机组", specs: "", unit: "台班", type: "301" },
        { code: "906", name: "15kW以内柴油发电机组", specs: "", unit: "台班", type: "301" },
        { code: "907", name: "30kW以内柴油发电机组", specs: "", unit: "台班", type: "301" },
        { code: "908", name: "50kW以内柴油发电机组", specs: "", unit: "台班", type: "301" },
        { code: "909", name: "75kW以内柴油发电机组", specs: "", unit: "台班", type: "301" },
        { code: "910", name: "100kW以内柴油发电机组", specs: "", unit: "台班", type: "301" },
        { code: "911", name: "120kW以内柴油发电机组", specs: "", unit: "台班", type: "301" },
        { code: "912", name: "160kW以内柴油发电机组", specs: "", unit: "台班", type: "301" },
        { code: "913", name: "200kW以内柴油发电机组", specs: "", unit: "台班", type: "301" },
        { code: "914", name: "250kW以内柴油发电机组", specs: "", unit: "台班", type: "301" },
        { code: "915", name: "320kW以内柴油发电机组", specs: "", unit: "台班", type: "301" }
    ]
}

if (typeof materialCalcObj !== 'undefined') {
    materialCalcObj.getAssistProductionLabel = function () {
        return "辅助生产现场经费费率(%)";
    }
    gljUtil.getAssUsedPrice = function(g){
      return g.marketPrice;
    }
}

if (typeof projectObj !== 'undefined') {
    projectObj.isInsertEquipmentVisable = function (selected) {
        return false;   //浙江不管是预算或者工程量清单，都是隐藏   
    }
}



if (typeof module !== 'undefined') {
    let _ = require('lodash');

    module.exports = {
        sortRationGLJ: function (list) {
            list = _.sortByAll(list, [function (item) {
                return getMainType(item.gljType ? item.gljType : item.type);
            }, getCodeSortMath()]);
            return list;

            function getMainType(type) {
                let str = type + "";
                return parseInt(str.substr(0, 1));
            }
        },
        getDefalutAssistProductionFeeRate: function () {
            return 15
        }
    };
}

function getCodeSortMath() {
    return function (item) {
        let arr = item.code.split('-');
        return parseInt(arr[0])
    }
}

if (typeof module !== 'undefined') {
    module.exports = {
        progression,
        deficiency
    };
}