/**
 * 编办管理相关js
 *
 * @author CaiAoLin
 * @date 2017/7/28
 * @version
 */

const delayTime = 500;
let keyupTime;
function delayKeyup(callback) {
    let nowTime = Date.now();
    keyupTime = nowTime;
    setTimeout(function () {
        if (nowTime - keyupTime == 0 && callback) {
            callback();
        }
    }, delayTime);
}

$(document).ready(function() {
    let isAdding = false;
    let model = '';
    let section = 'bill';
    let id = $("#compilation-id").val();

    // 计价规则页面初始化数据
    if ($("#save-lib").length > 0) {
        initCompilation();
    }

    // 计价类型选择
    $(".nav-tabs li > a").click(function() {
        section = $(this).attr("aria-controls");
    });

    // 新增编办
    $("#add-compilation").click(function() {
        try {
            let data = getAndValidData(model);
            let url = '/compilation/add'
            if (model === 'all') {
                // 新增编办操作
                $.ajax({
                    url: url,
                    type: 'post',
                    data: {name: data.name},
                    error: function() {
                        isAdding = false;
                    },
                    beforeSend: function() {
                        isAdding = true;
                    },
                    success: function(response) {
                        isAdding = false;
                        if (response.err === 0) {
                            window.location.reload();
                        } else {
                            let msg = response.msg === undefined ? '未知错误' : response.msg;
                            alert(msg);
                        }
                    }
                });
            } else {
                // 新增标准清单/定额库
                let addLib = {
                    name: data[model].name,
                    id: data[model].id
                };
                // 判断是否有重复的数据
                if ($("input:hidden[name='"+ model +"_lib'][data-id='"+ addLib.id +"']").length > 0) {
                    alert('重复添加数据!');
                    return false;
                }

                let removeHtml = '<a class="pull-right text-danger remove-lib" data-model="'+model+'" ' +
                    'title="移除"><span class="glyphicon glyphicon-remove"></span></a>';
                let tmpHtml = '<p class="form-control-static">' + removeHtml + addLib.name +
                    '<input type="hidden" data-id="'+ addLib.id +'" name=\'' + model + '_lib\' value=\'' + JSON.stringify(addLib) + '\'>' + '</p>';
                $("." + model + "-list").append(tmpHtml);
                $('#addcompilation').modal('hide');
            }

        } catch (error) {
            alert(error);
        }
    });

    $("#addTaxGroupBtn").click(function () {
        $('#groupEditType').val("add");
        $("#taxType").val("");
        $("#program_lib").val("");
        $("#template_lib").val("");
        $("#col_lib").val("");
        $("#fee_lib").val("");
    });

    //新增计税组合
    $("#add-group").click(function() {
        let taxMap = {"1":"一般计税","2":"简易计税" };
        let actionType = $('#groupEditType').val();
        let groupData = getTaxGroupData();
        let groupIndex = getGroupIndex(groupData);//用来做重复判断
        if(!_.isEmpty(groupData)){
            //重复判断 todo
            if($("input[data-id = "+groupIndex+"]").length <= 0){
                let taxName = groupData.taxType?taxMap[groupData.taxType]:'';
                let p_name = groupData.program_lib?groupData.program_lib.displayName:"";
                let t_name = groupData.template_lib?groupData.template_lib.name:"";
                let c_name = groupData.col_lib?groupData.col_lib.name:"";
                let f_name = groupData.fee_lib?groupData.fee_lib.name:"";
                let htmlString = "<tr class='taxGroup_tr'><td><span>"+taxName+"</span></td>" +
                    "<td><span>"+p_name+"</span></td>" +
                    "<td><span>"+t_name+"</span></td>" +
                    "<td><span>"+c_name+"</span></td>" +
                    "<td><span>"+f_name+"</span></td>" +
                    "<td> <a class='btn btn-link btn-sm' style='padding: 0px' onclick='editTaxGroup(this)'> 编辑</a>/<a class='btn btn-link btn-sm ' style='padding: 0px' onclick='deleteTableTr(this,\"taxGroup_tr\")'>删除</a> " +
                    "<input type='hidden' name='tax_group' data-id ='"+groupIndex+"' value='"+JSON.stringify(groupData)+"'>"+
                    "</td>" +
                    "</tr>";
                if(actionType == "add"){
                    $("#tax_group_tbody").append(htmlString);
                }else if(actionType == "modify"){
                    let oldIndex = $("#groupIndex").val();
                    let parentTr = $("input[data-id = "+oldIndex+"]").parents(".taxGroup_tr");
                    parentTr.after(htmlString);
                    parentTr.remove();
                }
            }else {
                alert("已存在相同的组合！");
            }
        }
        $("#addTaxGroup").modal('hide');
    });

    //新增定额库
    /* $("#add-ration").click(function () {
        let rationLib = $("select[name='ration_lib']").children("option:selected").val();
        let rationLibString = $("select[name='ration_lib']").children("option:selected").text();
        if (rationLib == undefined || rationLib == '') {
            alert("请选择定额库");
            return;
        }
        if ($("input:hidden[name=ration_lib][data-id = " + rationLib + "]").length <= 0) {
            let tem = {
                id: rationLib,
                name: rationLibString,
                isDefault: false
            };
            let htmlString = ` 
                <tr class='ration_tr' draggable="true">
                    <td><span class="cursor-default">${tem.name}</span></td>
                    <td><label class="form-check-label"> <input class="form-check-input" name="ration_isDefault"  value="${tem.id}" type="radio"></td>  
                    <td>
                        <a class='btn btn-link btn-sm ' style="padding: 0px" onclick='deleteTableTr(this,"ration_tr")'>删除</a>
                        <input type="hidden" name="ration_lib" data-id="${tem.id}" value='${JSON.stringify(tem)}'>
                    </td>
                </tr>`
            $("#ration_tbody").append(htmlString);
        } else {
            alert('已存在相同的定额库')
        }
        $("#addRation").modal('hide');
    }); */
    $("#add-ration").click(function () {
        const options = $("select[name='ration_lib']").children("option:selected");
        let alertArr = [];
        let htmlString = '';
        for (const option of options) {
            const rationLib = $(option).val();
            const rationLibString = $(option).text();
            if (!rationLib) {
                alertString.push(`“${rationLibString}”为无效定额库`);
                continue;
            }
            if ($("input:hidden[name=ration_lib][data-id = " + rationLib + "]").length > 0) {
                alertArr.push(`“${rationLibString}”已存在`);
                continue;
            }
            const tem = {
                id: rationLib,
                name: rationLibString,
                isDefault: false
            };
            htmlString += ` 
                <tr class='ration_tr' draggable="true">
                    <td><span class="cursor-default">${tem.name}</span></td>
                    <td><label class="form-check-label"> <input class="form-check-input" name="ration_isDefault"  value="${tem.id}" type="radio"></td>  
                    <td>
                        <a class='btn btn-link btn-sm ' style="padding: 0px" onclick='deleteTableTr(this,"ration_tr")'>删除</a>
                        <input type="hidden" name="ration_lib" data-id="${tem.id}" value='${JSON.stringify(tem)}'>
                    </td>
                </tr>`;
        }
        if (alertArr.length) {
            alert(alertArr.join('\n'));
        } else {
            $("#ration_tbody").append(htmlString);
            $("#addRation").modal('hide');
        }
    });

    // 复制定额库
    $('#copy-lib-confirm').click(async function () {
        try {
            $.bootstrapLoading.start();
            const [valuationID, engineeringID] = window.location.pathname.split('/').slice(-2);
            await ajaxPost('/compilation/copyRationLibs', { valuationID, engineeringID });
        } catch (err) {
            console.log(err);
        } finally {
            $.bootstrapLoading.end();
        }
    });

    // 拖动排序
    const dragSelector = '.ration_tr[draggable=true]';
    const rationBodySelector = '#ration_tbody';
    const wrapper = $('.panel-content')[0];
    let dragged;
    let rID = null;
    const scrollStep = 6;
    // 表格数据过多的时候，靠下方的条目想要移动到上方，需要滚动条滚动到相应位置，滚动条向上滚动需要代码自行处理
    function scroll(ele, step) {
        wrapper.scrollTop -= step;
        rID = window.requestAnimationFrame(() => {
            scroll(ele, step);
        });
    }
    // 动态绑定(新增的也能监听到)
    $(rationBodySelector).on('drag', dragSelector, function (ev) {
        const { clientX, clientY } = ev;
        const dom = document.elementFromPoint(clientX, clientY);
        if (dom.tagName === 'H2' && !rID) {
            rID = window.requestAnimationFrame(() => {
                scroll(wrapper, scrollStep);
            })
        } else if (dom.tagName !== 'H2' && rID) {
            window.cancelAnimationFrame(rID);
            rID = null;
        }
    });
    $(rationBodySelector).on('dragstart', dragSelector, function (ev) {
        dragged = this;
        $(this).addClass('dragging');
        ev.originalEvent.dataTransfer.effectAllowed = 'move';
    });
    $(rationBodySelector).on('dragend', dragSelector, function (ev) {
        $(this).removeClass('dragging');
        if (rID) {
            window.cancelAnimationFrame(rID);
            rID = null;
        }
    });
    $(rationBodySelector).on('dragover', dragSelector, function (ev) {
        ev.preventDefault(); // 必须调用此方法，否则drop事件不触发
    });
    $(rationBodySelector).on('dragenter', dragSelector, function (ev) {
        if (this !== dragged) {
            $(this).addClass('highlight');
        }
    });
    $(rationBodySelector).on('dragleave', dragSelector, function (ev) {
        if (this !== dragged) {
            $(this).removeClass('highlight');
        }
    });
    $(rationBodySelector).on('drop', dragSelector, function (ev) {
        $(this).removeClass('highlight');
        $(this).after($(dragged));
    });

    // 新增计价规则
    $("#add-valuation").click(function() {
        try {
            if (id === '') {
                throw '页面数据有误';
            }
            let name = $("input[name='valuation_name']").val();
            if (name === '') {
                throw '请填写计价规则名称';
            }

            $.ajax({
                url: '/compilation/add-valuation',
                type: 'post',
                data: {name: name, id: id, section: section},
                error: function() {
                    isAdding = false;
                },
                beforeSend: function() {
                    isAdding = true;
                },
                success: function(response) {
                    isAdding = false;
                    if (response.err === 0) {
                        window.location.reload();
                    } else {
                        let msg = response.msg === undefined ? '未知错误' : response.msg;
                        alert(msg);
                    }
                }
            });
        } catch (error) {
            alert(error);
            return false;
        }
    });

    // 添加
    $(".add-compilation").click(function() {
        model = $(this).data('model');
        $("#addcompilation .modal-body > div").hide();
        switch (model) {
            case 'all':
                $("#name-area").show();
                $("#add-compilation-title").text('添加新费用定额');
                break;
            case 'bill':
                $("#bill-area").show();
                $("#add-compilation-title").text('添加标准清单');
                break;
            case 'ration':
                $("#ration-area").show();
                $("#add-compilation-title").text('添加定额库');
                break;
            case 'glj':
                $("#glj-area").show();
                $("#add-compilation-title").text('添加定额库');
                break;
            case 'billsGuidance':
                $("#billsGuidance-area").show();
                $("#add-compilation-title").text('添加清单指引库');
                break;
            case 'fee':
                $("#fee-area").show();
                $("#add-compilation-title").text('添加费率标准');
                break;
            case 'artificial':
                $("#artificial-area").show();
                $("#add-compilation-title").text('添加人工系数');
                break;
            case 'program':
                $("#program-area").show();
                $("#add-compilation-title").text('添加计算程序');
                break;
            case 'feature':
                $("#feature-area").show();
                $("#add-compilation-title").text('添加工程特征');
                break;
            case 'info':
                $('#info-area').show();
                $('#add-compilation-title').text('添加基本信息');
                break;
            case 'engineer_info':
                $('#engineer-info-area').show();
                $('#add-compilation-title').text('添加工程信息');
                break;
            case 'engineer_feature':
                $('#engineer-feature-area').show();
                $('#add-compilation-title').text('添加工程特征指标');
                break;
            case 'material':
                $('#material-area').show();
                $('#add-compilation-title').text('添加主要工料指标');
                break;
            case 'main_quantity':
                $('#main-quantity-area').show();
                $('#add-compilation-title').text('添加主要工程量指标');
                break;
            case 'economic':
                $('#economic-area').show();
                $('#add-compilation-title').text('添加主要经济指标');
                break;
            case 'over_height':
                $('#over-height-area').show();
                $('#add-compilation-title').text('添加超高降效');
                break;
        }
        $("#addcompilation").modal('show');
    });

    // 保存专业工程标准库
    $("#save-lib").click(function() {
        if (validLib()) {
            $("form").submit();
        }
    });
    // 保存计价规则
    $("#save-valuation").click(function() {
        $("#saveValuation").submit();
    });

    // 移除操作
    /*$(".remove-lib").on("click", function() {
        $(this).parent().remove();
    })*/
    $(".bill-list, .ration-list, .glj-list, .fee-list, .artificial-list, .program-list, .billsGuidance-list,.feature-list,.info-list,.engineer_info-list,.engineer_feature-list,.material-list,.main_quantity-list,.economic-list,.over_height-list").on("click", ".remove-lib", function() {
        $(this).parent().remove();
    });

    //更改描述
    $('#description').change(function () {
        let description = $(this).val();
        $.ajax({
            url: '/compilation/setDescription',
            type: 'post',
            dataType: "json",
            data: {id: id, description: description},
            success: function(response) {
                if (response.err !== 0) {
                    alert('更改失败');
                }
            }
        });
    });

    //更改代码覆盖路径
    $('#overWriteUrl').change(function () {
        let overWriteUrl = $(this).val();
        if(overWriteUrl=="") overWriteUrl = undefined;
        $.ajax({
            url: '/compilation/setOverWriteUrl',
            type: 'post',
            dataType: "json",
            data: {id: id, overWriteUrl: overWriteUrl},
            success: function(response) {
                if (response.err !== 0) {
                    alert('更改失败');
                }
            }
        });
    });

    //例题建设项目ID, 用英文字符;分隔建设项目ID
    $('#example').keyup(function () {
        let exampleVal = $(this).val();
        let tempExample = exampleVal.split(/[;,；]/g),
            example = [];
        for (let te of tempExample) {
            let intTe = parseInt(te);
            if (!isNaN(intTe)) {
                example.push(intTe);
            }
        }
        example = Array.from(new Set(example));
        delayKeyup(function () {
            $.ajax({
                url: '/compilation/setExample',
                type: 'post',
                dataType: "json",
                data: {id: id, example: example},
                success: function(response) {
                    if (response.err !== 0) {
                        alert('更改失败');
                    }
                }
            });
        });
    });

    // 计价规则启用/禁止
    $(".enable").click(function() {
        let goingChangeStatus = switchChange($(this));
        let id = $(this).data('id');
        if (id === undefined || id === '' || isAdding) {
            return false;
        }
        $.ajax({
            url: '/compilation/valuation/' + section + '/enable',
            type: 'post',
            dataType: "json",
            data: {id: id, enable: goingChangeStatus},
            error: function() {
                isAdding = false;
                switchChange($(this));
            },
            beforeSend: function() {
                isAdding = true;
            },
            success: function(response) {
                isAdding = false;
                if (response.err !== 0) {
                    switchChange($(this));
                    alert('更改失败');
                }
            }
        });
    });

    //计价规则删除
    $('#delete-confirm').click(function () {
        let id = $('#del').attr('selectedId');
        if (id === undefined || id === '') {
            return false;
        }
        window.location.href = `/compilation/valuation/bill/delete/${id}`;
    });

    // 发布编办
    $("#release").click(function() {
        let id = $(this).data("id");
        let status = $(this).data("status");
        status = parseInt(status);
        if (isAdding || id === '' || isNaN(status)) {
            return false;
        }

        $.ajax({
            url: '/compilation/release',
            type: 'post',
            data: {id: id, status: status},
            dataType: "json",
            error: function() {
                isAdding = false;
            },
            beforeSend: function() {
                isAdding = true;
            },
            success: function(response) {
                isAdding = false;
                if (response.err === 0) {
                    window.location.reload();
                } else {
                    let msg = response.msg === undefined ? "未知错误" : response.msg;
                    alert(msg);
                }
            }
        });

    });

    //添加工程专业
    $("#addEngineerConfirm").click(async function() {
        if($('#name').val() == ''){
            $("#nameError").show();
            return;
        }
        if($('#feeName').val() == ''){
            $("#feeNameError").show();
            return;
        }
        if($('#engineeringInput').val() == ''){
            $("#engineeringError").show();
            return;
        }
        if($('#projectEngineering').val() == ''){
            $("#projectError").show();
            return;
        }
        $("#addEngineerConfirm").attr("disabled",true);//防止重复提交
        $("#addEngineerForm").submit();
    });
    //

    // CLD 办事处选择
    $('#category-select').change(function () {
        $.ajax({
            url: '/compilation/changeCategory',
            type: 'post',
            data: {id: id, category: $(this).val()},
            dataType: "json",
            success: function(response) {
                if (response.error !== 0) {
                    alert('更改失败');
                }
            }
        });
    })

});

