/**
 * 一个资金计划的字段
 */
BUDGET_PLAN_DETAIL_ARR=["month","deviceCost","engineerCost","projectManageCost","earnestMoneyCost","totalCost","saleIncome","earnestMoneyIncome","totalIncome","fundBalance","capitalInterest","underwrittenPlan","repaymentPlan"];
BUDGET_PLAN_DETAIL={
    "month":[true,"月份"],
    "deviceCost":[true,"设备支出","number"],
    "engineerCost":[true,"工程支出","number"],
    "projectManageCost":[true,"经营性开支","number"],
    "earnestMoneyCost":[true,"保证金支出","number"],
    "totalCost":[true,"支出合计","number"],
    "saleIncome":[true,"销售收款","number"],
    "earnestMoneyIncome":[true,"保证金收款","number"],
    "totalIncome":[true,"收款合计","number"],
    "fundBalance":[true,"资金余额","number"],
    "capitalInterest":[true,"资金利息","number"],
    "underwrittenPlan":[true,"垫资计划","number"],
    "repaymentPlan":[true,"还款计划","number"]
};


/*$(function () {
    $(".budget-plan-detail").click(function () {
        $('#my-prompt-budget-plan-detail').modal({
            relatedTarget: this,
            closeOnConfirm:false,
            onConfirm: function(e) {

                //校验数据正确性
                var message = verifyBudgetPlan();
                if (message) {
                    layuiAlert(message);
                    return;
                }


                //不能使用e.data，因为无法获取动态添加的
                var data = collectData("am-modal-prompt-input-budget-plan-detail");
                //data = prepareAjaxData(data, BUDGET_PLAN_DETAIL_ARR, $("#id").val(),false);
                data = prepareAjaxDataVerify(data, BUDGET_PLAN_DETAIL, $("#id").val());
                if(data){
                    postAjax(base+"/project/budgetEditSaveBudgetPlanDetail", data, updateBudgetPlanDetailData);
                }
            },
            onCancel: function(e) {
            }
        });
    });
    $("#budgetPlanDetailAddBtn").click(function () {
        appendTrBudgetPlan();
    });

    //绑定资金计划明细输入框
    bindChangeableInputBudgetPlanDetail();
    //绑定资金计划的删除按钮
    bindBudgetPlanDeleteBtn();
    //绑定公司管理费用的输入框
    bindCompanyManageChangeable();
    //渲染日期选择框
    renderMonthDatePicker();
    //绑定数字输入框保留两位小数
    bindNumberInput();
});*/


$(function () {
    $(".budget-plan-detail").click(function () {
        $('#my-prompt-budget-plan-detail').modal({
            relatedTarget: this,
            closeOnConfirm:false,
            onConfirm: function(e) {
                //校验数据正确性
                var message = verifyBudgetPlan();
                if (message) {
                    layuiAlert(message);
                    return;
                }
                //不能使用e.data，因为无法获取动态添加的
                var data = collectData("am-modal-prompt-input-budget-plan-detail");
                //data = prepareAjaxData(data, BUDGET_PLAN_DETAIL_ARR, $("#id").val(),false);
                data = prepareAjaxDataVerify(data, BUDGET_PLAN_DETAIL, $("#id").val());
                if(data){
                    postAjax(base+"/project/budgetEditSaveBudgetPlanDetail", data, updateBudgetPlanDetailData);
                }
            },
            onCancel: function(e) {
            }
        });
    });
});

layui.use('laydate', function(){
    var laydate = layui.laydate;

    laydate.render({
        elem: '#planStartStr',
        type: 'month',
        btns: ['confirm'],
        trigger: 'click',
        ready: function(){
            console.log($(this.elem).val());
        },
        done: function() {
            var time = $(this.elem).val();
            console.log("planStartStr:" + time)
            appendMultiplePlan();
            $("#planStartDate").val(time);
        }
    });
});

layui.use('laydate', function(){
    var laydate = layui.laydate;

    laydate.render({
        elem: '#planEndStr',
        type: 'month',
        btns: ['confirm'],
        trigger: 'click',
        ready: function(){
            console.log($(this.elem).val());
        },
        done: function() {
            var time = $(this.elem).val();
            console.log("planEndStr:" + time);
            appendMultiplePlan();
            $("#planEndDate").val(time);
        }
    });
});

