/**
 * Created by CSL on 2017-07-04.
 */
//modified by zhong on 2017-08-30
// Tab panes 下有多个Spread时，相互之间不能正确显示。改成一个Spread下多个Sheet。
//特征及内容spread，解决不能正确显示spread

//zhang 5-31  删除附注条件、辅助定额tab,增加子目换算tab

let subSpread = null;
let subObj = {
    fisrtLinked: true,  //提升焦点变换性能 2019年4月12日
    TZJNRrePercent:null,
    showGljSubTab:false,
    showQDSubTab:false,
    firstOpen:true,
    initSubSpread:function () {
        //清单子界面
        BillsSub.buildSheets();
        contentOprObj.buildSheet($("#jobSpread")[0]);
        //sheetCommonObj.bindEscKey(contentOprObj.workBook, [{sheet: contentOprObj.workBook.getSheet(0), editStarting: contentOprObj.onEditStart, editEnded: contentOprObj.onEditEnded}]);
        sheetCommonObj.spreadDefaultStyle(contentOprObj.workBook);
        characterOprObj.buildSheet($("#itemSpread")[0]);
        //sheetCommonObj.bindEscKey(characterOprObj.workBook, [{sheet: characterOprObj.workBook.getSheet(0), editStarting: characterOprObj.onEditStart, editEnded: characterOprObj.onEditEnded}]);
        sheetCommonObj.spreadDefaultStyle(characterOprObj.workBook);
        $("#tzjnrCon").hide();
        $("#subSpread").show();
        subSpread = sheetCommonObj.createSpread($("#subSpread")[0], 4);
        sheetCommonObj.spreadDefaultStyle(subSpread);
        subSpread.options.allowUserDragDrop = false;
        subSpread.options.allowUserDragFill = false;
        subSpread.getSheet(2).name('JSCX');

        pageCCOprObj.active = false;

        // 工料机
        gljOprObj.initSheet(subSpread.getSheet(0));
        //sheetCommonObj.shieldAllCells(subSpread.getSheet(0), gljOprObj.setting);
        SheetDataHelper.protectdSheet(subSpread.getSheet(0));
        // assistOprObj.initSheet(subSpread.getSheet(1));
        // sheetCommonObj.shieldAllCells(subSpread.getSheet(1), assistOprObj.setting);

        if(!projectReadOnly){
            gljContextMenu.loadGLJSpreadContextMenu();
        }

        //工程量明细
        gljOprObj.initDetailSheet(subSpread.getSheet(1));
        SheetDataHelper.protectdSheet(subSpread.getSheet(1));

        //安装增加费
        installationFeeObj.initRationInstallSheet(subSpread.getSheet(3));
        SheetDataHelper.protectdSheet(subSpread.getSheet(3));

        //绑定esc
        let subEscSheets = [];
        subEscSheets.push({sheet: subSpread.getSheet(0), editStarting: gljOprObj.editChecking, editEnded: gljOprObj.onEditEnded});//定额工料机
        subEscSheets.push({sheet: subSpread.getSheet(1), editStarting: gljOprObj.editChecking, editEnded: gljOprObj.onEditEnded});//工程量明细
        subEscSheets.push({sheet: subSpread.getSheet(3), editStarting: installationFeeObj.rationInstSheeteditChecking, editEnded: null});//定额安装增加费
        sheetCommonObj.bindEscKey(subSpread, subEscSheets);

        if(projectReadOnly){
            sheetCommonObj.disableSpread(subSpread);
            sheetCommonObj.disableSpread(contentOprObj.workBook);
            sheetCommonObj.disableSpread(characterOprObj.workBook);
        }
    },
    initNavItem:function (node) {
     /*   1、造价书选中行类别是“大项费用”、“分部”、“分项”、“清单”时，显示按钮“工程量明细”、“计算程序”、“特征及内容”，默认打开“计算程序”。
          2、选中行类别是“定额”、“量价”、“人材机”时，显示按钮“人材机”、“子目换算”、“工程量明细”、“计算程序”、“安装增加费”、"模板子目"，默认打开“人材机”。
     */
        if (!node) {
            return;
        }
        $('.sub-item').removeClass('active');
        if(node.sourceType == ModuleNames.ration){
            //GLJ_div //ZMHS_div
            $("#GLJ_div").show();
            $("#ZMHS_div").show();
            $("#MBZM_div").show();
            installationFeeObj.engineeringTypeChecking();//检查是否安装工程
            $("#TZJNR_div").hide();
            BillsSub.toggleDiv('hide');
            $("#linkGLJ").addClass();
            $(gljOprObj.rationTab).click();
        }else {
            $("#GLJ_div").hide();
            $("#ZMHS_div").hide();
            $("#MBZM_div").hide();
            $("#AZZJF_div").hide();
            $("#TZJNR_div").show();
            BillsSub.toggleDiv('show');
            $(gljOprObj.billsTab).click();
        }
        projectObj.mainSpread.focus();
    },
    //初始化人材机和项目特征文本两个区域的宽度,改变窗口大小时调用此方法，实时刷新
    initItemWidth:function (){
        //总宽度
        let totalWidth = $('#subItems').width();
        //人材机和项目特征文本比例
        const openWidth = 30;//打开项目特征工具条
        const tab_tem = (305+openWidth+10)/totalWidth;//tab显示框默认宽度:305(表格宽度) + 30（工具条宽度）+10(resize div 宽度)
        let textVisible = $('#replaceText').is(':visible'),
            //默认比例
            textPercent = tab_tem * 100 + '%',//'15%',
            rcjPercent = (1 - tab_tem)* 100 + '%';//85
        //文本没显示，则打开工具条固定30px转换百分比
        if (!subObj.showGljSubTab) {
            textPercent = openWidth / totalWidth;
            rcjPercent = 1 - textPercent;
            textPercent = textPercent * 100 + '%';
            rcjPercent = rcjPercent * 100 + '%';
        }
        //设置特征及内容与排版规则的比例
        $('#subSpread').css('width', rcjPercent);
        $('#itemTextDiv').css('width', textPercent);
        //打开了项目特征，则继续加载人材机表和项目特征文本具体比例
        if (subObj.showGljSubTab === true) {
            let rg_sideResizeEles = MaterialController.getSideResize();
            SlideResize.loadHorizonWidth(rg_sideResizeEles.eleObj.module,
                [rg_sideResizeEles.eleObj.resize], [rg_sideResizeEles.eleObj.left, rg_sideResizeEles.eleObj.right]);
            $("#gljSubDiv").width( $('#itemTextDiv').width() - rg_sideResizeEles.eleObj.resize.width() - 30)
        }
    },
    initGljSubTab:function() {
        if(!($('#linkGLJ').hasClass('active'))){
            return;
        }
        if(this.showGljSubTab == true){
            $("#gljSubDiv").show();
            $("#rgResize").show();
        } else {
            $("#gljSubDiv").hide();
            $("#rgResize").hide();
        }
        $("#subSpread").addClass("ration_glj_spread");
        this.initItemWidth();
    },
    //初始化清单精灵和项目特征文本两个区域的宽度,改变窗口大小时调用此方法，实时刷新
    initTZItemWidth:function (){
        let tabID = "";
        if($('#qdzy').is(':visible')) tabID = "qdzy";
        if($('#qdjl').is(':visible')) tabID = "qdjl";
        if($('#tzjnrCon').is(':visible')) tabID = "tznr";
        if(tabID == "") return;
        //总宽度
        let totalWidth = $('#subItems').width();
        //人材机和项目特征文本比例
        const openWidth = 30;//打开项目特征工具条
        if (tabID === 'tznr') {
            if (this.showQDSubTab) {
                $('#tzjnrCon').css('width', '66%');
                $('#xmtzTextDiv').css('width', '34%');
                $('#tzSubDiv').css('width', 'calc(100% - 38px)');
            } else {
                const tznrWidthRate = (totalWidth - openWidth) / totalWidth;
                $('#xmtzTextDiv').css('width', '');
                $('#tzjnrCon').css('width', `${tznrWidthRate * 100}%`);
            }
            return;
        }
        const tab_tem = (305+openWidth+10)/totalWidth;//tab显示框默认宽度:305(表格宽度) + 30（工具条宽度）+10(resize div 宽度)
        //默认比例
        let textPercent = tab_tem * 100 + '%',//'15%',
            rcjPercent = (1 - tab_tem)* 100 + '%';//85
        //文本没显示，则打开工具条固定30px转换百分比
        if (!subObj.showQDSubTab) {
            textPercent = openWidth / totalWidth;
            rcjPercent = 1 - textPercent;
            textPercent = textPercent * 100 + '%';
            rcjPercent = rcjPercent * 100 + '%';
        }
        //设置特征及内容与排版规则的比例
        $('#'+tabID).css('width', rcjPercent);
        $('#xmtzTextDiv').css('width', textPercent);
        //打开了项目特征，则继续加载人材机表和项目特征文本具体比例
        if (subObj.showQDSubTab === true) {
            let jl_sideResizeEles = this.getJLSideResize(tabID);
            SlideResize.loadHorizonWidth(jl_sideResizeEles.eleObj.module,
                [jl_sideResizeEles.eleObj.resize], [jl_sideResizeEles.eleObj.left, jl_sideResizeEles.eleObj.right]);
            $("#tzSubDiv").width( $('#xmtzTextDiv').width() - jl_sideResizeEles.eleObj.resize.width() - 30)
        }
    },
    getJLSideResize:function (tabID) {
        let jl_sideResizeEles = {};
        jl_sideResizeEles.eleObj = {
            module: tabID,
            resize: $('#tzrgResize'),
            parent: $('#subItems'),
            left: $('#'+tabID),
            right: $('#tzSubDiv')
        };
        rg_sideResizeEles.limit = {
            min: 100,
            max: `$('#subItems').width()-100`
        };
        return jl_sideResizeEles;
    },
    initQDSubTab:function () {
      if(!($('#linkQDJL').hasClass('active') || $('#linkQDZY').hasClass('active') || $('#linkTZJNR').hasClass('active')))   return;
      if(this.showQDSubTab == true){
          $("#tzSubDiv").show();
          $("#tzrgResize").show();
      } else {
          $("#tzSubDiv").hide();
          $("#tzrgResize").hide();
      }
        this.initTZItemWidth();
    },
    showGljSubTabData:function () {
        this.initGljSubTab();
        zmhs_obj.showDatas();
        if (gljOprObj.activeTab !== gljOprObj.preActiveTab) {   //提高焦点变换性能 2019年4月12日
            refreshSubSpread();
        }
        if(this.firstOpen == true){
            $("#zmhs_toogle").click();
            this.firstOpen = false;
        }
    },
    showQDSubTabData:function () {
        this.initQDSubTab();
        MaterialController.showItemCharacterText(null,"#tzCharacterText");
        if (gljOprObj.activeTab !== gljOprObj.preActiveTab) {   //提供焦点变换性能 2019年4月12日
            refreshSubSpread();
        }
    }
};