/**
 * 初始化
 *
 * @return {void|boolean}
 */
function initCompilation() {
    let billListData = billList === undefined ? [] : JSON.parse(billList);
    let rationLibData = rationList === undefined ? [] : JSON.parse(rationList);
    let gljLibData = gljList === undefined ? [] : JSON.parse(gljList);
    let feeLibData = feeRateList === undefined ? [] : JSON.parse(feeRateList);
    let artificialCoefficientData = artificialCoefficientList === undefined ? [] : JSON.parse(artificialCoefficientList);
    let programData = programList === undefined ? [] : JSON.parse(programList);
    let billsGuidanceData = billsGuidanceList === undefined ? [] : JSON.parse(billsGuidanceList);
    let billTemplateData = billTemplateList == undefined ? [] : JSON.parse(billTemplateList);
    let mainTreeColData= mainTreeColList == undefined ? [] : JSON.parse(mainTreeColList);
    let featureData = featureList == undefined?[]: JSON.parse(featureList);
    let infoData = infoList == undefined ? [] : JSON.parse(infoList);
    let engineerInfoData = engineerInfoList == undefined ? [] : JSON.parse(engineerInfoList);
    let engineerFeatureData = engineerFeatureList == undefined ? [] : JSON.parse(engineerFeatureList);
    let materialData = materialList == undefined ? [] : JSON.parse(materialList);
    let mainQuantityData = mainQuantityList == undefined ? [] : JSON.parse(mainQuantityList);
    let economicData = economicList == undefined ? [] : JSON.parse(economicList);
    let overHeightData = overHeightList == undefined ? [] : JSON.parse(overHeightList);

    /*mainTreeCol = mainTreeCol !== '' ? mainTreeCol.replace(/\n/g, '\\n') : mainTreeCol;
    billsTemplateData = billsTemplateData.replace(/\n/g, '\\n');

    let mainTreeColObj = mainTreeCol === '' ? {} : JSON.parse(mainTreeCol);

    // 初始化 造价书列设置
    colSpread = TREE_SHEET_HELPER.createNewSpread($('#main-tree-col')[0]);
    let billsTemplateTree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1});

    billsTemplateTree.loadDatas(JSON.parse(billsTemplateData));
    if (mainTreeCol !== '' && mainTreeColObj.cols.length > 0) {
        TREE_SHEET_HELPER.loadSheetHeader(mainTreeColObj, colSpread.getActiveSheet());
        TREE_SHEET_HELPER.showTreeData(mainTreeColObj, colSpread.getActiveSheet(), billsTemplateTree);
    }*/

    /* if (billListData.length <= 0 || rationLibData.length <= 0 || gljLibData.length <= 0) {
        return false;
    } */

    // 标准清单
    let html = '';
    for(let tmp of billListData) {
        let tmpHtml = '<option value="' + tmp.id + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='standard_bill']").children("option").first().after(html);

    // 定额库
    html = '';
    for(let tmp of rationLibData) {
        let tmpHtml = '<option value="' + tmp.id + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='ration_lib']").html(html);

    // 工料机库
    html = '';
    for(let tmp of gljLibData) {
        let tmpHtml = '<option value="' + tmp.id + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='glj_lib']").children("option").first().after(html);

    // 清单指引库
    html = '';
    for(let tmp of billsGuidanceData) {
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='billsGuidance_lib']").children("option").first().after(html);


    // 人工系数标准库
    html = '';
    for(let tmp of artificialCoefficientData) {
        let tmpHtml = '<option value="' + tmp.id + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='artificial_lib']").children("option").first().after(html);

    // 计算程序标准库
    html = '';
    for(let tmp of programData) {
        let tmpHtml = '<option value="' + tmp.id + '">' + tmp.displayName + '</option>';
        html += tmpHtml;
    }
    $("select[name='program_lib']").children("option").first().after(html);

    //模板库
    html = '';
    for(let tmp of billTemplateData) {
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='template_lib']").children("option").first().after(html);
    //列设置
    html = '';
    for(let tmp of mainTreeColData) {
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='col_lib']").children("option").first().after(html);

    // 费率标准库
    html = '';
    for(let tmp of feeLibData) {
        let tmpHtml = '<option value="' + tmp.id + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='fee_lib']").children("option").first().after(html);

    //工程特征库
    html = '';
    for(let tmp of featureData){
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='feature_lib']").children("option").first().after(html);

    //基本信息库
    html = '';
    for(let tmp of infoData){
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='info_lib']").children("option").first().after(html);
    //工程信息库
    html = '';
    for(let tmp of engineerInfoData){
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='engineer_info_lib']").children("option").first().after(html);
    //工程特征指标库
    html = '';
    for(let tmp of engineerFeatureData){
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='engineer_feature_lib']").children("option").first().after(html);

    //主要工料指标库
    html = '';
    for(let tmp of materialData){
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='material_lib']").children("option").first().after(html);

    //主要工程量指标库
    html = '';
    for(let tmp of mainQuantityData){
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='main_quantity_lib']").children("option").first().after(html);

    //主要经济指标库
    html = '';
    for(let tmp of economicData){
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='economic_lib']").children("option").first().after(html);

    //超高降效
    html = '';
    for(let tmp of overHeightData){
        let tmpHtml = '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
        html += tmpHtml;
    }
    $("select[name='over_height_lib']").children("option").first().after(html);
}

