/**
 * 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月15日
    TZJNRrePercent:null,
    showGljSubTab:false,
    firstOpen:true,
    initSubSpread:function () {
        //清单精灵
        BillsElf.buildSheet();
        $("#subSpread").show();
        subSpread = sheetCommonObj.createSpread($("#subSpread")[0], 4);
        sheetCommonObj.spreadDefaultStyle(subSpread);
        subSpread.options.allowUserDragDrop = false;
        subSpread.options.allowUserDragFill = false;
        subSpread.getSheet(2).name('JSCX');

        // 工料机
        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){
            disableSpread(subSpread);
        }
    },
    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();//检查是否安装工程
  			$('#QDJL_div').hide();
            $("#linkGLJ").addClass();
            $(gljOprObj.rationTab).click();
        }else {
            $("#GLJ_div").hide();
            $("#ZMHS_div").hide();
            $("#MBZM_div").hide();
            $("#AZZJF_div").hide();
            $('#QDJL_div').hide();//暂时隐藏
            $(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();
    },
    showGljSubTabData:function () {
        this.initGljSubTab();
        zmhs_obj.showDatas();
        if (gljOprObj.activeTab !== gljOprObj.preActiveTab) {   //提高焦点变换性能 2019年4月15日
            if($("#subItems").is(':visible')) refreshSubSpread();
        }
        if(this.firstOpen == true){
            $("#zmhs_toogle").click();
            this.firstOpen = false;
        }
    }
};



$("#linkGLJ").click(function(){
    $("#subItems").children().hide();//控制显示subSpread,隐藏特征及内容spread
    //show
    //MaterialController.showReplaceDiv();
    //subObj.showGljSubTabData();   //提升焦点变换性能 2019年4月15日
    $("#subSpread").show();
    $("#itemTextDiv").show();
    $("#gljItemTab").show();
    subSpread.options.allowUserDragFill = false;
    //refreshSubSpread();   //提升焦点变换性能 2019年4月15日
    subSpread.setActiveSheetIndex(0);
    //提高焦点变换性能 2019年4月15日--
    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();
    refreshSubSpread();
    subSpread.setActiveSheetIndex(3);
    gljOprObj.activeTab='#linkAZZJF';
    gljOprObj.setNodeShowTab();
});

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

$("#linkJSCX").click(function(){        // 计算程序
    $("#subItems").children().hide();
    MaterialController.hideReplaceDiv();
    $("#subSpread").show();
    refreshSubSpread();
    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月15日
    gljOprObj.activeTab='#linkJSCX';
    gljOprObj.setNodeShowTab();
});



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

//清单精灵
$('#linkQDJL').click(function () {
    gljOprObj.preActiveTab = gljOprObj.activeTab;   //提升焦点变换性能 2019年4月15日
    gljOprObj.activeTab='#linkQDJL';
    $("#subItems").children().hide();
    $('#qdjl').show();
    let selectedNode = projectObj.mainController.tree.selected;
    BillsElf.billsSelElf(selectedNode.data.code);
    refreshSubSpread();
    gljOprObj.setNodeShowTab();
    BillsElf.refreshWorkBook();

});

//应用到选中清单、应用到所有，添加位置列如果隐藏了，则重新显示
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 activeSubSheetIs(idx){
    let rst = subSpread.getActiveSheetIndex() == idx;
    return rst;
}

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

//弹出清单规则或定额库后导致subSpread和特征及内容spread显示出问题
function refreshSubSpread(){
    if(subSpread) subSpread.refresh();
    if(MaterialController.spread) MaterialController.spread.refresh();
    BillsElf.refreshWorkBook();
    if($('#rnc-zm').is(':visible')|| $('#rnc-fz').is(':visible') || $('#rnc-cus') || $('#rnc-stable').is(':visible')) 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');
});

$('#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) {
    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.activeTab?$(subObj.activeTab).click():$("#hs-nav").click();
   }
    $("#zmhs_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.activeTab =this;
    }

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

$('.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();
    }else if(this.hash == "#rnc-stable"){
        zmhs_obj.initStableSpread();
    }
    zmhs_obj.refresh();
    zmhs_obj.showDatas();
});

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);

}