$("#linkGLJ").click(function(){
    $("#subItems").children().hide();//控制显示subSpread,隐藏特征及内容spread
    //show
    //MaterialController.showReplaceDiv();
    //subObj.showGljSubTabData();   //提高焦点变换性能 2019年4月12日
    $("#subSpread").show();
    $("#itemTextDiv").show();
    $("#gljItemTab").show();
    pageCCOprObj.active = false;
    subSpread.options.allowUserDragFill = false;
    //refreshSubSpread();   //提高焦点变换性能 2019年4月12日
    subSpread.setActiveSheetIndex(0);
    //提高焦点变换性能 2019年4月12日--
    if (!subObj.fisrtLinked) {
        gljOprObj.preActiveTab = gljOprObj.activeTab;
    }
    subObj.fisrtLinked = false;
    //--
    gljOprObj.activeTab='#linkGLJ';
    gljOprObj.setNodeShowTab();
});


$("#linkAZZJF").click(function(){
    $("#subItems").children().hide();
    MaterialController.hideReplaceDiv();
    $("#subSpread").show();
    pageCCOprObj.active = false;
    subSpread.setActiveSheetIndex(3);
    gljOprObj.preActiveTab = gljOprObj.activeTab;   //提高焦点变换性能 2019年4月12日
    gljOprObj.activeTab='#linkAZZJF';
    if (gljOprObj.preActiveTab !== gljOprObj.activeTab) { //提高焦点变换性能 2019年4月12日
        refreshSubSpread();
    }
    gljOprObj.setNodeShowTab();
});