function appendMultiplePlan() {
    var planStartStr = $("#planStartStr").val();
    var planEndStr = $("#planEndStr").val();
    if (planStartStr !== "" && planEndStr !== "") {
        if (planStartStr > planEndStr) {
            layuiAlert("开始时间不可大于结束时间");
            return;
        }
        var planStartDate = $("#planStartDate").val();
        var planEndDate = $("#planEndDate").val();
        var startYear = planStartStr.substring(0, 4);
        var startMonth = planStartStr.substring(5, 7);
        var totalStartMonth = startYear * 12 + parseInt(startMonth);
        var endYear = planEndStr.substring(0, 4);
        var endMonth = planEndStr.substring(5, 7);
        var totalEndMonth = endYear * 12 + parseInt(endMonth);
        var diff = totalEndMonth - totalStartMonth + 1;
        var planIndex = 0;
        if (planStartDate === "") {
            while (planIndex < diff) {
                appendTrBudgetPlan();
                planIndex++;
            }
        } else {
            if (planEndDate === "") {
                while (planIndex < diff) {
                    appendTrBudgetPlan();
                    planIndex++;
                }
            } else {
                var startYear2 = planStartDate.substring(0, 4);
                var startMonth2 = planStartDate.substring(5, 7);
                var totalStartMonth2 = startYear2 * 12 + parseInt(startMonth2);
                var endYear2 = planEndDate.substring(0, 4);
                var endMonth2 = planEndDate.substring(5, 7);
                var totalEndMonth2 = endYear2 * 12 + parseInt(endMonth2);
                if (totalStartMonth < totalStartMonth2) {
                    console.log("增加开始");
                    diff = totalStartMonth2 - totalStartMonth;
                    while (planIndex < diff) {
                        appendTrBudgetPlan2();
                        planIndex++;
                    }
                } else if (totalStartMonth > totalStartMonth2) {
                    console.log("减少开始");
                    $(".input-changeable-month-budget-plan").each(function () {
                        var cur = $(this).val();
                        if (cur < planStartStr) {
                            //删除自己对应的tr
                            $(this).parent().parent().remove();
                            delBudgetPlan();
                        }
                    });
                }
                if (totalEndMonth < totalEndMonth2) {
                    console.log("减少结束");
                    $(".input-changeable-month-budget-plan").each(function () {
                        var cur = $(this).val();
                        if (cur > planEndStr) {
                            //删除自己对应的tr
                            $(this).parent().parent().remove();
                            delBudgetPlan();
                        }
                    });
                } else if (totalEndMonth > totalEndMonth2) {
                    console.log("增加结束");
                    diff = totalEndMonth - totalEndMonth2;
                    while (planIndex < diff) {
                        appendTrBudgetPlan();
                        planIndex++;
                    }
                }
            }
        }
    }
}

/**
 * 删除现有项
 */
function delBudgetPlan() {

    //还需要更新每一列的合计数据
    updateBudgetPlanTotal("input-changeable-device-cost-budget-plan","input-total-device-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-engineer-cost-budget-plan","input-total-engineer-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-project-manage-cost-budget-plan","input-total-project-manage-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-earnest-money-cost-budget-plan","input-total-earnest-money-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-earnest-money-cost-budget-plan","input-total-title-earnest-money-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-total-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-title-total-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-sale-income-budget-plan","input-total-sale-income-budget-plan");
    updateBudgetPlanTotal("input-changeable-earnest-money-income-budget-plan","input-total-earnest-money-income-budget-plan");
    updateBudgetPlanTotal("input-changeable-earnest-money-income-budget-plan","input-total-title-earnest-money-income-budget-plan");
    updateBudgetPlanTotal("input-changeable-total-income-budget-plan","input-total-total-income-budget-plan");
    updateBudgetPlanTotal("input-changeable-total-income-budget-plan","input-total-title-total-income-budget-plan");
    /*updateBudgetPlanTotal("input-changeable-fund-balance-budget-plan","input-total-fund-balance-budget-plan");*/
    updateBudgetPlanTotal("input-changeable-capital-interest-budget-plan","input-total-capital-interest-budget-plan");
    updateBudgetPlanTotal("input-changeable-capital-interest-budget-plan","input-total-title-capital-interest-budget-plan");
    updateBudgetPlanTotal("input-changeable-underwritten-plan-budget-plan","input-total-underwritten-plan-budget-plan");
    updateBudgetPlanTotal("input-changeable-underwritten-plan-budget-plan","input-total-title-underwritten-plan-budget-plan");
    updateBudgetPlanTotal("input-changeable-repayment-plan-budget-plan","input-total-repayment-plan-budget-plan");
    updateBudgetPlanTotal("input-changeable-repayment-plan-budget-plan","input-total-title-repayment-plan-budget-plan");

    updatePageData();
}

/**
 *
 */
function bindMonth() {
    //找到每个月的资金余额输入框
    $(".input-changeable-month-budget-plan").each(function (t) {
        //找到前一个月的数据
        var prev = $(this).parent().parent().prev("tr").find(".input-changeable-month-budget-plan").val();
        if(!prev){
            //第一个月
            var startDate = $("#planStartStr").val();
            $(this).val(startDate.substring(0, 7));
        } else {
            var year = prev.substring(0, 4);
            var month = prev.substring(5, 7);
            var totalMonth = year * 12 + parseInt(month) + 1;
            var newYear = Math.floor((totalMonth - 1) / 12);
            var newMonth = totalMonth % 12;
            if (newMonth == 0) {
                newMonth = 12;
            }
            if (newMonth < 10) {
                newMonth = "0" + newMonth;
            }
            $(this).val(newYear + "-" + newMonth);
        }
    });
}

//保存资金计划表
$(function () {
    $("#budgetPlanDetailTableSave").click(function () {
        //校验数据正确性
        var message = verifyBudgetPlan();
        if (message) {
            layuiAlert(message);
            return;
        }

        //不能使用e.data，因为无法获取动态添加的
        var data = collectData("am-modal-prompt-input-budget-plan-detail");
        //data = prepareAjaxData(data, BUDGET_PLAN_DETAIL_ARR, $("#id").val(),false);
        data = prepareAjaxDataVerify(data, BUDGET_PLAN_DETAIL, $("#id").val());
        if(data){
            postAjax(base+"/project/budgetEditSaveBudgetPlanDetail", data, updateBudgetPlanDetailData);
        }
    });

    $("#budgetPlanDetailAddBtn").click(function () {
        appendTrBudgetPlan();
    });

    //绑定资金计划明细输入框
    bindChangeableInputBudgetPlanDetail();
    //绑定资金计划的删除按钮
    bindBudgetPlanDeleteBtn();
    //绑定公司管理费用的输入框
    bindCompanyManageChangeable();
    //绑定数字输入框保留两位小数
    bindNumberInput();
});

