const $ = require('jquery');
require("../css/uncorrectedCasesStatistics.less");
require('./modal.js');
const {api} = require('./api.js')
const {post,getCookie,getUrlArgObjectNew,emptyBox,setTitleTxt,setDatePicker,getPickerDate,expJson,downloadExportedData,initScroll,listenScroll} = require('./utils.js')
require('./../resource/jquery-ui/jquery-ui.min.js');
require('./../resource/jquery-ui/jquery-ui.min.css');
const iconCheck= require("./../images/icon_check.png")
const iconUnCheck = require("./../images/icon_unchecked.png")
const iconDown= require("./../images/arrow_down.png")
const iconUp = require("./../images/arrow_up.png")
const loadingImg = require("./../images/loading.gif")
const arrowLeft= require("./../images/arrow_left.png")
const arrowRight = require("./../images/arrow_right.png")
let deptName = "", behospitalCode = "", deptNameTemp = "", deptId = '', deptIdTemp = '', behospitalCodeTemp = "", data_desc = "", data_asc = "", columns = [], isfirstRenderTitle=false; 
let srcUrl = $("#contentIframe",parent.document).attr("src")
statisticsType = getUrlArgObjectNew("dateType",srcUrl)||"";
from = getUrlArgObjectNew("from",srcUrl)||""
lineType = getUrlArgObjectNew("lineType",srcUrl)||""
let startDateParam = getUrlArgObjectNew("startDateParam",srcUrl)||""
let endDateParam = getUrlArgObjectNew("endDateParam",srcUrl)||""
/*if(lineType){
  $("th[code="+data_desc+"]").addClass("desc");
}*/
//setTitleTxt('',from)         //导航栏面包屑
let isPlacefile = getCookie('isPlacefile')||1

listenScroll()
if(statisticsType == 1){
  setDatePicker($("#datepicker"),$("#datepicker2"),1)
}else if(statisticsType == 2){
  setDatePicker($("#datepicker"),$("#datepicker2"),2)
}else if(statisticsType == 3){
  setDatePicker($("#datepicker"),$("#datepicker2"),3,new Date(startDateParam),new Date(endDateParam))
}else{
  setDatePicker($("#datepicker"),$("#datepicker2"),'default')
}

if(!statisticsType){
  setDatePicker($("#datepicker"),$("#datepicker2"),'default')
}
$(".abnormalClear").click(function(){
  data_desc="";
  data_asc="";
  deptId="";
  deptIdTemp="";
  deptName="";
  deptNameTemp="";
  setDatePicker($("#datepicker"),$("#datepicker2"),"default")
  $(".selectDept").attr({'title':"全部",'data-id':''}).val("全部")
  $('.patientNumInp').val('')
  $("th[code]").removeClass("asc desc")
  //behospitalCode =behospitalCodeTemp= ""
  getTabData(1)
  getDeptList()
  
})
$(".partTitle a").click(function(){
  //初始菜单选中
  $(".menu .page",parent.document).removeClass("active").eq(0).addClass("active");
  $(".container",parent.document).addClass("console-cont");
})
$(".menu .page", parent.document).removeClass("active")
$(parent.document).find(".menu .page[code=YH-ZKK-WZGBLTJ]").addClass("active")