$("#linkGCLMX").click(function(){
    $("#subItems").children().hide();
    MaterialController.hideReplaceDiv();
    $("#subSpread").show();
    subSpread.options.allowUserDragFill = true;
    pageCCOprObj.active = false;
    //refreshSubSpread(); //提升焦点变换性能 2019年4月12日
    subSpread.setActiveSheetIndex(1);
    gljOprObj.preActiveTab = gljOprObj.activeTab;   //提高焦点变换性能 2019年4月12日
    gljOprObj.activeTab='#linkGCLMX';
    gljOprObj.setNodeShowTab();
});

$("#linkJSCX").click(function(){        // 计算程序
    $("#subItems").children().hide();
    MaterialController.hideReplaceDiv();
    $("#subSpread").show();
    pageCCOprObj.active = false;
    //refreshSubSpread();   //提升焦点变换性能 2019年4月12日
    subSpread.setActiveSheetIndex(2);
    calcProgramObj.initSheet(subSpread.getSheet(2));

    if (!projectObj.mainController.tree.selected)
        projectObj.mainController.tree.selected = projectObj.mainController.tree.firstNode();
    let sel = projectObj.mainController.tree.selected;
    calcProgramObj.refreshCalcProgram(sel, 3);
    gljOprObj.preActiveTab = gljOprObj.activeTab;   //提高焦点变换性能 2019年4月12日
    gljOprObj.activeTab='#linkJSCX';
    gljOprObj.setNodeShowTab();
});