/**
 * 校验资金计划表
 * 校验失败返回相应的报错信息，否则返回""
 */
function verifyBudgetPlan(){
    //判断月份是否有重复
    var months = [];
    $(".input-changeable-month-budget-plan").each(function () {
        months.push($(this).val());
    });
    var ms = months.sort();
    for(var i = 0; i < ms.length - 1; i++) {
        if(ms[i] == ms[i + 1]) {
            return "选择的月份有重复，["+ms[i]+"]";
        }
    }

    var planStartStr = $("#planStartStr").val();
    var planEndStr = $("#planEndStr").val();
    if (planStartStr === "" || planEndStr === "") {
        return "请选择资金计划表中的开始时间和结束时间";
    }

    var costPurchaseDeviceTaxInclude = inputVal("costPurchaseDeviceTaxInclude");
    var costPurchaseBuildTaxInclude = inputVal("costPurchaseBuildTaxInclude");
    var costPurchaseServiceTaxInclude = inputVal("costPurchaseServiceTaxInclude");
    var costPurchaseOtherTaxInclude = inputVal("costPurchaseOtherTaxInclude");
    var costProjectManageTaxInclude = inputVal("costProjectManageTaxInclude");
    var incomeTotalTaxInclude = inputVal("incomeTotalTaxInclude");
    var input_total_device_cost_budget_plan = classVal("input-total-device-cost-budget-plan");
    var input_total_engineer_cost_budget_plan = classVal("input-total-engineer-cost-budget-plan");
    var input_total_project_manage_budget_plan = classVal("input-total-project-manage-cost-budget-plan");
    var input_total_sale_income_budget_plan = classVal("input-total-sale-income-budget-plan");
    var input_total_earnest_money_cost_budget_plan = classVal("input-total-earnest-money-cost-budget-plan");
    var input_total_earnest_money_income_budget_plan = classVal("input-total-earnest-money-income-budget-plan");


    //从采购成本明细中取“设备”大类下的总计---设备支出
    if(costPurchaseDeviceTaxInclude != input_total_device_cost_budget_plan){
        return "采购成本明细中取“设备”大类下的总计["+costPurchaseDeviceTaxInclude+"]与设备支出["+input_total_device_cost_budget_plan+"]不等";
    }
    //从采购成本明细中取“服务+施工+其他”大类的总计---工程支出
    var t = f2(f2(costPurchaseBuildTaxInclude)+f2(costPurchaseServiceTaxInclude)+f2(costPurchaseOtherTaxInclude));
    if(t != f2(input_total_engineer_cost_budget_plan)){
        return "采购成本明细中取“服务+施工+其他”大类的总计["+t+"]与工程支出["+input_total_engineer_cost_budget_plan+"]不等";
    }
    //从项目管理成本取总计金额--经营性开支
    if(costProjectManageTaxInclude != input_total_project_manage_budget_plan){
        return "项目管理成本取总计金额["+costProjectManageTaxInclude+"]与经营性开支["+input_total_project_manage_budget_plan+"]不等";
    }
    //从“销售收入明细”中取合计--销售收款
    if(incomeTotalTaxInclude != input_total_sale_income_budget_plan){
        return "销售收入明细金额["+incomeTotalTaxInclude+"]与销售收款["+input_total_sale_income_budget_plan+"]不等";
    }
    //保证金支出和收入一致
    if(input_total_earnest_money_cost_budget_plan != input_total_earnest_money_income_budget_plan){
        return "保证金支出["+input_total_earnest_money_cost_budget_plan+"]与保证金收款["+input_total_earnest_money_income_budget_plan+"]不等";
    }

    return "";

}

/**
 * 资金计划增加一行
 */
function appendTrBudgetPlan() {
    var template = '<tr style="display: inline-block;">\n' +
        '        <td style="display: block;"><input type="text" class="am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-month-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-device-cost-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-engineer-cost-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-project-manage-cost-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-earnest-money-cost-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-total-cost-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-sale-income-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-earnest-money-income-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-total-income-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-fund-balance-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-capital-interest-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-underwritten-plan-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-repayment-plan-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><button type="button" class="am-btn am-btn-danger am-btn-xs am-round am-modal-line-delete-budget-plan"><span class="am-icon-minus"></span></button></td>\n' +
        '    </tr>';
    $("#budgetPlanDetailTable").append(template);
    //根据前一条数据拿到月份
    bindMonth();
    //新增的收入与支出默认为0，并更新每一列的数据
    bindBudgetPlanUpdate();
    //重新绑定删除事件和input修改事件
    bindBudgetPlanDeleteBtn();
    //绑定资金计划明细输入框
    bindChangeableInputBudgetPlanDetail();
    //绑定数字输入框保留两位小数
    bindNumberInput();
}

/**
 * 资金计划增加一行
 */