//判断有无某一权限
/*function hasData(data){
  let trdObj = JSON.parse(getCookie("trdObj"))
  let lis = trdObj['YH-BLZK-ZKPF']
  if(!lis){
    return false
  }
  if(lis.indexOf(data)>-1){//有权限
    return true
  }
  return false;
}*/
function getTabData(activePage){
  const dateStatrt = getPickerDate($("#datepicker"),1)
  const dateEnd = getPickerDate($("#datepicker2"),2)
  const start = new Date(dateStatrt).getTime()
  const end = new Date(dateEnd).getTime()
  if(start > end){
    $.alerModal({"message":'开始时间不能大于结束时间~',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
    return
  }
  const param = {
    // current: 1,
    // size: 15,
    "deptName": deptName=="全部"?"":deptName||"",
    "name": deptName=="全部"?"":deptName||"",
    "asc":data_asc,     //升序
    "desc":data_desc,       //降序
    //"type": 0, //1-本月，2-本年,0-自定义时间（现在所有都是自定义时间，都会传开始日期和结束日期）
    "startDate":dateStatrt.replace(/\//g,'-'),
    "endDate":dateEnd.replace(/\//g,'-')
  }
  startDateParam = dateStatrt
  endDateParam = dateEnd
  $('.pagination').html("")
  $('.key-list tbody').html(emptyBox('努力加载中...','',1))
  post(api.unModifyMRStatistics,param).then(res =>{
    if(res.data.code == '0'){
      const data = res.data.data||[];
      renderTab(data,data.hospitalId,activePage);
      if (isfirstRenderTitle === false) { renderTabTitle(data) }  //首次渲染渲染Table表头
      renderPagination(totalPage,Number(activePage),totalNum)
      if(totalPage > 1){
        renderPagination(totalPage,Number(activePage),totalNum)
      } else{
        $('.pagination').html("")
      }
    }else{
      $.alerModal({"message":res.data.msg,type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
    }
  }).catch((e) =>{

  })
 
}

getTabData(1)

$(".filter").on("click", function(e){
  deptName = deptNameTemp;
  behospitalCode = behospitalCodeTemp;
  if(deptName == ""){
      $(".selectDept").attr({'title':"全部",'data-id':''}).val("全部")
  }
  getTabData(1)
})
// // 处理th tr数据
function formatTableData(data){
  let newColumns = data.filter(function(item,index){
    if(item.isShow === 1) {
      return item
    }
  })
  return newColumns
}


function renderTab(data,hisId,activePage){
  let formatColumns = formatTableData(data.columns)
  data = data.data;
  let str = ``
  for(let i = 0; i < data.length; i++){
    const item = data[i]
    str += `
        <tr  data-index=${i}>
            <td  class="textCenter">${(activePage-1)*15 + i+1}</td>`
      for(var j = 0; j < formatColumns.length ; j++) {
          let dataId = `entry_${formatColumns[j].id}_id`;
          let dataName = `entry_${formatColumns[j].id}_name`
          let dataNum = `entry_${formatColumns[j].id}_num`
          entryId = item[dataId]
          entryName = item[dataName]
          entryNum = item[dataNum]
          if(!formatColumns[j].id){
            str += `<td>${item.deptName+'' || "-"}</td>`
          }else{
            str += `<td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${entryId || ""}" data-name="${entryName || ""}">${entryNum+'' || "-"}</td>`
          }
      }
    str += `</tr>`
 }
  // for(let i = 0; i < data.length; i++){
  //   const item = data[i];
  //   str += `
  //           <tr  data-index=${i}>
  //               <td  class="textCenter">${(activePage-1)*15 + i+1}</td>
  //               <td>${item.deptName+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2658_id || ""}" data-name="${item.entry_2658_name || ""}">${item.entry_2658_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2686_id || ""}" data-name="${item.entry_2686_name || ""}">${item.entry_2686_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_3010_id || ""}" data-name="${item.entry_3010_name || ""}">${item.entry_3010_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2656_id || ""}" data-name="${item.entry_2656_name || ""}">${item.entry_2656_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2657_id || ""}" data-name="${item.entry_2657_name || ""}">${item.entry_2657_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2170_id || ""}" data-name="${item.entry_2170_name || ""}">${item.entry_2170_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2930_id || ""}" data-name="${item.entry_2930_name || ""}">${item.entry_2930_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2900_id || ""}" data-name="${item.entry_2900_name || ""}">${item.entry_2900_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2229_id || ""}" data-name="${item.entry_2229_name || ""}">${item.entry_2229_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2220_id || ""}" data-name="${item.entry_2220_name || ""}">${item.entry_2220_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2221_id || ""}" data-name="${item.entry_2221_name || ""}">${item.entry_2221_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2655_id || ""}" data-name="${item.entry_2655_name || ""}">${item.entry_2655_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2654_id || ""}" data-name="${item.entry_2654_name || ""}">${item.entry_2654_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2218_id || ""}" data-name="${item.entry_2218_name || ""}">${item.entry_2218_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2217_id || ""}" data-name="${item.entry_2217_name || ""}">${item.entry_2217_num+'' || "-"}</td>            
  //               <td class="goHomeDetail" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.entry_2495_id || ""}" data-name="${item.entry_2495_name || ""}">${item.entry_2495_num+'' || "-"}</td>            
  //           </tr>
  //       `
  // }
  $('.key-list tbody').html(str?str:emptyBox())
  /*bindScoreDetail(hisId)*/
  // 跳转至详情页
  $(".goHomeDetail").click(function(){
    let casesName = $(this).attr("data-name") || '';
    let casesId = $(this).attr("data-id");
    let name=$(this).attr("dept-name");
    name=name==="全院"?"全部":name;
    let id=$(this).attr("dept-id");

    $(parent.document).find("#contentIframe").attr("src","uccDetail.html?from=3&deptName="+name+"&deptId="+id+"&casesEntryId="+casesId+"&defectName="+casesName+"&startDate="+startDateParam+"&endDate="+endDateParam)
  })
  // initScroll("partDetailControl","YX",1)
}


$('.selectDept').on("focus", function(e){
  e.stopPropagation()
  // let val = $(this).val().trim()
  // deptName = deptNameTemp = val
  // val&&getDeptList(val)
  $(".deptList ").css("display","block")
})
$('.selectDept').on("blur", function(e){
  $(".deptList ").css("display", "none")
  $(".selectDept .arrow").attr("src",iconDown)
})
$('.selectDept').on("input", function(e){
  let val = $(this).val().trim()
  deptName = deptNameTemp = val
  getDeptList(deptName)
})
//获取科室列表
getDeptList()
function getDeptList(val){
    post(api.getDeptList,{inputStr:val=="全部"?"":val||""}).then(res =>{
        if(res.data.code == '0'){
           const deptList = res.data.data||[]
           rendeDeptList(deptList)
        }else{
            rendeDeptList([])
        }
    }).catch((e) =>{

    })
}

function rendeDeptList(deptList){   
  if(deptList.length == 0){
    $('.deptList').html("")
    return
  }
  let str = `<li class="deptItem ellipsis" data-id=" " data-name="全部">全部</li>`;
  for(let i = 0; i < deptList.length; i++){
    str += `<li class="deptItem ellipsis" title=${deptList[i].deptName} data-id=${deptList[i].deptId} data-name=${deptList[i].deptName}> ${deptList[i].deptName}</li>`
  }
  $('.deptList').html(str)
  bindDeptSelect()
}
//科室选择
function bindDeptSelect(){
  $('.deptItem').on("mousedown",function(){
    const deptItemName = $(this).attr("data-name")
    const deptItemId = $(this).attr("data-id")
    deptIdTemp =deptItemId;
    deptNameTemp=deptItemName==="全部"?"":deptItemName;
    $('.selectDept').val(deptItemName)
    $('.selectDept ').attr('title',deptItemName)
    $(".deptList").css("display", "none")
    $('.selectDept').removeClass('unSelect')
  })
}
//获取页面配置

// function getPageSet(){
//   const dateStatrt = getPickerDate($("#datepicker"),1)
//   const dateEnd = getPickerDate($("#datepicker2"),2)
//   const start = new Date(dateStatrt).getTime()
//   const end = new Date(dateEnd).getTime()
//   if(start > end){
//     $.alerModal({"message":'开始时间不能大于结束时间~',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
//     return
//   }
//   const param = {
//     "name": deptName,
//     "asc":data_asc,     //升序
//     "desc":data_desc,       //降序
//     "startDate":dateStatrt.replace(/\//g,'-'),
//     "endDate":dateEnd.replace(/\//g,'-')
//   }
//   startDateParam = dateStatrt
//   endDateParam = dateEnd
//   post(api.unModifyMRStatistics,param).then(res =>{
//     if(res.data.code == '0'){
//       const data = res.data.data||[];
//       renderTabTitle(data)   //渲染Table表头
//     }else{
//       $.alerModal({"message":res.data.msg,type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
//     }
//   }).catch((e) =>{

//   })
// }
// getPageSet()

// 渲染table表头
function renderTabTitle(data){
  isfirstRenderTitle = true
  data = data.columns; 
  // console.log(data,'1111111');
  let str = `
  <th class="moduleName" style="width: 65px;">序号</th>`
  for(let i = 0; i < data.length; i++){
      const item = data[i]
      if(item.isShow == 1){
          // showNum++
          // str += `<th class="textCenter ${item.val} ${item.val =='leaveHospitalDate' ? 'desc':''}" code="${item.val}">${item.name}</th>`
          str += `<th class="textCenter beHospitalId" code="${item.fieldName}">${item.columnName}</th>`
      }
  }
  $(".tabTitle").html(str)
  bindOrder()
}

function loading(){
  const str = `
    <div class="loadingBox">
            <div class="mask"></div>
            <img class="loadingImg" src=${loadingImg}  alt="loading" />
        </div>
    `
  $("#mainBox", parent.document).append(str)
}
function hideLoading(){
  $("#mainBox .loadingBox", parent.document).remove()
}

// 上升下降筛选
function bindOrder(){
  $("th[code]").off("click").on("click",function(e){
    const code=$(this).attr("code");
    if(data_asc==code){
      data_desc=code;
      data_asc="";
      $("th[code]").removeClass("asc desc");
      $(this).addClass("desc");
    }else{
      data_desc="";
      data_asc=code;
      $("th[code]").removeClass("asc desc");
      $(this).addClass("asc");
    }
    getTabData(1);
  });
}


//分页渲染
function renderPagination(totalPage,activePage,totalNum){
  let str = `<span class="totalSum">共${totalPage}页/${totalNum}条数据</span><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>`
  $('.pagination').html(str)
  $('.page' + activePage).addClass('activePage')
  $(".pageNum").on("click", function(e){
    const activePageNow = Number($(this).attr('data-page'))
    getTabData(activePageNow)
    // renderPagination(totalPage,activePageNow,totalNum)
  })
  $(".prePage").on("click", function(e){
    let activePageNow = Number($(".activePage").attr('data-page'))
    if(activePageNow > 1){
      activePageNow--
      getTabData(activePageNow)
      // renderPagination(totalPage,activePageNow,totalNum)
    }
  })
  $(".nextPage").on("click", function(e){
    let activePageNow = Number($(".activePage").attr('data-page'))
    if(activePageNow < totalPage){
      activePageNow++
      getTabData(activePageNow)
      // renderPagination(totalPage,activePageNow,totalNum)
    }
  })

}

$(".patientNumInp").on("input", function(e){
  const val = $(this).val().trim()
  deptName = val
})

$(function() {
  const  iconCalenBlue= require("./../images/icon_calen_blue.png")
  const  iconCalenGrey= require("./../images/icon_calen_grey.png")
  $('.datapickerBox').append(`<img class="iconCalen" src=${iconCalenGrey} />`)
  $('.iconCalen').on("mouseenter", function(e){
    $(this).attr("src", iconCalenBlue)
  })
  $('.iconCalen').on("mouseleave", function(e){
    $(this).attr("src", iconCalenGrey)
  })
  $('.iconCalen').on("click", function(e){
    $(this).parent().find("input").focus()
  })
  $('.exportData').click(function(){
      const start = new Date(startDateParam).getTime()
      const end = new Date(endDateParam).getTime()
      if(start > end){
          $.alerModal({"message":'开始时间不能大于结束时间~',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
          return
      }
      const param = {
        name: deptName=="全部"?"":deptName||"",
        deptName: deptName=="全部"?"":deptName||"",
        asc:data_asc,     //升序
        desc:data_desc,       //降序
        startDate:startDateParam,
        endDate:endDateParam,
        isPlacefile:isPlacefile
      }
      expJson(api.unModifyMRStatisticsExport,param).then(res =>{
          downloadExportedData(res.data, "时效性相关统计.xls")
      })
      
      //  初始渲染TableTitle
      // getPageSet().then(res =>{
      //   $(".filter").click();   //初始查询
      // })
  })
});