$("#linkZMHS").click(function(){        // 子目换算
    $("#subItems").children().hide();
    $("#tabZMHS").show();
    zmhs_obj.loadSideResize();
    pageCCOprObj.active = false;
    refreshSubSpread();
    gljOprObj.preActiveTab = gljOprObj.activeTab;   //提高焦点变换性能 2019年4月12日
    gljOprObj.activeTab='#linkZMHS';
    gljOprObj.setNodeShowTab();
});
$("#linkMBZM").click(function(){        // 模板子目
    $("#subItems").children().hide();
    $("#tabMBZM").show();
    pageCCOprObj.active = false;
    gljOprObj.preActiveTab = gljOprObj.activeTab;   //提高焦点变换性能 2019年4月12日
    gljOprObj.activeTab='#linkMBZM';
    if (gljOprObj.activeTab !== gljOprObj.preActiveTab) {   //提高焦点变换性能 2019年4月12日
        refreshSubSpread();
    }
    gljOprObj.setNodeShowTab();
});

//特征及内容、工作内容与项目特征左右拖动
let TZJNR_sideResizeEles = {};
TZJNR_sideResizeEles.eleObj = {
    module: 'tzjnr',
    resize: $('#TZJNRResize'),
    parent: $('#contentDiv'),
    left: $('#jobDiv'),
    right: $('#itemDiv')
};
TZJNR_sideResizeEles.limit = {
    min: 100,
    max: `$('#contentDiv').width()-100`
};
SlideResize.horizontalSlide(TZJNR_sideResizeEles.eleObj, TZJNR_sideResizeEles.limit, function () {
    pageCCOprObj.resizeWidth();
    refreshSubSpread();
});

//刷新特征内容与添加规则宽度
function initTznrWidth(){
    //特征及内容总宽度
    let totalWidth = $('#tzjnrCon').width();
    //特征及内容和排版规则比例
    const typeSettingWidth = 30;//排版规则工具条
    let addRuleVisible = $('#add-rule').is(':visible'),
        addRulePercent = '33.3%',
        contentPercent = '66.7%';
    //排版规则没显示，则排版规则工具条固定30px转换百分比
    if (!addRuleVisible) {
        addRulePercent = typeSettingWidth / totalWidth;
        contentPercent = 1 - addRulePercent;
        addRulePercent = addRulePercent * 100 + '%';
        contentPercent = contentPercent * 100 + '%';
    }
    //设置特征及内容与排版规则的比例
    // $('#contentDiv').css('width', contentPercent);
    $('#contentDiv').css('width', '100%');
    $('#ruleDiv').css('width', addRulePercent);
}

//特征及内容各模块宽度自适应
function adaptiveTzjnrWidth() {
    if(gljOprObj.activeTab !== '#linkTZJNR'){
        return;
    }
    initTznrWidth();
    //加载特征及内容里，工作内容和项目特征的比例
    SlideResize.loadHorizonWidth(TZJNR_sideResizeEles.eleObj.module, [TZJNR_sideResizeEles.eleObj.resize],
        [TZJNR_sideResizeEles.eleObj.left, TZJNR_sideResizeEles.eleObj.right]);
    pageCCOprObj.resizeWidth();
    refreshSubSpread();
}
//清单精灵
$('#linkQDJL').click(function () {
    //提高焦点变换性能 2019年4月12日--
    if (!subObj.fisrtLinked) {
        gljOprObj.preActiveTab = gljOprObj.activeTab;
    }
    subObj.fisrtLinked = false;
    //--
    gljOprObj.activeTab='#linkQDJL';
    $("#subItems").children().hide();
    //subObj.showQDSubTabData();    //提升焦点变换性能 2019年4月12日
    $('#qdjl').show();
    $("#xmtzTextDiv").show();
    $("#tzItemTab").show();
    let selectedNode = projectObj.mainController.tree.selected;
    BillsSub.billsSelSub(selectedNode.data.code);
    //refreshSubSpread();      //提升焦点变换性能 2019年4月12日
    gljOprObj.setNodeShowTab();

});
//清单指引
$('#linkQDZY').click(function () {
  if (!subObj.fisrtLinked) {
      gljOprObj.preActiveTab = gljOprObj.activeTab;
  }
  subObj.fisrtLinked = false;
  //--
  gljOprObj.activeTab='#linkQDZY';
  $("#subItems").children().hide();
  $('#qdzy').show();
  $("#xmtzTextDiv").show();
  $("#tzItemTab").show();
  let selectedNode = projectObj.mainController.tree.selected;
  BillsSub.billsSelSub(selectedNode.data.code);
  gljOprObj.setNodeShowTab();

});