function appendTrBudgetPlan2() {
    var template = '<tr style="display: inline-block;">\n' +
        '        <td style="display: block;"><input type="text" class="am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-month-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-device-cost-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-engineer-cost-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-project-manage-cost-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-earnest-money-cost-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-total-cost-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-sale-income-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" maxlength="16" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-earnest-money-income-budget-plan"></td>\n' +
        '        <td style="display: block;"><input type="text" value="0.00" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-total-income-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-fund-balance-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-capital-interest-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-underwritten-plan-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><input type="text" class="number am-modal-prompt-input am-modal-prompt-input-budget-plan-detail input-changeable-repayment-plan-budget-plan" readonly></td>\n' +
        '        <td style="display: block;"><button type="button" class="am-btn am-btn-danger am-btn-xs am-round am-modal-line-delete-budget-plan"><span class="am-icon-minus"></span></button></td>\n' +
        '    </tr>';
    $("#firstBlock").after(template);
    //根据前一条数据拿到月份
    bindMonth();
    //新增的收入与支出默认为0，并更新每一列的数据
    bindBudgetPlanUpdate();
    //重新绑定删除事件和input修改事件
    bindBudgetPlanDeleteBtn();
    //绑定资金计划明细输入框
    bindChangeableInputBudgetPlanDetail();
    //绑定数字输入框保留两位小数
    bindNumberInput();
}

// /**
//  * 给月份输入框绑定日期选择框
//  */
// function renderMonthDatePicker() {
//     $(".input-changeable-month-budget-plan").datepicker({
//         format: 'yyyy-mm',
//         viewMode: 'years',
//         minViewMode: 'months'/*,
//         autoClose:true*/
//     });
//
//     //解决不能自动关闭的问题
//     $(".am-datepicker-month").on("click", function() {
//         $(".am-datepicker").hide();
//     });
// }

/**
 * 新增默认为0，并更新每一列的数据
 */
function bindBudgetPlanUpdate() {
    //还需要更新每一列的合计数据
    updateBudgetPlanTotal("input-changeable-device-cost-budget-plan","input-total-device-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-engineer-cost-budget-plan","input-total-engineer-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-project-manage-cost-budget-plan","input-total-project-manage-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-earnest-money-cost-budget-plan","input-total-earnest-money-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-earnest-money-cost-budget-plan","input-total-title-earnest-money-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-total-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-title-total-cost-budget-plan");
    updateBudgetPlanTotal("input-changeable-sale-income-budget-plan","input-total-sale-income-budget-plan");
    updateBudgetPlanTotal("input-changeable-earnest-money-income-budget-plan","input-total-earnest-money-income-budget-plan");
    updateBudgetPlanTotal("input-changeable-earnest-money-income-budget-plan","input-total-title-earnest-money-income-budget-plan");
    updateBudgetPlanTotal("input-changeable-total-income-budget-plan","input-total-total-income-budget-plan");
    updateBudgetPlanTotal("input-changeable-total-income-budget-plan","input-total-title-total-income-budget-plan");
    /*updateBudgetPlanTotal("input-changeable-fund-balance-budget-plan","input-total-fund-balance-budget-plan");*/
    updateBudgetPlanTotal("input-changeable-capital-interest-budget-plan","input-total-capital-interest-budget-plan");
    updateBudgetPlanTotal("input-changeable-capital-interest-budget-plan","input-total-title-capital-interest-budget-plan");
    updateBudgetPlanTotal("input-changeable-underwritten-plan-budget-plan","input-total-underwritten-plan-budget-plan");
    updateBudgetPlanTotal("input-changeable-underwritten-plan-budget-plan","input-total-title-underwritten-plan-budget-plan");
    updateBudgetPlanTotal("input-changeable-repayment-plan-budget-plan","input-total-repayment-plan-budget-plan");
    updateBudgetPlanTotal("input-changeable-repayment-plan-budget-plan","input-total-title-repayment-plan-budget-plan");

    updatePageData();
}

/**
 * 绑定删除删除按钮，不仅删除还需要重新计算统计的数据
 */
