/**
 *
 *
 * @author Tony Kang
 * @date 2021/10/15
 * @version
 */

function _chkIfEquals(orgStr, targetStr) {
    //㎡ ㎥ 立方
    let rst = false;
    if (typeof(orgStr) == 'string' && typeof(targetStr) == 'string') {
        let regExp1 = new RegExp('㎡', "gm");
        let regExp2 = new RegExp('（', "gm");
        let regExp3 = new RegExp('）', "gm");
        let orgS = orgStr.replace(regExp1, 'm2').replace(regExp2, '(').replace(regExp3, ')');
        let targetS = targetStr.replace(regExp1, 'm2').replace(regExp2, '(').replace(regExp3, ')');
        rst = (orgS === targetS);
    }
    return rst;
}

function chkAndSetBillsUnitPrice(billsNodes) {
    // 此方法在用户选择清单时调用(有指标基价/清单单价设置)
    if (billsUnitPriceFeature !== null) {
        for (const node of billsNodes) {
            if (node.updateType === 'create') {
                let unitFeeVal = _commonChkAndSetPrice(node.updateData, true);
                if (unitFeeVal !== 0) {
                    // 暂时未设小数位数 scMathUtil.roundTo(unitFeeVal,2);
                    unitFeeVal = unitFeeVal + 0.0000001; //前端四舍五入补偿用
                    node.updateData.calcFlag = 2; //当用户输入单价
                    if (!node.updateData.hasOwnProperty('fees')) {
                        node.updateData.fees = [];
                    }
                    node.updateData.fees.push({fieldName: 'common', unitFee: unitFeeVal, totalFee: 0, tenderUnitFee: unitFeeVal, tenderTotalFee: 0});
                }
            }
        }
    }
}