//特征及内容
$("#linkTZJNR").click(function () {
    gljOprObj.preActiveTab = gljOprObj.activeTab;   //提高焦点变换性能 2019年4月12日
    gljOprObj.activeTab='#linkTZJNR';
    $("#subItems").children().hide();
    $("#tzjnrCon").show();
    $("#xmtzTextDiv").show();
    subObj.showQDSubTabData();
    $("#add-rule p").not(":first").css('margin-bottom', 4);
    pageCCOprObj.active = true;
    adaptiveTzjnrWidth();
    contentOprObj.workBook.getActiveSheet().showColumn(0, GC.Spread.Sheets.HorizontalPosition.left);
    characterOprObj.workBook.getActiveSheet().showColumn(0, GC.Spread.Sheets.HorizontalPosition.left);
    let selectedNode = projectObj.mainController.tree.selected;
    if (projectObj.project.property.addRule !== undefined) {
        setRule(projectObj.project.property.addRule);
    }
    pageCCOprObj.mainActiveCell = projectObj.mainSpread.getActiveSheet().getSelections()[0];
    pageCCOprObj.setCacheAndShow(selectedNode);
    gljOprObj.setNodeShowTab();
});
//打开排版规则
$('#openTypeSetting').click(function () {
    $('#add-rule').show();
    $(this).hide();
    adaptiveTzjnrWidth();
});
//关闭排版规则
$('#closeTypeSetting').click(function () {
    $('#add-rule').hide();
    $('#openTypeSetting').show();
    adaptiveTzjnrWidth();
});

//应用到选中清单、应用到所有，添加位置列如果隐藏了，则重新显示
function colSettingAddPosition(addPosition){
    let settingMapping = {1: 'itemCharacterText', 2: 'name', 3: 'jobContentText', 4: 'both'};
    let settingInfo = settingMapping[addPosition];
    if(!settingInfo){
        return;
    }
    let fields = [];
    if(settingInfo === 'both'){
        fields = [settingMapping['1'], settingMapping['3']];
    }
    else{
        fields = [settingInfo];
    }
    let needToUpdate = false;
    let showItemCharacter = false;
    for(let field of fields){
        let colVisible = colSettingObj.getVisible(field);
        if(field === settingMapping['1'] && !colVisible){
            showItemCharacter = true;
        }
        if(!colVisible){
            colSettingObj.setVisible(field, true);
            needToUpdate = true;
        }
    }
    if(showItemCharacter){
        switchTznrHtml(false);
    }
    if(needToUpdate){
       colSettingObj.updateColSetting(true);
    }
}

//如果，添加内容为定额子目时进行定额的增删改，更新相关其清单
function updateBillsOprRation() {
    const setting = getAddRuleSetting();
    if(setting && setting.addContent && setting.addContent === '5'){
        $('#use-to-current').click();
    }
}

// 应用到选中清单
let isSaving = false;
$("#use-to-current").click(function() {
    if($(this).hasClass('disabled')){
        return false;
    }
    if(projectReadOnly){
        return false;
    }
    if (isSaving) {
        return false;
    }
    const setting = getAddRuleSetting();
    colSettingAddPosition(setting.position);
    isSaving = true;
    const self = $(this);
    self.attr('disabled', 'disabled');
    let selectedNode = projectObj.mainController.tree.selected;
    function findBill(node){
        while(node && node.sourceType !== projectObj.project.Bills.getSourceType()){
            node = node.parent;
        }
        return node;
    }
    let billsNode = findBill(selectedNode);
    // 操作内容
    pageCCOprObj.setCharacterBySetting(billsNode, setting);

    // 防止连续点击1秒后才能再次发起请求
    setTimeout(function() {
        isSaving = false;
        self.removeAttr('disabled');
    }, 1000);
});
//todo: 优化成批量
function addRuleUseToBills(setting, nodes) {
    pageCCOprObj.bulkSetCharacterBySetting(nodes, setting);
}
// 应用到所有的清单
$("#use-to-all").click(function() {
    if($(this).hasClass('disabled')){
        return false;
    }
    if(projectReadOnly){
        return false;
    }
    let treeNode = projectObj.mainController.tree;
    const setting = getAddRuleSetting();
    colSettingAddPosition(setting.position);
    if (treeNode.items === undefined || treeNode.items.length <= 0) {
        return false;
    }
    // 处理
    addRuleUseToBills(setting, treeNode.items);
});