function bindBudgetPlanDeleteBtn() {
    $(".am-modal-line-delete-budget-plan").click(function () {
        // //删除自己对应的tr
        // $(this).parent().parent().remove();
        $(this).parent().parent().find(".input-changeable-device-cost-budget-plan").val(f2Fixed(0));
        $(this).parent().parent().find(".input-changeable-engineer-cost-budget-plan").val(f2Fixed(0));
        $(this).parent().parent().find(".input-changeable-project-manage-cost-budget-plan").val(f2Fixed(0));
        $(this).parent().parent().find(".input-changeable-earnest-money-cost-budget-plan").val(f2Fixed(0));
        $(this).parent().parent().find(".input-changeable-total-cost-budget-plan").val(f2Fixed(0));
        $(this).parent().parent().find(".input-changeable-sale-income-budget-plan").val(f2Fixed(0));
        $(this).parent().parent().find(".input-changeable-earnest-money-income-budget-plan").val(f2Fixed(0));
        $(this).parent().parent().find(".input-changeable-total-income-budget-plan").val(f2Fixed(0));
        //还需要更新每一列的合计数据
        updateBudgetPlanTotal("input-changeable-device-cost-budget-plan","input-total-device-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-engineer-cost-budget-plan","input-total-engineer-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-project-manage-cost-budget-plan","input-total-project-manage-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-earnest-money-cost-budget-plan","input-total-earnest-money-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-earnest-money-cost-budget-plan","input-total-title-earnest-money-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-total-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-title-total-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-sale-income-budget-plan","input-total-sale-income-budget-plan");
        updateBudgetPlanTotal("input-changeable-earnest-money-income-budget-plan","input-total-earnest-money-income-budget-plan");
        updateBudgetPlanTotal("input-changeable-earnest-money-income-budget-plan","input-total-title-earnest-money-income-budget-plan");
        updateBudgetPlanTotal("input-changeable-total-income-budget-plan","input-total-total-income-budget-plan");
        updateBudgetPlanTotal("input-changeable-total-income-budget-plan","input-total-title-total-income-budget-plan");
        /*updateBudgetPlanTotal("input-changeable-fund-balance-budget-plan","input-total-fund-balance-budget-plan");*/
        updateBudgetPlanTotal("input-changeable-capital-interest-budget-plan","input-total-capital-interest-budget-plan");
        updateBudgetPlanTotal("input-changeable-capital-interest-budget-plan","input-total-title-capital-interest-budget-plan");
        updateBudgetPlanTotal("input-changeable-underwritten-plan-budget-plan","input-total-underwritten-plan-budget-plan");
        updateBudgetPlanTotal("input-changeable-underwritten-plan-budget-plan","input-total-title-underwritten-plan-budget-plan");
        updateBudgetPlanTotal("input-changeable-repayment-plan-budget-plan","input-total-repayment-plan-budget-plan");
        updateBudgetPlanTotal("input-changeable-repayment-plan-budget-plan","input-total-title-repayment-plan-budget-plan");

        updatePageData();

    });
}

function bindChangeableInputBudgetPlanDetail() {
    //设备支出改变
    $(".input-changeable-device-cost-budget-plan").change(function () {
        var deviceCost = f2($(this).val());
        //找到对应的工程支出、经营性支出、保证金支出
        var engineerCost = f2($(this).parent().parent().find(".input-changeable-engineer-cost-budget-plan").val());
        var projectManageCost = f2($(this).parent().parent().find(".input-changeable-project-manage-cost-budget-plan").val());
        var earnestMoneyCost = f2($(this).parent().parent().find(".input-changeable-earnest-money-cost-budget-plan").val());

        //更新本月所有项支出
        $(this).parent().parent().find(".input-changeable-total-cost-budget-plan").val(f2Fixed(deviceCost+engineerCost+projectManageCost+earnestMoneyCost));
        //更新所有月设备支出总额
        updateBudgetPlanTotal("input-changeable-device-cost-budget-plan","input-total-device-cost-budget-plan");
        //更新所有月支出总额
        updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-total-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-title-total-cost-budget-plan");

        updatePageData();
    });
    //工程支出改变
    $(".input-changeable-engineer-cost-budget-plan").change(function () {
        var engineerCost = f2($(this).val());
        //找到对应的设备支出、经营性支出、保证金支出
        var deviceCost = f2($(this).parent().parent().find(".input-changeable-device-cost-budget-plan").val());
        var projectManageCost = f2($(this).parent().parent().find(".input-changeable-project-manage-cost-budget-plan").val());
        var earnestMoneyCost = f2($(this).parent().parent().find(".input-changeable-earnest-money-cost-budget-plan").val());

        //更新本月所有项支出
        $(this).parent().parent().find(".input-changeable-total-cost-budget-plan").val(f2Fixed(deviceCost+engineerCost+projectManageCost+earnestMoneyCost));
        //更新所有月工程支出总额
        updateBudgetPlanTotal("input-changeable-engineer-cost-budget-plan","input-total-engineer-cost-budget-plan");
        //更新所有月支出总额
        updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-total-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-title-total-cost-budget-plan");

        updatePageData();
    });
    //经营性支出改变
    $(".input-changeable-project-manage-cost-budget-plan").change(function () {
        var projectManageCost = f2($(this).val());
        //找到对应的设备支出、工程支出、保证金支出
        var deviceCost = f2($(this).parent().parent().find(".input-changeable-device-cost-budget-plan").val());
        var engineerCost = f2($(this).parent().parent().find(".input-changeable-engineer-cost-budget-plan").val());
        var earnestMoneyCost = f2($(this).parent().parent().find(".input-changeable-earnest-money-cost-budget-plan").val());

        //更新本月所有项支出
        $(this).parent().parent().find(".input-changeable-total-cost-budget-plan").val(f2Fixed(deviceCost+engineerCost+projectManageCost+earnestMoneyCost));
        //更新所有月经营性支出总额
        updateBudgetPlanTotal("input-changeable-project-manage-cost-budget-plan","input-total-project-manage-cost-budget-plan");
        //更新所有月支出总额
        updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-total-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-title-total-cost-budget-plan");

        updatePageData();
    });
    //保证金改变
    $(".input-changeable-earnest-money-cost-budget-plan").change(function () {
        var earnestMoneyCost = f2($(this).val());
        //找到对应的设备支出、经营性支出、保证金支出
        var deviceCost = f2($(this).parent().parent().find(".input-changeable-device-cost-budget-plan").val());
        var engineerCost = f2($(this).parent().parent().find(".input-changeable-engineer-cost-budget-plan").val());
        var projectManageCost = f2($(this).parent().parent().find(".input-changeable-project-manage-cost-budget-plan").val());

        //更新本月所有项支出
        $(this).parent().parent().find(".input-changeable-total-cost-budget-plan").val(f2Fixed(deviceCost+engineerCost+projectManageCost+earnestMoneyCost));
        //更新所有月保证金支出总额
        updateBudgetPlanTotal("input-changeable-earnest-money-cost-budget-plan","input-total-earnest-money-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-earnest-money-cost-budget-plan","input-total-title-earnest-money-cost-budget-plan");
        //更新所有月支出总额
        updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-total-cost-budget-plan");
        updateBudgetPlanTotal("input-changeable-total-cost-budget-plan","input-total-title-total-cost-budget-plan");

        updatePageData();
    });

    //销售收款改变
    $(".input-changeable-sale-income-budget-plan").change(function () {
        var saleIncome = f2($(this).val());
        //找到保证金收款
        var earnestMoneyIncome = f2($(this).parent().parent().find(".input-changeable-earnest-money-income-budget-plan").val());

        //更新本月所有项收入
        $(this).parent().parent().find(".input-changeable-total-income-budget-plan").val(f2Fixed(saleIncome+earnestMoneyIncome));
        //更新所有月销售收款总额
        updateBudgetPlanTotal("input-changeable-sale-income-budget-plan","input-total-sale-income-budget-plan");
        //更新所有月收入总额
        updateBudgetPlanTotal("input-changeable-total-income-budget-plan","input-total-total-income-budget-plan");
        updateBudgetPlanTotal("input-changeable-total-income-budget-plan","input-total-title-total-income-budget-plan");

        updatePageData();
    });
    //保证金收款改变
    $(".input-changeable-earnest-money-income-budget-plan").change(function () {
        var earnestMoneyIncome = f2($(this).val());
        //找到保证金收款
        var saleIncome = f2($(this).parent().parent().find(".input-changeable-sale-income-budget-plan").val());

        //更新本月所有项收入
        $(this).parent().parent().find(".input-changeable-total-income-budget-plan").val(f2Fixed(saleIncome+earnestMoneyIncome));
        //更新所有月保证金收款总额
        updateBudgetPlanTotal("input-changeable-earnest-money-income-budget-plan","input-total-earnest-money-income-budget-plan");
        updateBudgetPlanTotal("input-changeable-earnest-money-income-budget-plan","input-total-title-earnest-money-income-budget-plan");
        //更新所有月收入总额
        updateBudgetPlanTotal("input-changeable-total-income-budget-plan","input-total-total-income-budget-plan");
        updateBudgetPlanTotal("input-changeable-total-income-budget-plan","input-total-title-total-income-budget-plan");

        updatePageData();
    });


    /*//资金余额改变
    $(".input-changeable-fund-balance-budget-plan").change(function () {
        updateBudgetPlanTotal("input-changeable-fund-balance-budget-plan","input-total-fund-balance-budget-plan");
    });*/
    //资金利息改变
    $(".input-changeable-capital-interest-budget-plan").change(function () {
        updateBudgetPlanTotal("input-changeable-capital-interest-budget-plan","input-total-capital-interest-budget-plan");
        updateBudgetPlanTotal("input-changeable-capital-interest-budget-plan","input-total-title-capital-interest-budget-plan");
    });
    //垫资计划改变
    $(".input-changeable-underwritten-plan-budget-plan").change(function () {
        updateBudgetPlanTotal("input-changeable-underwritten-plan-budget-plan","input-total-underwritten-plan-budget-plan");
        updateBudgetPlanTotal("input-changeable-underwritten-plan-budget-plan","input-total-title-underwritten-plan-budget-plan");
    });
    //还款计划改变
    $(".input-changeable-repayment-plan-budget-plan").change(function () {
        updateBudgetPlanTotal("input-changeable-repayment-plan-budget-plan","input-total-repayment-plan-budget-plan");
        updateBudgetPlanTotal("input-changeable-repayment-plan-budget-plan","input-total-title-repayment-plan-budget-plan");
    });
}


