(function ($) {
  var api = ['tft_build', 'tft_buildlist', 'tft_item', 'tft_origin', 'tft_class', 'tft_level'];

  // 初始化
  init();

  function init() {
    fetchMenuData();
    handleEvent();
    hideLoading();
  }

  // 获取menu下的数据
  function fetchMenuData(type) {
    var idx = type || 0,
      $container = $('#js-tab-content .tab-panel:eq(' + idx + ')');

    var response = vcmsg(api[idx]);

    if (!response) return;

    var data = JSON.parse(response)

    // 阵容克制,不同模版，左侧sidebar
    if (idx === 1) {
      // 渲染左侧菜单
      renderSidebar('tpl-sidebar', $('#js-sidebar'), data['1080']);
      fetchSidebarData(idx, data['1080'].data[0].link)
    } else {
      render('tpl-content', $container, data['1080']);
    }
  }

  // 获取sidebar下的数据
  function fetchSidebarData(idx, link) {
    var $container = $('#js-sidebar-main');

    idx = idx || 0;

    var response = vcmsg(link);

    if (!response) return;

    var data = JSON.parse(response)

    render('tpl-content', $container, data['1080']);
  }

  // 渲染页面
  function render(tempId, container, data) {
    var html = template(tempId, data);

    container.css({
      width: data.total_size.size_x,
      height: data.total_size.size_y
    })
    container.html(html);

    container.find('img.lazy').lazyload({
      effect: 'fadeIn',
      threshold: 200,
      failurelimit: 10
    }).removeClass('lazy');
  }

  // 显示左侧菜单
  function renderSidebar(tempId, container, data) {
    var html = template(tempId, data);
    container.html(html);

    handleSidebarEvent();
  }

  // 隐藏loading
  function hideLoading() {
    setTimeout(function () {
      $('.loading-wrapper').fadeOut(300);
    }, 300)
  }

  function handleEvent() {
    var $navBar = $('#js-navbar');

    $navBar.on('click', '.navbar-item', function () {
      var $this = $(this),
        idx = $this.index(),
        $panel = $('#js-tab-content .tab-panel:eq(' + idx + ')');

      if ((idx === 1 && !$panel.find('#js-sidebar .sidebar-item').length) || !$panel.find('div').length) {
        fetchMenuData(idx)
      }

      $this.addClass('active').siblings().removeClass('active');
      $panel.addClass('active').siblings().removeClass('active');
    })

    // 触发关闭方法
    $('#js-close').on('click', function () {
      vcclose();
    })
  }

  function handleSidebarEvent() {
    $('#js-sidebar').on('click', '.sidebar-btn', function () {
      var $this = $(this),
        idx = $this.index(),
        $link = $this.attr('data-link'),
        isActive = $this.hasClass('active');

      if (isActive) return;

      $this.addClass('active').siblings().removeClass('active');
      // 显示右侧内容
      fetchSidebarData(idx, $link)
    })
  }
})(jQuery);
