/**
 * 一个采购成本详情的字段
 */
//COST_DETAIL_ARR=["type","category","name","unit","amount","price","taxRate","totalTaxInclude","totalTaxExclude"];
COST_DETAIL={
    "num":[false,"序号","string"],
    "type":[true,"大类","string"],
    "category":[true,"类别","string"],
    "name":[true,"名称","string"],
    "unit":[true,"单位","string"],
    "amount":[true,"数量","string"],
    "price":[true,"单价","price"],
    "taxRate":[true,"税率","number"],
    "totalTaxInclude":[true,"含税总金额","number"],
    "totalTaxExclude":[true,"不含税金额","number"]
};
/*
[
    {"id":"1","name":"xxx1"},{"id":"2","name":"xxx2"}
]
 */
SELECT_TYPE_CATEGORY_DATA=[];
/*{
    "1":[
        {
            "id":"1",
            "name":"华智产品"
        },
        {
            "id":"2",
            "name":"紫光其他产品"
        },
        {
            "id":"3",
            "name":"外购产品"
        }
    ],
    "2":[
        {
            "id":"4",
            "name":"外购工程"
        }
    ],
    "3":[
        {
            "id":"5",
            "name":"华智服务"
        },
        {
            "id":"6",
            "name":"紫光其他服务"
        },
        {
            "id":"7",
            "name":"外购服务"
        }
    ],
    "4":[
        {
            "id":"8",
            "name":"其他"
        }
    ]
};*/
SELECT_TYPE_CATEGORY_MAP_DATA={};
/*{
    "1":"1",
    "2":"1",
    "3":"1",
    "4":"2",
    "5":"3",
    "6":"3",
    "7":"3",
    "8":"4"
};
*/
SELECT_CATEGORY_TYPE_MAP_DATA={};

/*$(function () {
    $("#cost-detail").click(function () {
        $('#my-prompt-cost-detail').modal({
            relatedTarget: this,
            closeOnConfirm:false,
            onConfirm: function(e) {
                //不能使用e.data，因为无法获取动态添加的
                var data = collectData("am-modal-prompt-input-cost");
                //data = prepareAjaxData(data, COST_DETAIL_ARR, $("#id").val(),false);
                data = prepareAjaxDataVerify(data, COST_DETAIL, $("#id").val());
                if(data){
                    postAjax(base+"/project/budgetEditSaveCostDetail", data, updateCostData);
                }
            },
            onCancel: function(e) {
            }
        });
    });
    $("#costAddBtn").click(function () {
        appendTrCost();
    });

    //绑定其他其他的输入框
    bindOtherOtherChangeable();
    //绑定采购明细中select联动事件
    bindTypeSelectChange();

    //初始化大类和类别的数据
    getAjax(base+"/procurement/type/map", null, initTypeCategory);
});*/

$(function () {
    $("#cost-detail").click(function () {
        $('#my-prompt-cost-detail').modal({
            relatedTarget: this,
            closeOnConfirm:false,
            onConfirm: function(e) {
                //不能使用e.data，因为无法获取动态添加的
                var data = collectData("am-modal-prompt-input-cost");
                //data = prepareAjaxData(data, COST_DETAIL_ARR, $("#id").val(),false);
                data = prepareAjaxDataVerify(data, COST_DETAIL, $("#id").val());
                if(data){
                    postAjax(base+"/project/budgetEditSaveCostDetail", data, updateCostData);
                }
            },
            onCancel: function(e) {
            }
        });
    });
});

//保存采购成本明细表
$(function () {
    $("#costTableSave").click(function () {
        //不能使用e.data，因为无法获取动态添加的
        var data = collectData("am-modal-prompt-input-cost");
        //data = prepareAjaxData(data, COST_DETAIL_ARR, $("#id").val(),false);
        data = prepareAjaxDataVerify(data, COST_DETAIL, $("#id").val());
        if(data){
            postAjax(base+"/project/budgetEditSaveCostDetail", data, updateCostData);
        }
    });

    $("#costAddBtn").click(function () {
        appendTrCost();
    });

    //绑定其他其他的输入框
    bindOtherOtherChangeable();
    //绑定采购明细中select联动事件
    bindTypeSelectChange();

    //初始化大类和类别的数据
    getAjax(base+"/procurement/type/map", null, initTypeCategory);
});

/**
 * 采购成本增加一行
 */