function updatePageData() {
    //更新余额
    updateEachFundBalance();
    //更新垫资计划
    updateEachUnderwrittenPlan();
    //更新回款计划
    updateEachRepaymentPlan();
    //更新资金利息
    updateEachCapitalInterest();
    //更新垫资峰值月
    updateUnderwrittenInfo();
}

/**
 * 更新每列的总计
 */
function updateBudgetPlanTotal(className, totalClassName) {
    var total = 0;
    //找到本列所有的
    $("."+className).each(function (t) {
        total += f2($(this).val());
    });

    $("."+totalClassName).val(f2Fixed(total));
}

/**
 * 更新每一行【即每个月】的资金余额
 * 每个月的余额=本月收入-支出+上月余额
 */
function updateEachFundBalance() {
    var fundBalance = 0;
    //找到每个月的资金余额输入框
    $(".input-changeable-fund-balance-budget-plan").each(function (t) {
        //找到当前月的收入和支出
        var income = f2($(this).parent().parent().find(".input-changeable-total-income-budget-plan").val());
        var cost = f2($(this).parent().parent().find(".input-changeable-total-cost-budget-plan").val());
        //我的上月余额
        var prevFundBalance = f2($(this).parent().parent().prev("tr").find(".input-changeable-fund-balance-budget-plan").val());
        if(!prevFundBalance){
            //第一个月的话，上月余额就为0
            prevFundBalance = 0;
        }
        fundBalance = income - cost + prevFundBalance;
        $(this).val(f2Fixed(fundBalance));
    });

    //总余额=最后一个月的余额
    $(".input-total-fund-balance-budget-plan").val(f2Fixed(fundBalance));
    $(".input-total-title-fund-balance-budget-plan").val(f2Fixed(fundBalance));
}