/**
 * 校验数据
 *
 * @param {String} model
 * @return {Object}
 */
function getAndValidData(model) {
    let name = $("input[name='compilation_name']").val();
    let standardBill = $("select[name='standard_bill']").children("option:selected").val();
    let rationLib = $("select[name='ration_lib']").children("option:selected").val();
    let gljLib = $("select[name='glj_lib']").children("option:selected").val();
   // let feeLib = $("select[name='fee_lib']").children("option:selected").val();
    let artificialLib = $("select[name='artificial_lib']").children("option:selected").val();
    let programLib = $("select[name='program_lib']").children("option:selected").val();
    let billsGuidanceLib = $("select[name='billsGuidance_lib']").children("option:selected").val();
    let featureLib = $("select[name='feature_lib']").children("option:selected").val();
    let infoLib = $("select[name='info_lib']").children("option:selected").val();
    let engineerInfoLib = $("select[name='engineer_info_lib']").children("option:selected").val();
    let engineerFeatureLib = $("select[name='engineer_feature_lib']").children("option:selected").val();
    let materialLib = $("select[name='material_lib']").children("option:selected").val();
    let mainQuantityLib = $("select[name='main_quantity_lib']").children("option:selected").val();
    let economicLib = $("select[name='economic_lib']").children("option:selected").val();
    let overHeightLib = $("select[name='over_height_lib']").children("option:selected").val();

    if (name === '' && model === 'all') {
        throw '编办名字不能为空';
    }

    if ( model === 'bill' && (standardBill === '' || standardBill === undefined)) {
        throw '请选择标准清单库';
    }

    if (model === 'ration' && (rationLib === '' || rationLib === undefined)) {
        throw '请选择定额库';
    }
    if (model === 'feature' && (featureLib === '' || featureLib === undefined)) {
        throw '请选择工程特征库';
    }

    if (model === 'glj' && (gljLib === '' || gljLib === undefined)) {
        throw '请选择人材机库';
    }

    if (model === 'artificial' && (artificialLib === '' || artificialLib === undefined)) {
        throw '请选择人工系数库';
    }

    if (model === 'program' && (programLib === '' || programLib === undefined)) {
        throw '请选择计算程序';
    }

    if (model === 'billsGuidance' && (billsGuidanceLib === '' || billsGuidanceLib === undefined)) {
        throw '请选择清单指引库';
    }

    let standardBillString = $("select[name='standard_bill']").children("option:selected").text();
    let rationLibString = $("select[name='ration_lib']").children("option:selected").text();
    let gljLibString = $("select[name='glj_lib']").children("option:selected").text();
  //  let feeLibString = $("select[name='fee_lib']").children("option:selected").text();
    let artificialString = $("select[name='artificial_lib']").children("option:selected").text();
    let programString = $("select[name='program_lib']").children("option:selected").text();
    let billsGuidanceString = $("select[name='billsGuidance_lib']").children("option:selected").text();
    let featrueString = $("select[name='feature_lib']").children("option:selected").text();
    let infoString = $("select[name='info_lib']").children("option:selected").text();
    let engineerInfoString = $("select[name='engineer_info_lib']").children("option:selected").text();
    let engineerFeatureString = $("select[name='engineer_feature_lib']").children("option:selected").text();
    let materialString = $("select[name='material_lib']").children("option:selected").text();
    let mainQuantityString = $("select[name='main_quantity_lib']").children("option:selected").text();
    let economicString = $("select[name='economic_lib']").children("option:selected").text();
    let overHeightString = $("select[name='over_height_lib']").children("option:selected").text();


    let result = {
        name: name,
        bill: {
            id: standardBill,
            name: standardBillString
        },
        ration: {
            id: rationLib,
            name: rationLibString
        },
        glj: {
            id: gljLib,
            name: gljLibString
        },
      /*  fee: {
            id: feeLib,
            name: feeLibString
        },*/
        artificial: {
            id: artificialLib,
            name: artificialString
        },
        program: {
            id: programLib,
            name: programString
        },
        billsGuidance: {
            id: billsGuidanceLib,
            name: billsGuidanceString
        },
        feature:{
            id:featureLib,
            name:featrueString
        },
        info: {
            id: infoLib,
            name: infoString
        },
        engineer_info:{
            id:engineerInfoLib,
            name:engineerInfoString
        },
        engineer_feature:{
            id:engineerFeatureLib,
            name:engineerFeatureString
        },
        material:{
            id:materialLib,
            name:materialString
        },
        main_quantity:{
            id:mainQuantityLib,
            name:mainQuantityString
        },
        economic:{
            id:economicLib,
            name:economicString
        },
        over_height:{
            id:overHeightLib,
            name:overHeightString
        }
    };
    return result;
}

