require('./../css/searchStaticList.less');

const $ = require("jquery");
const { post,config,getUrlArgObject,openNewWin } = require('./promise.js');
const {toggleWarnBox} = require('./util.js');

let searchType = 0, inputStr = '', curPage = 1, size = 10, totalPage = 1;
searchType = getUrlArgObject('type') || 0
inputStr = getUrlArgObject('inputStr') || ''

let arrowLeft = require('./../images/leftpage.png').replace(/^undefined/g, '')
let arrowRight = require('./../images/rightpage.png').replace(/^undefined/g, '')
require('./../images/staticBgS.png').replace(/^undefined/g, '')
require('./../images/staticLogo.png').replace(/^undefined/g, '')
require('./../images/staticBg.png').replace(/^undefined/g, '')
require('./../images/nolis.png').replace(/^undefined/g, '')
require('./../images/warn.png').replace(/^undefined/g, '')

$(function(){
  initData()
  getAllTypes()
  getSearchList()
  getTabData()
});
//tab
function renderTab(data){
    let str = '';
    for (let i = 0; i < data.length; i++) {
      const element = data[i];
      str += `<li class="${i==0?'tabFst':''}" data-id="${element.val}">${element.name}</li>`
    }
    $('.staticTopTab ul').html(str)
    $('.staticTopTab li[data-id='+searchType+']').css({color:'#2A9BD5'}).siblings().css({color:'#333'});
    $(".staticTopTab li").click(function(){
      searchType = $(this).attr('data-id')
      $(this).css({color:'#2A9BD5'}).siblings().css({color:'#333'})
    })
  }
//获取字典信息
function getAllTypes(){
    /*const allTypes = localStorage.getItem('allTypes')&&JSON.parse(localStorage.getItem('allTypes'))||[];
    if(allTypes.length>0){
      renderTab(allTypes)
      return
    }*/
    post(config.dictionaryInfo, {}).then((res) => {
      const result = res.data
      if(result.code==='0'){
        const data = result.data[7]||[];
        //localStorage.setItem('allTypes',JSON.stringify(data))
        renderTab(data)
      }
    })
  }
function getSearchList(){
    $(".searchBtn").click(function(){
        $(".resultItemWrap,.pagination").html("");
        $(".staticResult .loading").show();
        curPage=1;
        getTabData()
    })
}
function getTabData(){
    let vals = $('.searchStr').val().trim();
    if (!vals) {
        $(".staticResult .loading").hide();
        toggleWarnBox('检索词不能为空！');
        return;
    }
    let param = {
        size,
        current:curPage,
        types:[+searchType],
        inputStr:vals
    }
    $(".resultItemEmpty").hide();
    post(config.staticSearch,param).then((res) => {
      const result = res.data
      if(result.code == 0) {
        const data = result.data;
        tabList = data.records;
          totalPage = data.pages;
        const totalNum = data.total;
        renderList(tabList);
        if(totalNum > 0){
            renderPagination(totalPage,Number(curPage),totalNum)
        } else{
            $('.pagination').html("")
        }
      }
    })
}
function renderList(tabList){
    $(".staticResult .loading").hide();
    if(tabList.length == 0){
        $('.pagination').html('')
        $(".resultItemWrap").html('');
        $(".resultItemEmpty").css({display:'block'});
        return
    }
    let str = ''
    for(let i = 0;i<tabList.length;i++){
        let item = tabList[i]
        str += `
            <div class="resultItem" data-type="${item.type}" data-name="${item.name}">
                <div>
                    <span class="type">${item.typeName}</span>
                    <span class="drug">${item.name}</span>
                    ${item.code ?`<span class="code">${item.code}</span>`:''}
                </div>
                ${item.retrievalName?`<div class="same">同义词：<span>${item.retrievalName}</span></div>`:''}
                <div class="content">
                    <p>${item.abstractContent}</p>
                </div>
            </div>
        `
    }
    $(".resultItemWrap").html(str);
    $('.resultItem').click(function(){
        let name = $(this).attr('data-name')
        let type = $(this).attr('data-type')
        if(window.opener){
            openNewWin(`./staticInfo.html?name=${name}&type=${type}`);
        }else{
            window.open(`./staticInfo.html?name=${name}&type=${type}`);
        }
    })
    window.scrollTo(0, 0);
}
function initData(){
    if(searchType){
        $('.staticTopTab li').eq(searchType).css({color:'#2A9BD5'}).siblings().css({color:'#333'})
    }
    if(inputStr){
        $(".searchStr").val(inputStr)
    }
}