function saveAddRule(){
    let setting = getAddRuleSetting();
    let toUpdate = false;
    if(!projectObj.project.property.addRule){
        toUpdate = true;
    }
    else {
        for(let attr in setting){
            if(setting[attr] !== projectObj.project.property.addRule[attr]){
                toUpdate = true;
                break;
            }
        }
    }
    if(toUpdate){
        projectObj.project.property.addRule = setting;
        projectObj.project.saveProperty('addRule', setting);
    }
}

// 添加位置选择
function changeAddPosition(save = false) {
    const selected = $('#add-position').children(":selected").val();
    const addContentEle = $("#add-content");
    const displayFormatEle = $("#display-format");
    const characterFormatEle = $("#character-format");
    const serialTypeEle = $("#serial-type");
    switch (selected) {
        case '4':
            // 分别添加到对应列
            // 当“添加位置”是“分别添加到对应列”，则“添加内容”恢复默认“无”，且灰显；“显示格式”恢复默认“换行分隔”，且灰显。
            addContentEle.val('');
            addContentEle.attr('disabled', 'disabled');
            displayFormatEle.val(1);
            characterFormatEle.val(2);
            serialTypeEle.val(1);
            break;
        default:
            addContentEle.removeAttr('disabled');
            displayFormatEle.removeAttr('disabled');
            characterFormatEle.removeAttr('disabled');
            addContentEle.val(1);
            break;
    }
    if (save) {
        saveAddRule();
    }
}
$("#add-position").change(function() {
    changeAddPosition(true);
});
// 添加内容选择
function changeAddContent(save = false) {
    const selected = $('#add-content').children(":selected").val();
    const characterFormatEle = $("#character-format");
    const childDisplayFormatEle = $("#child-display-format");
    const serialTypeEle = $("#serial-type");

    switch (selected) {
        case '5':
            // 当“添加内容”是“定额子目”或“工作内容”，则“特征生成方式”灰显，不需选择；否则有效可选。
            characterFormatEle.attr('disabled', 'disabled');
            characterFormatEle.val(2);
            // 当“添加内容”是“定额子目”，则“子目生成方式”有效可选；否则灰显，不需选择。
            childDisplayFormatEle.removeAttr('disabled');
            serialTypeEle.val('');
            serialTypeEle.attr('disabled', 'disabled');
            break;
        case '':
            characterFormatEle.attr('disabled', 'disabled');
            break;
        case '1':
        case '2':
        case '3':
            characterFormatEle.removeAttr('disabled');
            if (serialTypeEle.val() === '') {
                serialTypeEle.val(1);
            }
            serialTypeEle.removeAttr('disabled');
            childDisplayFormatEle.attr('disabled', 'disabled');
            break;
        case '4':
            // 当“添加内容”是“定额子目”或“工作内容”，则“特征生成方式”灰显，不需选择；否则有效可选。
            characterFormatEle.attr('disabled', 'disabled');
            characterFormatEle.val(2);
        default:
            serialTypeEle.removeAttr('disabled');
            if (serialTypeEle.val() === '') {
                serialTypeEle.val(1);
            }
            childDisplayFormatEle.attr('disabled', 'disabled');
            break;
    }
    if (save) {
        saveAddRule();
    }
}
$("#add-content").change(function() {
    changeAddContent(true);
});

//显示格式
$('#display-format').change(function () {
    saveAddRule();
});

//特征生成方式
$('#character-format').change(function () {
    saveAddRule();
});

// 子目生成方式选择事件
function changeChildDisplay(save = false) {
    const selected = $('#child-display-format').children(":selected").val();
    const serialTypeEle = $("#serial-type");
    const addContent = $('#add-content').val();
    // 如果添加内容是定额子目且子目生成方式是编号+定额名称则序号格式不能选择
    if (addContent === '5' && selected === '1') {
        // 默认选中数字显示模式
        serialTypeEle.val("");
        serialTypeEle.attr('disabled', 'disabled');
    } else {
        serialTypeEle.val(1);
        serialTypeEle.removeAttr('disabled');
    }
    if (save) {
        saveAddRule();
    }

}
$("#child-display-format").change(function() {
    changeChildDisplay(true);
});

//序号格式
$('#serial-type').change(function () {
    saveAddRule();
});