function chkAndResetBills(adHocSheet, adHocNodes) {
    //用户调整了工程特征后调用
    for (let key in projectObj.project.mainTree.nodes) {
        const node = projectObj.project.mainTree.nodes[key];
        let unitFeeVal = _commonChkAndSetPrice(node.data, true);
        if (unitFeeVal !== 0) {
            // 暂时未设小数位数 scMathUtil.roundTo(unitFeeVal,2);
            unitFeeVal = unitFeeVal + 0.0000001; //前端四舍五入补偿用
            if (!node.data.hasOwnProperty('fees')) {
                node.data.fees = [];
            }
            for (let idx = node.data.fees.length - 1; idx >= 0; idx--) {
                if (node.data.fees[idx].fieldName === 'common') {
                    node.data.fees[idx].unitFee = unitFeeVal;
                    node.data.fees[idx].tenderUnitFee = unitFeeVal;
                    node.data.feesIndex.common.unitFee = unitFeeVal;
                    node.data.feesIndex.common.tenderUnitFee = unitFeeVal;
                    break;
                }
            }
            if (adHocSheet) {
                let rCount = adHocSheet.getRowCount();
                for (let aNode of adHocNodes) {
                    unitFeeVal = _commonChkAndSetPrice(aNode.data, false);
                    if (unitFeeVal !== 0) {
                        for (let idx = 0; idx < rCount; idx++) {
                            let cell1 = adHocSheet.getCell(idx, 1);
                            let cell2 = adHocSheet.getCell(idx, 2);
                            let cell3 = adHocSheet.getCell(idx, 3);
                            if (_chkIfEquals(aNode.data.code, cell1.value()) && _chkIfEquals(aNode.data.name, cell2.value()) && _chkIfEquals(aNode.data.unit, cell3.value())) {
                                let cell4 = adHocSheet.getCell(idx, 4);
                                unitFeeVal = unitFeeVal + 0.0000001; //前端四舍五入补偿用
                                unitFeeVal = unitFeeVal.toFixed(2);
                                if (unitFeeVal === '0.00') unitFeeVal = '';
                                cell4.value(unitFeeVal);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    // 调整了后需要重新计算
    $.bootstrapLoading.start();
    projectObj.project.calcProgram.calcAllNodesAndSave(calcAllType.catAll, function () {
        projectObj.project.projectGLJ.loadData(function () {
            $.bootstrapLoading.end();
        });
    });
}

function chkAndAddEstUnitPrice(orgBills) {
    //只显示基本价格，无系数！
    if (billsUnitPriceFeature !== null) {
        for (const node of orgBills) {
            let unitFeeVal = _commonChkAndSetPrice(node, false);
            if (!isNaN(parseFloat(unitFeeVal))) {
                unitFeeVal = unitFeeVal.toFixed(2);
                if (unitFeeVal === '0.00') unitFeeVal = '';
            }
            node.baseEstUnitPrice = unitFeeVal;
        }
    }
}

function _commonChkAndSetPrice(curItem, isNeedFactor) {
    let rst = 0;
    let isMatch = true;
    // 1. 基本数量
    // 先判断此bills是否有配置
    let basicValue = 0;
    for (const bm of billsUnitPriceFeature.feature.basicMappings) {
        isMatch = true;
        if (bm.parentBasicKeys.length === billsUnitPriceFeature.feature.basicKeyOptions.length) {
            for (let kIdx = 0; kIdx < bm.parentBasicKeys.length; kIdx++) {
                if (bm.parentBasicKeys[kIdx] !== 'ALL' && !_chkIfEquals(curItem[billsUnitPriceFeature.feature.basicKeyOptions[kIdx].key], bm.parentBasicKeys[kIdx]) ) {
                    isMatch = false;
                    break;
                }
            }
        } else {
            isMatch = false;
            continue;
        }
        if (isMatch) {
            //再根据相关项目属性指定基数
            for (const bms of bm.subs) {
                if (_chkUnitPriceFeatureKeys(bms.keys, curItem)) {
                    basicValue = bms.basicValue;
                    break;
                }
            }
            break;
        }
    }
    let factors = [];
    if (!isMatch || !isNeedFactor) {
        rst = basicValue;
    } else {
        for (const fm of billsUnitPriceFeature.feature.factorMappings) {
            isMatch = true;
            if (fm.basicFactorKeys.length === billsUnitPriceFeature.feature.basicKeyOptions.length) {
                for (let kIdx = 0; kIdx < fm.basicFactorKeys.length; kIdx++) {
                    if (fm.basicFactorKeys[kIdx] !== 'ALL' && !_chkIfEquals(curItem[billsUnitPriceFeature.feature.basicKeyOptions[kIdx].key], fm.basicFactorKeys[kIdx])) {
                        isMatch = false;
                        break;
                    }
                }
            } else {
                isMatch = false;
                break;
            }
            if (isMatch) {
                for (const fms of fm.subs) {
                    if (_chkUnitPriceFeatureKeys(fms.keys, curItem)) {
                        factors.push(fms.basicValue);
                    }
                }
                // 允许多个,不break;
            }
        }
        //3. 装配(指标基价 即 默认的清单单价)
        let unitFeeVal = basicValue;
        for (const factor of factors) {
            unitFeeVal = unitFeeVal * parseFloat(factor);
        }
        rst = unitFeeVal;
    }
    return rst;
}

function _chkUnitPriceFeatureKeys(keys, curItem) {
    let rst = (keys.length > 0);
    for (const subKey of keys) {
        let isKeyMatch = false;
        if (subKey.type === 'prjFeature') {
            for (let prjF of projectObj.project.projectInfo.property.projectFeature) {
                if (prjF.key === subKey.key) {
                    if (prjF.value === subKey.value) {
                        isKeyMatch = true;
                        break;
                    } else {
                        //key相同而value不同，则说明不是这个设置值，无需再循环，直接退出
                        break;
                    }
                }
            }
        } else if (subKey.type === 'bills') {
            //判断当前清单curItem
            isKeyMatch = (curItem[subKey.key] === subKey.value);
        }
        if (!isKeyMatch) {
            //要所有的keys都匹配才行，否则false;
            rst = false;
            break;
        }
    }
    return rst;
}