// 分页
function renderPagination(totalPage,activePage,totalNum){
    let str = `<span class="totalSum">共${totalNum}条</span>
        <select class="select">
            <option value="10" ${size==10?'selected':''}>10条/页</option>
            <option value="50" ${size==50?'selected':''}>50条/页</option>
            <option value="100" ${size==100?'selected':''}>100条/页</option>
            <option value="500" ${size==500?'selected':''}>500条/页</option>
            <option value="1000" ${size==1000?'selected':''}>1000条/页</option>
            <option value="5000" ${size==5000?'selected':''}>5000条/页</option>
        </select>
        <span class="prePage">
            <img class="arrowPage" src=${arrowLeft} />
        </span>
    `
    if(totalPage <= 6){
        for(let i = 1; i <= totalPage; i++){
            str += `<span class="pageNum ${'page'+i}" data-page=${i}>${i}</span>`
        }
    }else{
        if(activePage <= 3){ //选中页数小于4
            for(let i = 1; i <= 4; i++){
                str += `<span class="pageNum ${'page'+i}" data-page=${i}>${i}</span>`
            }
            str += `<span class="more" >...</span>`
            str += `<span class="pageNum ${'page'+totalPage}" data-page=${totalPage}>${totalPage}</span>`
        } else if(activePage > totalPage -3){
            str += `<span class="pageNum page1" data-page=1>1</span>`
            str += `<span class="more" >...</span>`
            str += `<span class="pageNum ${'page'+(totalPage-3)}" data-page=${totalPage -3}>${totalPage -3}</span>`
            str += `<span class="pageNum ${'page'+(totalPage-2)}" data-page=${totalPage -2}>${totalPage -2}</span>`
            str += `<span class="pageNum ${'page'+(totalPage-1)}" data-page=${totalPage -1}>${totalPage -1}</span>`
            str += `<span class="pageNum ${'page'+totalPage}" data-page=${totalPage}>${totalPage}</span>`
        } else {
            str += `<span class="pageNum page1" data-page=1>1</span>`
            str += `<span class="more" >...</span>`
            str += `<span class="pageNum ${'page'+(activePage -1)}" data-page=${activePage -1}>${activePage -1}</span>`
            str += `<span class="pageNum ${'page'+activePage}" data-page=${activePage}>${activePage}</span>`
            str += `<span class="pageNum ${'page'+(activePage +1)}" data-page=${activePage +1}>${activePage +1}</span>`
            str += `<span class="more" >...</span>`
            str += `<span class="pageNum ${'page'+totalPage}" data-page=${totalPage}>${totalPage}</span>`
        }
       
    }
    str += `<span class="nextPage"><img class="arrowPage" src=${arrowRight} /></span>
        <span class="goNum">前往 <input type="number" value="${curPage}" /> 页</span>`
    $('.pagination').html(str)
    $('.page' + activePage).addClass('activePage')
    $(".pageNum").on("click", function(e){
        //console.log($(this)[0])
        const activePageNow = Number($(this).attr('data-page'))
        curPage = activePageNow
        getTabData()
    })
    $(".prePage").on("click", function(e){
        let activePageNow = Number($(".activePage").attr('data-page'))
        if(activePageNow > 1){
            curPage = --activePageNow
            getTabData()
        }
    })
    $(".nextPage").on("click", function(e){
        let activePageNow = Number($(".activePage").attr('data-page'))
        if(activePageNow < totalPage){
            curPage = ++activePageNow
            getTabData()
        }
    })
    $('.select').change(function(){
        size = $(this).val();
        curPage=1;
        getTabData()
    })
    $('.goNum input').change(function(){
        const n = $(this).val()
        if (totalPage < n || n < 1) {
            toggleWarnBox("请输入1-" + totalPage + "范围内的整数");
            return;
        }
        curPage = n;
        getTabData()
    })
}

$(function () {
    $(".warning-box .confirm,.warning-box .close").click(function () {
        toggleWarnBox();
    })
});