/**
 * 获取添加规则的设置
 *
 * @return {Object} - 返回设置内容
 */
function getAddRuleSetting() {
    // 添加位置
    const position = $("#add-position").val();
    // 添加内容
    const addContent = $("#add-content").val();
    // 显示格式
    const displayFormat = $("#display-format").val();
    // 特征生成方式
    const characterFormat = $("#character-format").val();
    // 子目生成方式
    const childDisplayFormat = $("#child-display-format").val();

    // 序号格式
    const serialType = $("#serial-type").val();
    const setting = {
        serialType,
        characterFormat,
        addContent,
        position,
        displayFormat,
        childDisplayFormat,
    };

    return setting;
}

/**
 * 根据配置设置规则
 *
 * @param {Object} setting - 数据库中读取的数据
 * @return {void}
 */
function setRule(setting) {
    if (Object.keys(setting).length <= 0) {
        return;
    }
    $("#add-position").val(setting.position);
    changeAddPosition(false);

    $("#add-content").val(setting.addContent);
    changeAddContent(false);

    $("#display-format").val(setting.displayFormat);

    $("#character-format").val(setting.characterFormat);

    $("#child-display-format").val(setting.childDisplayFormat);
    changeChildDisplay(false);

    $("#serial-type").val(setting.serialType);

    if(projectReadOnly){
        disableTools();
    }
}

function activeSubSheetIs(idx){
    let rst = subSpread.getActiveSheetIndex() == idx;
    return rst;
}

function activeSubSheetIsCalcProgram(){
    return subSpread.getActiveSheetIndex() == subSheetIndex.ssiCalcProgram;
}

//弹出清单规则或定额库后导致subSpread和特征及内容spread显示出问题
function refreshSubSpread(){
    if(pageCCOprObj.active){
        contentOprObj.workBook.refresh();
        characterOprObj.workBook.refresh();
    } else{
        if(subSpread) subSpread.refresh();
        if(MaterialController.spread) MaterialController.spread.refresh();
    }
    BillsSub.refreshWorkBook();
    //if($('#linkZMHS').hasClass('active')) zmhs_obj.refresh();
    if($('#rnc-zm').is(':visible')|| $('#rnc-fz').is(':visible') || $('#rnc-cus')) zmhs_obj.refresh();
    if($('#linkMBZM').hasClass('active')) mbzm_obj.refresh();
}

let subViewObj = {
    linkTabClick: function () {
        $("#subItems").children().hide();
        $($(this).attr('href')).show();
    },
    loadComments: function (node) {
        let comments = [];
        let commentText = '';
        if (node) {
            if (node.sourceType === projectObj.project.Bills.getSourceType() &&
                (node.data.type === billType.FX || node.data.type === billType.BX || node.data.type === billType.BILL)) {
                if(node.data.ruleText && node.data.ruleText !== ''){
                    comments.push('工程量计算规则:');
                    comments.push(node.data.ruleText);
                }
                if(node.data.comments && node.data.comments !== ''){
                    comments.push('清单注释：');
                    comments.push(node.data.comments);
                }
            } else if (node.sourceType === projectObj.project.Ration.getSourceType()) {
                if(node.data.content && node.data.content !== ''){
                    comments.push('工作内容：');
                    comments.push(node.data.content);
                }
                if(node.data.annotation && node.data.annotation !== ''){
                    comments.push('附注：');
                    comments.push(node.data.annotation);
                }
            }
            commentText = comments.join('\n');
        }
        $('#comments>textarea').val(commentText);
    },
    saveComments: function (node) {
        let text = $('#comments>textarea').val();
        if (node && node.sourceType === projectObj.project.Bills.getSourceType()) {
            if (node.data.comments !== text) {
                projectObj.project.Bills.updateField(node.source, "comments", text);
            }
        } else if (node && node.sourceType === projectObj.project.Ration.getSourceType()) {
            if (node.data.comments !== text) {
                projectObj.project.Ration.updateField(node.source, "comments", text);
            }
        }
    }
}

$("#linkComments").click(subViewObj.linkTabClick);

$('#linkGLJ').on('shown.bs.tab', function () {
    gljOprObj.showDataIfRationSelect(projectObj.project.mainTree.selected, '111111');
});

$('.linkQDJL').on('shown.bs.tab', function () {
    subObj.showQDSubTabData();
    if(!subObj.inited) {
        $("#tz_toogle").click();
        subObj.inited = true;
    }
});


$('#linkZMHS').on('shown.bs.tab', function (e) {
    if(zmhs_obj.coeSpread == null || zmhs_obj.assSpread == null){
        zmhs_obj.initSpread();
    }
    zmhs_obj.refresh();
    zmhs_obj.showZMHSData();
});