/**
 * 验证标准库数据
 *
 * @return {boolean}
 */
function validLib() {
    let result = false;
    try {
        let valuationName = $("input[name='name']").val();
        if (valuationName === '') {
            throw '请填写计价规则名称';
        }

        let engineering = $("select[name='engineering']").val();
        if (engineering === '' || engineering <= 0) {
            throw '请选择工程专业';
        }
        //按新需求，清单库、定额库等不做非空验证
      /*  if ($("input:hidden[name='bill_lib']").length <= 0) {
            throw '请添加标准清单';
        }

        if ($("input:hidden[name='ration_lib']").length <= 0) {
            throw '请添加定额库';
        }

        if ($("input:hidden[name='glj_lib']").length <= 0) {
            throw '请添加人材机库';
        }

        if ($("input:hidden[name='fee_lib']").length <= 0) {
            throw '请添加费率标准';
        }

        if ($("input:hidden[name='artificial_lib']").length <= 0) {
            throw '请添加人工系数';
        }

        if ($("input:hidden[name='program_lib']").length <= 0) {
            throw '请添加计算程序';
        }

        if ($("input:hidden[name='billsGuidance_lib']").length <= 0) {
            throw '请添加清单指引库';
        }*/

        result = true;
    } catch (error) {
        alert(error);
        result = false;
    }

    return result;
}