/**
 * 更新每一行【即每个月】的垫资计划
 */
function updateEachUnderwrittenPlan() {
    var total = 0;
    //找到每个月的垫资计划输入框
    $(".input-changeable-underwritten-plan-budget-plan").each(function (t) {
        //找到当前月的收入和支出
        var income = $(this).parent().parent().find(".input-changeable-total-income-budget-plan").val();
        var cost = $(this).parent().parent().find(".input-changeable-total-cost-budget-plan").val();
        //我的上月余额
        var prevFundBalance = $(this).parent().parent().prev("tr").find(".input-changeable-fund-balance-budget-plan").val();
        if(!prevFundBalance){
            //第一个月的话，上月余额就为0
            prevFundBalance = 0;
        }
        var underwrittenPlan = calUnderwrittenPlan(income, cost, prevFundBalance);

        total += underwrittenPlan;

        $(this).val(f2Fixed(underwrittenPlan));
    });

    //总垫资计划=所有月累加
    $(".input-total-underwritten-plan-budget-plan").val(f2Fixed(total));
    $(".input-total-title-underwritten-plan-budget-plan").val(f2Fixed(total));
    //下放小表的垫资峰值金额
    $(".input-underwritten-plan-statistic-amount-budget-plan").val(f2Fixed(total));
}

/**
 * 计算垫资计划
 * @param income 收入
 * @param cost 支出
 * @param prevFundBalance 上月余额
 */
function calUnderwrittenPlan(income, cost, prevFundBalance) {
    var underwrittenPlan = 0;

    if(!income || !cost){
        //数据还不全的时候
        underwrittenPlan = NaN;
    }else {
        if (f2(income) - f2(cost) >= 0) {
            underwrittenPlan = 0;
        } else {
            if (f2(prevFundBalance) < 0) {
                underwrittenPlan = f2(f2(cost) - f2(income));
            } else {
                if (f2(prevFundBalance) <= f2(cost) - f2(income)) {
                    underwrittenPlan = f2(f2(cost) - f2(income) - f2(prevFundBalance));
                } else {
                    underwrittenPlan = 0;
                }
            }
        }
    }

    return underwrittenPlan;
}

/**
 * 更新每一行【即每个月】的还款计划
 */
function updateEachRepaymentPlan() {
    var total = 0;
    //找到每个月的回款计划输入框
    $(".input-changeable-repayment-plan-budget-plan").each(function (t) {
        //找到当前月的收入和支出
        var income = $(this).parent().parent().find(".input-changeable-total-income-budget-plan").val();
        var cost = $(this).parent().parent().find(".input-changeable-total-cost-budget-plan").val();
        //我的上月余额
        var prevFundBalance = $(this).parent().parent().prev("tr").find(".input-changeable-fund-balance-budget-plan").val();
        if(!prevFundBalance){
            //第一个月的话，上月余额就为0
            prevFundBalance = 0;
        }


        var repaymentPlan = calRepaymentPlan(income, cost, prevFundBalance);

        total += repaymentPlan;

        $(this).val(f2Fixed(repaymentPlan));

    });

    //总回款计划=所有月累加
    $(".input-total-repayment-plan-budget-plan").val(f2Fixed(total));
    $(".input-total-title-repayment-plan-budget-plan").val(f2Fixed(total));
}

/**
 * 计算回款计划
 * @param income 收入
 * @param cost 支出
 * @param prevFundBalance 上月余额
 */
function calRepaymentPlan(income, cost, prevFundBalance) {
    var repaymentPlan = 0;
    if(!income || !cost){
        //数据还不全的时候
        repaymentPlan = NaN;
    }else {
        if (f2(income) - f2(cost) <= 0) {
            repaymentPlan = 0;
        } else {
            if (f2(prevFundBalance) >= 0) {
                repaymentPlan = 0;
            } else {
                if (-f2(prevFundBalance) >= f2(income) - f2(cost)) {
                    repaymentPlan = f2(f2(income) - f2(cost));
                } else {
                    repaymentPlan = -f2(prevFundBalance);
                }
            }
        }
    }

    return repaymentPlan;
}

/**
 * 更新每一行【即每个月】的资金利息
 */
function updateEachCapitalInterest() {
    //找到年利率
    var underwrittenPlanTaxRate = f2($(".input-underwritten-plan-statistic-tax-rate-budget-plan").val());
    var total = 0;


    //找到每个月的资金利息输入框
    $(".input-changeable-capital-interest-budget-plan").each(function (index,element) {

        //找到本月之前的所有的垫资和回款
        var underwrittenPlan = summationByClass($(this),".input-changeable-underwritten-plan-budget-plan", index);
        var repaymentPlan= summationByClass($(this),".input-changeable-repayment-plan-budget-plan", index);
        console.log(underwrittenPlan, repaymentPlan);
        var capitalInterest = f2((underwrittenPlan-repaymentPlan)*underwrittenPlanTaxRate/100/12);
        total += capitalInterest;

        $(this).val(f2Fixed(capitalInterest));

    });

    //总资金利息=所有月累加
    $(".input-total-capital-interest-budget-plan").val(f2Fixed(total));
    $(".input-total-title-capital-interest-budget-plan").val(f2Fixed(total));
    //下方小表的资金利息
    $(".input-underwritten-plan-statistic-capital-interest-budget-plan").val(f2Fixed(total));
}