$('#linkMBZM').on('shown.bs.tab', function (e) {
    if (gljOprObj.activeTab !== gljOprObj.preActiveTab) {   //提高焦点变换性能 2019年4月12日
        mbzm_obj.refresh();
    }
    mbzm_obj.showMBZMData();
});


$('#linkComments').on('shown.bs.tab', function () {
    subViewObj.loadComments(projectObj.project.mainTree.selected);
});

$('#linkGCLMX').on('shown.bs.tab', function () {
    gljOprObj.showDataIfRationSelect(projectObj.project.mainTree.selected, '111111');
});

$('#linkAZZJF').on('shown.bs.tab', function () {
    gljOprObj.showDataIfRationSelect(projectObj.project.mainTree.selected, '111111');
});

$('#zmhs_toogle').bind('click',function (){
   $("#zmhs_nav").show();
   if(subObj.showGljSubTab == false){
       subObj.activeGLJItemTab?$(subObj.activeGLJItemTab).click():$("#hs-nav").click();
   }
    $("#zmhs_toogle").hide();
});

$('#tz_toogle').bind('click',function (){
    $("#tz_nav").show();
    if(subObj.showQDSubTab == false){
        subObj.activeQDItemTab?$(subObj.activeQDItemTab).click():$("#tz-nav").click();
    }
    $("#tz_toogle").hide();
});

$('.gljSubTab ul li a').bind('click',function () {
    if(this.hash =="#rnc-close"){
        $("#zmhs_nav").hide();
        $("#zmhs_toogle").show();
        closeTab(this);
        subObj.showGljSubTab = false;
    } else {
        subObj.showGljSubTab = true;
        subObj.activeGLJItemTab =this;
    }

    subObj.initGljSubTab();
    refreshSubSpread();
    /* if($(this).hasClass("active")){//点击展开了后又点击了自身，这时要隐藏tab和修改本身class
     subObj.showGljSubTab = false;
     closeTab(this);
     subSpread.focus();//要加上这个，不然右边侧栏的选中状态的border线不会消换
     }*/
});

$('.QDSubTab ul li a').bind('click',function () {
    if(this.hash =="#rnc-close"){
        $("#tz_nav").hide();
        $("#tz_toogle").show();
        closeTab(this);
        subObj.showQDSubTab = false;
    } else {
        subObj.showQDSubTab = true;
        subObj.activeQDItemTab =this;
    }
    subObj.initQDSubTab();
    refreshSubSpread();
});


$('.gljSubTab ul li a').on('shown.bs.tab', function () {
    if(this.hash == "#rnc-xm"){
        //初始化项目特征表格位置，如果以后需要的话，showdata 统一移动至zmhs_obj中
       //todo
    }else if(this.hash == "#rnc-zm"){
        zmhs_obj.initCoeSpread();
    }else if(this.hash == "#rnc-fz"){
        zmhs_obj.initAssSpread();
    }else if(this.hash == "#rnc-cus"){
        zmhs_obj.initCusSpread();
    }
    zmhs_obj.refresh();
    zmhs_obj.showDatas();
});

//显示格式
$('#tzCharacterText').blur(async function () {
  let billID = $("#xmtz_billID").val();
  let value = $(this).val();
  //let htmlString = $(this).html();
  // let value = htmlString.replace(/&nbsp;/g," ");
  // if(value.indexOf("<div>")!= -1){
  //     let preString = value.substring(0,value.indexOf("<div>"));
  //     let arrayText =[];
  //     let divArray = value.match(/<div>(.*?)<\/div>/g);
  //     for(let d of divArray){
  //         t = d.match(/<div>(\S*)<\/div>/)[1];
  //         if(t == "<br>") t="";
  //         arrayText.push(t)
  //     }
  //     value = preString +"\n"+ arrayText.join("\n");
  // } 
  // value = value.replace(/<br>/g,"\n");

  let billNode = projectObj.project.mainTree.getNodeByID(billID);
  if(billNode && value == billNode.data.itemCharacterText) return;
  let datas = [{
    type:'bills',
    data:{
        ID:billID,
        itemCharacterText:value
    }
  }]
  await projectObj.project.syncUpdateNodesAndRefresh(datas);

});

function closeTab(elem) {
    setTimeout(function () {
        $(elem).removeClass("show");
        $(elem).removeClass("active");
        $(elem).attr("aria-selected",false);
        $(elem.hash).removeClass("show");
        $(elem.hash).removeClass("active");
    },50);

}