/**
 * 切换switch效果
 *
 * @param {Object} element
 * @return {boolean}
 */
function switchChange(element) {
    // 第一个元素判断当前的状态
    let firstButton = element.children("button").first();
    let secondButton = element.children("button").eq(1);
    let currentStatus = firstButton.is(":disabled");
    if (currentStatus) {
        // 当前为true切换到false
        firstButton.removeClass('btn-success').removeClass('disabled').addClass('btn-default').removeAttr("disabled");
        firstButton.text('开启');
        secondButton.removeClass("btn-default").addClass("btn-danger").addClass("disabled").attr("disabled", "disabled");
        secondButton.text('已禁用');
    } else {
        // 当前false切换到true
        firstButton.removeClass("btn-default").addClass("btn-success").addClass("disabled").attr("disabled", "disabled");
        firstButton.text('已开启');
        secondButton.removeClass('btn-danger').removeClass('disabled').addClass('btn-default').removeAttr("disabled");
        secondButton.text('禁用');
    }

    return !currentStatus;
}

function editEngineer(selector,key) {
    let editText =  $(selector).prev("span").text();
    let parentDiv = $(selector).parent("div");
    let width =  key == 'seq'?70:200;
    parentDiv.next("div").css('width',width);
    parentDiv.next("div").find("input").val(editText);
    parentDiv.hide();
    parentDiv.next("div").show();
}

