const $ = require('jquery');
require("../css/uncorrectedCopy.less");
require('./modal.js');
const {api} = require('./api.js')
const {post,getCookie,getUrlArgObjectNew,emptyBox,setTitleTxt,explainTitle,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 = "",orderTitle=[],orderKey=[],orderList=[], 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)||""
$(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
/*if(lineType){
  $("th[code="+data_desc+"]").addClass("desc");
}*/
//setTitleTxt('',from)         //导航栏面包屑
let isPlacefile = getCookie('isPlacefile')||1
setTitleList()
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(isPlacefile==1){
  $(".dateTime").html('出院时间：')
  $(".partTitle p span").html('终末病历稽查表')
}else{
  $(".dateTime").html('入院时间：')
  $(".partTitle p span").html('运行病历稽查表')
}
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)
})
$(".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-YXBLJCB]").addClass("active")
$(parent.document).find(".menu .page[code=YH-ZKK-ZMBLJCB]").addClass("active")


function setTitleList(){
  $('.pagination').html("")
  $('.key-list tbody').html(emptyBox('努力加载中...',26,1))
  post(api.medicalCheckTitle,{}).then(res =>{
    if(res.data.code == '0'){
      const data = res.data.data||[];
      getTabData(1)
      if (isfirstRenderTitle === false) { renderTabTitle(data) }  //首次渲染渲染Table表头
    }
  })
}
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: activePage,
    size: 15,
    "name": deptName=="全部"?"":deptName||"",
    "deptName": deptName=="全部"?"":deptName||"",
    // "asc":data_asc,     //升序
    // "desc":data_desc,       //降序
    "startDate":dateStatrt.replace(/\//g,'-'),
    "endDate":dateEnd.replace(/\//g,'-'),
    "isPlacefile":isPlacefile
  }
  startDateParam = dateStatrt
  endDateParam = dateEnd
  $('.pagination').html("")
  $('.key-list tbody').html(emptyBox('努力加载中...',26,1))
  post(api.medicalCheckForm,param).then(res =>{
    if(res.data.code == '0'){
      const data = res.data.data||[];
      const totalPage = res.data.data.pages
      const totalNum = res.data.data.total
      renderTab(data,data.hospitalId,activePage);
      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) =>{

  })
}


$(".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){
  data = data.records;
  let str = ''
  // console.log(orderList)
  for(let i = 0; i < data.length; i++){
    const item = data[i]
    // console.log(item,'=====================item');
    str += `
        <tr  data-index=${i}>
            <td  class="textCenter">${(activePage-1)*15 + i+1}</td>`
      for(var j = 0; j < orderTitle.length; j++) {
        let tmpKey = orderTitle[j]
        if(tmpKey=='deptName'||tmpKey=='doctorName'){
          str += `<td dept-id="${item.deptId || ""}" data-tid="${item[tmpKey.replace('name','id')]}" data-doc="${item.doctorName}" dept-name="${item.deptName || ""}" data-id="${item.numId || ""}" data-name="${item[tmpKey] || ""}">${item[tmpKey.replace('name','num')]+'' || "-"}</td>`
        }else{
          str += `<td class="goHomeDetail" data-tid="${item[tmpKey.replace('name','id')]}" dept-id="${item.deptId || ""}" dept-name="${item.deptName || ""}" data-id="${item.numId || ""}" data-name="${item[tmpKey] || ""}"   data-doctor="${item.doctorName || ""}">${item[tmpKey.replace('name','num')]+'' || "-"}</td>`
        }
      }      
    str += `</tr>`
 }
  
  $('.key-list tbody').html(str?str:emptyBox())
  /*bindScoreDetail(hisId)*/
  // 跳转至详情页
  $(".goHomeDetail").click(function(){
    let casesName = $(this).attr("data-name") || '';
    let casesId = $(this).attr("data-tid");
    let name=$(this).attr("dept-name");
    // let docName=$(this).attr("data-doc");
    let doctorName = $(this).attr("data-doctor") || '';
    name=name==="全院"?"全部":name;
    let id=$(this).attr("dept-id");
    $(parent.document).find("#contentIframe").attr("src", "uccDetail.html?from=4&deptName=" + name + "&deptId=" + id + "&casesEntryId=" + casesId + "&defectName=" + casesName + "&startDate=" + startDateParam + "&endDate=" + endDateParam + "&doctorName=" + doctorName + "&isInspection=true")
  })
  // initScroll("partDetailControl","YX",1)
}


// 渲染table表头
function renderTabTitle(data){
  isfirstRenderTitle = true
  let str = `<th class="moduleName" style="width: 65px;">序号</th>`
  // data.sort(des)
  for(let i = 0; i < data.length; i++){
      const item = data[i]
      if(item.isShow == 1){
          str += `<th class="textCenter beHospitalId">${item.columnName}</th>`
          orderList.push(item)
      }
  }
  // orderList.sort(des)
  // function des(a,b){
  //   return a['orderNo']-b['orderNo']
  // }
  orderTitleLis(orderList)
  $(".tabTitle").html(str)
  // bindOrder()
}
function orderTitleLis(data){
  for(let i = 0;i < data.length;i++){
    let key = data[i].columnName
    orderTitle.push(data[i].fieldName)
    orderKey.push(key)
  }
}
//获取科室列表
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) =>{

    })
}

$('.selectDept').on("focus", function(e){
  e.stopPropagation()
  $(".selectLevel .arrow").attr("src",iconDown)
  const showList =  $(".deptList ").css("display")
  if(showList == "none" ||!showList){
    $(".deptList ").css("display","block")
    $(".selectDept .arrow").attr("src",iconUp)
  }else{
    $(".deptList ").css("display", "none")
    $(".selectDept .arrow").attr("src",iconDown)
  }
})
$('.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)
})
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 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)
    }
  })

}


$(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.replace(/\//g,'-'),
        endDate:endDateParam.replace(/\//g,'-'),
        isPlacefile:isPlacefile
      }
      expJson(api.medicalCheckExport,param).then(res =>{
          downloadExportedData(res.data, isPlacefile==1?"终末病历稽查表.xls":"运行病历稽查表.xls")
      })
      
      //  初始渲染TableTitle
      // getPageSet().then(res =>{
      //   $(".filter").click();   //初始查询
      // })
  })
});