function appendTrCost() {
    //console.log(SELECT_TYPE_CATEGORY_DATA);
    var options = '<option value="xxxx" disabled selected>--请选择--</option>\r\n';
    SELECT_TYPE_CATEGORY_DATA.forEach(function (e) {
        options+='<option value="'+e.id+'">'+e.name+'</option>\r\n';
    });

    var template = '<tr>' +
        '<td><input type="text" class="am-modal-prompt-input am-modal-prompt-input-cost input-budget-num" readonly></td>' +
        '<td><select style="width: 100px;float: left;" class="am-modal-prompt-input am-modal-prompt-input-cost am-modal-prompt-input-cost-type">'+
        '<option value="xxxx" disabled selected>--请选择--</option>'+
        '<option value="1">设备</option>'+
        '<option value="2">施工</option>'+
        '<option value="3">服务</option>'+
        '<option value="4">其他</option>'+
        '</select>'+
        '</td>'+
        '<td>'+
        '<select style="width: 180px;float: left;" class="am-modal-prompt-input am-modal-prompt-input-cost am-modal-prompt-input-cost-category">'+

        /*'<option value="1">华智产品</option>'+
        '<option value="2">紫光其他产品</option>'+
        '<option value="3">外购产品</option>'+
        '<option value="4">外购工程</option>'+
        '<option value="5">华智服务</option>'+
        '<option value="6">紫光其他服务</option>'+
        '<option value="7">外购服务</option>'+
        '<option value="8">其他</option>'+*/

        options+

        '</select>'+
        '</td>'+
        '<td><input type="text" class="am-modal-prompt-input am-modal-prompt-input-cost"></td>'+
        '<td><input type="text" class="am-modal-prompt-input am-modal-prompt-input-cost""></td>'+
        '<td><input type="number" min="0" max="99999999" step="1" maxlength="8" class="am-modal-prompt-input am-modal-prompt-input-cost input-changeable-amount input-changeable-amount-cost"></td>'+
        '<td><input type="text" min="0.00" max="9999999999.99" step="0.01" maxlength="19" class="price am-modal-prompt-input am-modal-prompt-input-cost input-changeable-price input-changeable-price-cost"></td>'+
        '<td><input type="text" min="0.00" max="99.99" step="0.01" maxlength="5" class="number am-modal-prompt-input am-modal-prompt-input-cost input-changeable-tax-rate input-changeable-tax-rate-cost"></td>'+
        '<td><input type="text" class="am-modal-prompt-input am-modal-prompt-input-cost input-changeable-total-tax-include input-changeable-total-tax-include-cost" readonly></td>'+
        '<td><input type="text" class="am-modal-prompt-input am-modal-prompt-input-cost input-changeable-total-tax-exclude input-changeable-total-tax-exclude-cost" readonly></td>'+
        '<td><button type="button" style="margin-top: 10px" class="am-btn am-btn-danger am-btn-xs am-round am-modal-line-delete"><span class="am-icon-minus"></span></button></td>'+
    '</tr>';

    $("#costTotal").before(template);
    //重新绑定删除事件和input修改事件
    bindDeleteBtnCost();
    //绑定序号
    bindNum();
    //重新绑定
    bindChangeableInput();
    //绑定总计值
    bindCostTotal();
    //绑定采购明细中select联动事件
    bindTypeSelectChange();
    //绑定数字输入框保留两位小数
    bindNumberInput();
}

/**
 * 绑定每一行的删除事件，删除当前的一行tr，修改总计值
 */
function bindDeleteBtnCost() {
    $(".am-modal-line-delete").click(function () {
        //删除自己对应的tr
        $(this).parent().parent().remove();
        bindNum();
        updateAmount("input-changeable-amount-cost", "input-changeable-total-amount-cost");
        updateTotal("input-changeable-total-tax-include-cost", "input-changeable-total-total-tax-include-cost");
        updateTotal("input-changeable-total-tax-exclude-cost", "input-changeable-total-total-tax-exclude-cost");
    });
}

/**
 * 绑定每个可改变的输入框，修改后改变对应输入框的值
 */
function bindCostTotal() {
    //数量改变
    $(".input-changeable-amount-cost").change(function () {
        updateAmount("input-changeable-amount-cost", "input-changeable-total-amount-cost");
        updateTotal("input-changeable-total-tax-include-cost", "input-changeable-total-total-tax-include-cost");
        updateTotal("input-changeable-total-tax-exclude-cost", "input-changeable-total-total-tax-exclude-cost");
    });
    //单价改变
    $(".input-changeable-price-cost").change(function () {
        updateTotal("input-changeable-total-tax-include-cost", "input-changeable-total-total-tax-include-cost");
        updateTotal("input-changeable-total-tax-exclude-cost", "input-changeable-total-total-tax-exclude-cost");
    });
    //税率改变
    $(".input-changeable-tax-rate-cost").change(function () {
        updateTotal("input-changeable-total-tax-exclude-cost", "input-changeable-total-total-tax-exclude-cost");
    });
}