function confirmUpdate(selector,engineerID) {
    let inputDiv = $(selector).parents(".input_group_div");
    let input = $(selector).parent(".input-group-btn").prev("input");
    let oldValue = inputDiv.prev("div").find("span").text();
    let newValue = input.val();
    let key = input.attr("name");
    if(newValue==oldValue || !engineerID){//不做非空判断
        inputDiv.prev("div").show();
        inputDiv.hide();
        return;
    }
     let updateData = {};
     updateData[key] = newValue;
     updateEngineer(engineerID,updateData,function () {
         if(key == 'seq'){
             window.location.reload();
         } else {
             inputDiv.prev("div").find("span").text(newValue);
         }
     });
     inputDiv.prev("div").show();
     inputDiv.hide();
}

function deleteEngineerClick(engineerID,element) {
    hintBox.infoBox('操作确认', '是否删除所选工程专业？', 2, async function () {
        try {
            let result  = await ajaxPost('/compilation/delete-engineer',{id:engineerID});
            $(element).parent("td").parent("tr").remove();
        }catch (err){
            console.log(err);
        }
    }, null,['确定','取消'],false);
}


function engineerVisibleChange(checkBox,engineerID) {
    if(engineerID){
        updateEngineer(engineerID,{visible:checkBox.checked});
    }
}

