/*
 * @Descripttion: 
 * @version: 
 * @Author: lihw02
 * @Date: 2021-01-04 16:27:31
 * @LastEditors: lihw02
 * @LastEditTime: 2021-01-12 18:12:13
 */
var $h;
//生成内容导航
function generateSectionNavigator(){
    $h = $(".page-inner .markdown-section").find("h3");
    $h.each(function(){
        var cls="anchor-h1";
        if($(this).is("h2")){
            cls="anchor-h2";
        }
        if($(this).is("h3")){
            cls="anchor-h3";
        }
        var text = $(this).text();
        var href = $(this).attr("id");
        $(".book-anchor-body").append("<a id='an_"+text+"' class='anchor-text "+cls+"' title='"+text+"'  href='#"+href+"'>"+text+"</a>")
    });

    
    if ($h.length === 0) {
        $('.book-anchor').hide();
    }

    $(".book-anchor-title").click(function () {
        // $(".book-anchor-body").toggle();
    });

    $(".book-anchor-body>a").click(function(){
        updateActiveNavItem($(this));
    });

    //获取hash值定向到指定位置
    var hash = decodeURIComponent(location.hash);
    if(hash){
        hash = hash.substring(1);
        $("#an_"+hash).addClass("selected");
    }
    
}

function getActiveSection(data, boundryTop, boundryBottom) {
    let activeSection;
  
    data.forEach(section => {
      if (section.offsetTop > boundryBottom) {
        if (!activeSection && section.offsetTop < boundryTop) {
          activeSection = section;
        }
      } else {
        activeSection = section;
      }
    });
  
    if (activeSection && activeSection.subSections.length) {
      let activeSubSection;
  
      activeSubSection = getActiveSection(
        activeSection.subSections,
        boundryTop,
        boundryBottom
      );
  
      if (activeSubSection) {
        activeSection = activeSubSection;
      }
    }
  
    return activeSection;
  }

  function updateActiveNavItem(activeAn) {
    $(".book-anchor-body>a").removeClass("selected");
    activeAn.addClass("selected");
  }
  

  function getActiveSection() {
    var topObj = $(".page-inner .markdown-section").find("h3").map(function() {
    return {
    top: Math.abs($(this).offset().top),
    node: this,
        };
    });
     var min = Math.min.apply(null,$(topObj).map(function(i, n) { return n.top;}));
    var activeSectionArr = $.grep(topObj, function (n,i ) {
        return n.top === min;

    });
    var activeSection;
    if(activeSectionArr) {
    activeSection = activeSectionArr[0].node;
    }
  
    return activeSection;
  }
  
  

function setupScrollHandler(scrollnav) {
    function scrollHandler() {

        
        console.log('scrollHandler :>> ', 234);
      var activeSection = getActiveSection();
      var activeAn = $('#an_'+$(activeSection).attr('id'));
  
      updateActiveNavItem(activeAn);
  
      return activeSection;
    }
  
    $('.body-inner').on('scroll', scrollHandler);
  
    return scrollHandler;
  }
  


module.exports = {
    init: generateSectionNavigator,
    setupScrollHandler: setupScrollHandler
};