/**
 * 更新页面收入的数据【累加】
 */
function updateCostData(data, returnData) {
    var details = data.details;
    var deviceTaxInclude = 0;
    var deviceTaxExclude = 0;
    var buildTaxInclude = 0;
    var buildTaxExclude = 0;
    var serviceTaxInclude = 0;
    var serviceTaxExclude = 0;
    var otherTaxInclude = 0;
    var otherTaxExclude = 0;
    details.forEach(function (t, number, ts) {
        if(t["type"] == "1"){
            //设备类
            deviceTaxInclude += f2(t["totalTaxInclude"]);
            deviceTaxExclude += f2(t["totalTaxExclude"]);
        }else if(t["type"] == "2"){
            //施工类
            buildTaxInclude += f2(t["totalTaxInclude"]);
            buildTaxExclude += f2(t["totalTaxExclude"]);
        }else if(t["type"] == "3"){
            //服务类
            serviceTaxInclude += f2(t["totalTaxInclude"]);
            serviceTaxExclude += f2(t["totalTaxExclude"]);
        }else if(t["type"] == "4"){
            //其他类
            otherTaxInclude += f2(t["totalTaxInclude"]);
            otherTaxExclude += f2(t["totalTaxExclude"]);
        }
    });
    $("input[name='costPurchaseDeviceTaxInclude']").val(f2Fixed(deviceTaxInclude));
    $("input[name='costPurchaseDeviceTaxExclude']").val(f2Fixed(deviceTaxExclude));
    $("input[name='costPurchaseBuildTaxInclude']").val(f2Fixed(buildTaxInclude));
    $("input[name='costPurchaseBuildTaxExclude']").val(f2Fixed(buildTaxExclude));
    $("input[name='costPurchaseServiceTaxInclude']").val(f2Fixed(serviceTaxInclude));
    $("input[name='costPurchaseServiceTaxExclude']").val(f2Fixed(serviceTaxExclude));
    $("input[name='costPurchaseOtherTaxInclude']").val(f2Fixed(otherTaxInclude));
    $("input[name='costPurchaseOtherTaxExclude']").val(f2Fixed(otherTaxExclude));


    //资金计划表中的
    $(".input-total-title-device-cost-budget-plan").val(f2Fixed(deviceTaxInclude));
    $(".input-total-title-engineer-cost-budget-plan").val(f2Fixed(f2(serviceTaxInclude)+f2(buildTaxInclude)+f2(otherTaxInclude)));
    $(".input-total-title-total-cost-budget-plan").val(f2Fixed(f2(deviceTaxInclude)+f2(buildTaxInclude)+f2(serviceTaxInclude)+f2(otherTaxInclude)
        +f2($(".input-total-title-project-manage-cost-budget-plan").val())
        +f2($(".input-total-title-earnest-money-cost-budget-plan").val())));

/*    var costOtherOtherTaxInclude = f2($("input[name='costOtherOtherTaxInclude']").val());
    var costOtherOtherTaxExclude = f2($("input[name='costOtherOtherTaxExclude']").val());

    var costProjectManageTaxInclude = f2($("input[name='costProjectManageTaxInclude']").val());
    var costProjectManageTaxExclude = f2($("input[name='costProjectManageTaxExclude']").val());

    $("input[name='costTotalTaxInclude']").val(f2(deviceTaxInclude+buildTaxInclude+serviceTaxInclude+otherTaxInclude+costOtherOtherTaxInclude+costProjectManageTaxInclude));
    $("input[name='costTotalTaxExclude']").val(f2(deviceTaxExclude+buildTaxExclude+serviceTaxExclude+otherTaxExclude+costOtherOtherTaxExclude+costProjectManageTaxExclude));*/

    calCostExclude();
    calCostInclude();

    updateProjectContributionProfitRate();

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

function bindOtherOtherChangeable() {
    $("input[name='costOtherOtherTaxInclude']").change(function () {
        /*var costPurchaseDeviceTaxInclude = f2($("input[name='costPurchaseDeviceTaxInclude']").val());
        var costPurchaseBuildTaxInclude = f2($("input[name='costPurchaseBuildTaxInclude']").val());
        var costPurchaseServiceTaxInclude = f2($("input[name='costPurchaseServiceTaxInclude']").val());
        var costPurchaseOtherTaxInclude = f2($("input[name='costPurchaseOtherTaxInclude']").val());

        var costProjectManageTaxInclude = f2($("input[name='costProjectManageTaxInclude']").val());
        var costOtherOther = f2($(this).val());

        $("input[name='costTotalTaxInclude']").val(f2(costPurchaseDeviceTaxInclude+costPurchaseBuildTaxInclude
            +costPurchaseServiceTaxInclude+costPurchaseOtherTaxInclude+costProjectManageTaxInclude+costOtherOther));*/

        calCostInclude();

        updateProjectContributionProfitRate();
        digitalSelf("costOtherOtherTaxInclude", "input[name='costOtherOtherTaxInclude']");
    });

    $("input[name='costOtherOtherTaxExclude']").change(function () {
        /*var costPurchaseDeviceTaxExclude = f2($("input[name='costPurchaseDeviceTaxExclude']").val());
        var costPurchaseBuildTaxExclude = f2($("input[name='costPurchaseBuildTaxExclude']").val());
        var costPurchaseServiceTaxExclude = f2($("input[name='costPurchaseServiceTaxExclude']").val());
        var costPurchaseOtherTaxExclude = f2($("input[name='costPurchaseOtherTaxExclude']").val());

        var costProjectManageTaxExclude = f2($("input[name='costProjectManageTaxExclude']").val());
        var costOtherOther = f2($(this).val());

        $("input[name='costTotalTaxExclude']").val(f2(costPurchaseDeviceTaxExclude+costPurchaseBuildTaxExclude
            +costPurchaseServiceTaxExclude+costPurchaseOtherTaxExclude+costProjectManageTaxExclude+costOtherOther));*/

        calCostExclude();

        updateProjectContributionProfitRate();
        digitalSelf("costOtherOtherTaxExclude", "input[name='costOtherOtherTaxExclude']");
    });
}

/**
 * 大类类别联动效果
 */
function bindTypeSelectChange() {
    //大类变化联动类别
    $(".am-modal-prompt-input-cost-type").on('change',function () {
        var categorySelect = $(this).parent().parent().find(".am-modal-prompt-input-cost-category");
        var type = $(this).val();
        //删除后重新添加对应的类别
        categorySelect.empty();

        //console.log(SELECT_TYPE_CATEGORY_MAP_DATA);

        if(SELECT_TYPE_CATEGORY_MAP_DATA[type]){
            categorySelect.append("<option value='xxxx' disabled selected>--请选择--</option>");
            SELECT_TYPE_CATEGORY_MAP_DATA[type].forEach(function (d) {
                categorySelect.append("<option value='"+d.id+"'>"+d.name+"</option>");
            });
        }

    });
    //类别变化联动大类
    $(".am-modal-prompt-input-cost-category").on('change',function () {
        var typeSelect = $(this).parent().parent().find(".am-modal-prompt-input-cost-type");
        var category = $(this).val();
        //设置他选中类别对应的大类

        //console.log(SELECT_CATEGORY_TYPE_MAP_DATA);

        typeSelect.val(SELECT_CATEGORY_TYPE_MAP_DATA[category]);
    });
}
/**
 * 初始化数据
 * SELECT_TYPE_CATEGORY_MAP_DATA
 * SELECT_CATEGORY_TYPE_MAP_DATA
 * SELECT_TYPE_CATEGORY_DATA
 */
function initTypeCategory(params, data) {
    var d = data.data;
    var map = d.map;

    Object.keys(map).forEach(function (t, number) {
        var temp = [];
        map[t].forEach(function (g) {
            temp.push({
                name:g.name,
                id:g.id+""
            });
        });
        SELECT_TYPE_CATEGORY_MAP_DATA[t]= temp;
    });

    var procurementTypes = d.procurementTypes;
    procurementTypes.forEach(function (e) {
        SELECT_TYPE_CATEGORY_DATA.push({
            id:e.id+"",
            name:e.name
        });
        SELECT_CATEGORY_TYPE_MAP_DATA[e.id]=e.type;
    });
    //--请选择--的映射
    //SELECT_CATEGORY_TYPE_MAP_DATA["xxxx"]="xxxx";

    // console.log(SELECT_TYPE_CATEGORY_MAP_DATA);
    // console.log(SELECT_TYPE_CATEGORY_DATA);
    // console.log(SELECT_CATEGORY_TYPE_MAP_DATA);
}