function updateEngineer(engineerID,data,callback) {
    CommonAjax.post('/compilation/update-engineer',{id:engineerID,updateData:data},function (data) {
        if(callback){
            callback();
        }
    })
}

function editTaxGroup(ele) {
    $('#groupEditType').val("modify");
    let groupData = $(ele).nextAll("input[name = 'tax_group']").val();
    groupData = JSON.parse(groupData);
    if(!_.isEmpty(groupData)){
        $("#taxType").val(groupData.taxType?groupData.taxType:"");
        $("#program_lib").val(groupData.program_lib?groupData.program_lib.id:"");
        $("#template_lib").val(groupData.template_lib?groupData.template_lib.id:"");
        $("#col_lib").val(groupData.col_lib?groupData.col_lib.id:"");
        $("#fee_lib").val(groupData.fee_lib?groupData.fee_lib.id:"");
    }else {
        $("#taxType").val("");
        $("#program_lib").val("");
        $("#template_lib").val("");
        $("#col_lib").val("");
        $("#fee_lib").val("");
    }
    $("#groupIndex").val(getGroupIndex(groupData));
    $("#addTaxGroup").modal({show:true});
}

function deleteTableTr(ele,classString) {
    let parentTr = $(ele).parents(`.${classString}`);
    parentTr.remove();
}