/**
 * 从输入框开始找到我上面的所有的包含className的输入框的值的和
 */
function summationByClass(input, className, myIndex) {
    var total = 0;
    var trs = input.parent().parent().parent().find("tr");
    trs.each(function (index, element) {
        //myIndex从0开始，刨除表头和总计、总计两行
        index-=2;
        if(index>=0 && index<=myIndex){
            total += f2($(this).find(className).val());
        }
    });

    return total;
}

/*function updateEachCapitalInterest() {
    var underwrittenPlanTaxRate = f2($(".input-underwritten-plan-statistic-tax-rate-budget-plan").val());
    var total = 0;
    //找到每个月的资金利息输入框
    $(".input-changeable-capital-interest-budget-plan").each(function (t) {
        //找到当前月的垫资计划
        var underwrittenPlan = f2($(this).parent().parent().find(".input-changeable-underwritten-plan-budget-plan").val());
        var capitalInterest = underwrittenPlan*underwrittenPlanTaxRate/100/12;
        total += capitalInterest;

        $(this).val(f2(capitalInterest));

    });

    //总资金利息=所有月累加
    $(".input-total-capital-interest-budget-plan").val(f2(total));
    //下方小表的资金利息
    $(".input-underwritten-plan-statistic-capital-interest-budget-plan").val(f2(total));
}*/

/**
 * 更新资金相关信息
 *
 垫资峰值时间 垫资最大的那一个月
 垫资峰值金额 垫资累计 @see updateEachUnderwrittenPlan
 资金利息 垫资每月利息累加 @see updateEachCapitalInterest
 */
function updateUnderwrittenInfo() {
    var max = 0;
    var month = '';
    //找到每个月的垫资计划输入框
    $(".input-changeable-underwritten-plan-budget-plan").each(function (t) {
        //找到当前月垫资计划
        var underwrittenPlan = f2($(this).val());
        //当月比最大的还大，就取当月的
        if(underwrittenPlan > max){
            month = $(this).parent().parent().find(".input-changeable-month-budget-plan").val();
            max = underwrittenPlan;
        }
    });

    //垫资峰值时间为每个月最大的那个月
    $(".input-underwritten-plan-statistic-max-month-budget-plan").val(month);
}



/**
 * 更新页面收入的数据
 */
function updateBudgetPlanDetailData(data,returnData) {
    //var details = data.details;
    //主页面上的财务费用
    $("input[name='costExpropriationTaxExclude']").val($(".input-underwritten-plan-statistic-capital-interest-budget-plan").val());
    //更新项目贡献率
    updateProjectContributionProfitRate();
    //更新现金流量
    updateCashFlow();

    layuiAlert("保存成功");
    $('#my-prompt-budget-plan-detail').modal('close');
}


/**
 * 绑定公司管理费用输入框
 */
function bindCompanyManageChangeable() {
    $("input[name='costCompanyManageTaxExclude']").change(function () {
        //更新项目贡献率
        updateProjectContributionProfitRate();
    });
}

/**
 * 更新现金流量表
 */
function updateCashFlow() {

    var saleIncome = classVal("input-total-sale-income-budget-plan");
    var earnestMoneyIncome = classVal("input-total-earnest-money-income-budget-plan");
    var deviceCost = classVal("input-total-device-cost-budget-plan");
    var engineerCost = classVal("input-total-engineer-cost-budget-plan");

    var projectManageCost = classVal("input-total-project-manage-cost-budget-plan");
    var earnestMoneyCost = classVal("input-total-earnest-money-cost-budget-plan");
    var capitalInterest = classVal("input-total-capital-interest-budget-plan");

    var underwrittenPlan = classVal("input-total-underwritten-plan-budget-plan");
    var repaymentPlan = classVal("input-total-repayment-plan-budget-plan");

    var d = f2(f2(deviceCost)+f2(engineerCost));
    var f = f2(f2(projectManageCost)+f2(earnestMoneyCost)+f2(capitalInterest));
    var g = f2(f2(saleIncome)+0+f2(earnestMoneyIncome)-d-0-f);
    var m = f2(f2(underwrittenPlan)-f2(repaymentPlan));
    var n = f2(g+0+m);

    /*console.log(saleIncome,earnestMoneyIncome,deviceCost,
        engineerCost,projectManageCost,earnestMoneyCost,
        capitalInterest,underwrittenPlan,repaymentPlan,
        d,f,g,m,m);*/


    $("input[name='saleIncomeCash']").val(f2Fixed(f2(saleIncome)));
    $("input[name='earnestMoneyIncome']").val(f2Fixed(f2(earnestMoneyIncome)));
    $("input[name='purchaseCost']").val(f2Fixed(d));
    $("input[name='earnestMoneyCost']").val(f2Fixed(f));

    $("input[name='netCashFlow']").val(f2Fixed(g));

    $("input[name='financingCapitalInflow']").val(f2Fixed(f2(underwrittenPlan)));
    $("input[name='financingCapitalOutflow']").val(f2Fixed(f2(repaymentPlan)));

    $("input[name='financingCapitalCashflow']").val(f2Fixed(m));
    $("input[name='netIncreaseMonetaryFunds']").val(f2Fixed(n));
}