function getGroupIndex(groupData) {//用来做唯一标识
    let index = "";
    if(groupData){
        if(groupData.taxType) index = index + groupData.taxType;
        if(groupData.program_lib) index = index + groupData.program_lib.id;
        if(groupData.template_lib) index = index + groupData.template_lib.id;
        if(groupData.col_lib) index = index + groupData.col_lib.id;
        if(groupData.fee_lib) index = index + groupData.fee_lib.id;
    }
    return index;
}
function getTaxGroupData() {
    let programData = programList === undefined ? [] : _.indexBy(JSON.parse(programList), 'id');
    let billTemplateData = billTemplateList == undefined ? [] : _.indexBy(JSON.parse(billTemplateList),'ID');
    let mainTreeColData= mainTreeColList == undefined ? [] :  _.indexBy(JSON.parse(mainTreeColList),'ID');
    let feeLibData = feeRateList === undefined ? [] : _.indexBy(JSON.parse(feeRateList),'id');
    let groupData = {};
    if($("#taxType").val() !==""){
        groupData.taxType = $("#taxType").val();
    }
    if($("#program_lib").val() !==""){
        let program =  programData[$("#program_lib").val()];
        if(program){
            groupData.program_lib = {
                id:program.id,
                name:program.name,
                displayName:program.displayName
            }
        }
    }
    if($("#template_lib").val() !==""){
        let template =  billTemplateData[$("#template_lib").val()];
        if(template){
            groupData.template_lib = {
                id:template.ID,
                name:template.name
            }
        }
    }
    if($("#col_lib").val() !==""){
        let col =  mainTreeColData[$("#col_lib").val()];
        if(col){
            groupData.col_lib = {
                id:col.ID,
                name:col.name
            }
        }
    }
    if($("#fee_lib").val() !==""){
        let feeRate =  feeLibData[$("#fee_lib").val()];
        if(feeRate){
            groupData.fee_lib = {
                id:feeRate.id,
                name:feeRate.name
            }
        }
    }
    return groupData;
}


function intChecking(e,elemt) {//限制输入正整数
    let code = e.which || e.keyCode;
    if(code == 46 || code == 45){//不能输入小数点和-号
        e.preventDefault();
    }
    if( elemt.value == ""&&code == 48){//当输入框为空时不能输入0
        e.preventDefault();
    }

}
