require('../mock')
const $ = require('jquery');
// require("../css/partDetailControl.less");
require("../../css/dataAnalysis/improveStatistics.less");

require('../modal.js');
const {api} = require('../api.js')
const {post,getCookie,getLocal,getUrlArgObjectNew,emptyBox,setTitleTxt,setDatePicker,getPickerDate,downloadExportedData,expJson,initScroll,listenScroll} = require('../utils.js')
require('../../resource/jquery-ui/jquery-ui.min.js');
require('../../resource/jquery-ui/jquery-ui.min.css');
const iconDown= require("../../images/arrow_down.png")
const loadingImg = require("../../images/loading.gif")
const arrowLeft= require("../../images/arrow_left.png")

const arrowRight = require("../../images/arrow_right.png");
$(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
listenScroll()
let isPlacefile = getCookie('isPlacefile')||1

let deptName="",deptNameTemp="", behospitalCode="", behospitalCodeTemp="",deptId="",deptIdTemp="",
	data_desc="totalModeNum",data_asc="";
let startDate="",startDateTemp = "";
let endDate="",endDateTemp = "";

$(function() {
  const  iconCalenBlue= require("../../images/icon_calen_blue.png")
  const  iconCalenGrey= require("../../images/icon_calen_grey.png")
  //获取科室列表
  getDeptList()
  //日期控件事件绑定
  $('.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()
  })
  //日期默认当年
  setDatePicker($("#datepicker"), $("#datepicker2"), 2);
  startDate=startDateTemp=getPickerDate($("#datepicker"),1)
  endDate=endDateTemp=getPickerDate($("#datepicker2"),2)
  //初始列表数据获取
  getTabData(1);
  //导出事件绑定
  $('.export').click(function(){
	startDateTemp=getPickerDate($("#datepicker"),1);
	endDateTemp=getPickerDate($("#datepicker2"),2);
	const param = {
	  "deptName": deptNameTemp=="全部"?"":deptNameTemp||"",
	  "asc":data_asc,     //升序
	  "desc":data_desc,       //降序
	  "startDate":startDateTemp,
	  "endDate":endDateTemp
	};
	if(startDateTemp > endDateTemp){
	  $.alerModal({"message":'开始时间不能大于结束时间~',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
	  return
	}
	expJson(api.getQcClickByExport,param,{noPlacefile:true}).then(res =>{
	  downloadExportedData(res.data,"临床质控使用统计"+startDateTemp.substr(0,10).replace(/\//g,'')+"-"+endDateTemp.substr(0,10).replace(/\//g,'')+".xls");
	})
  })
  //给每一个标题绑定一个排序事件
  $("th[code]").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);
  });
  //重置
  $(".abnormalClear").click(function(){
	data_desc="totalModeNum"
	data_asc=""
	setDatePicker($("#datepicker"),$("#datepicker2"),"default");
	startDate=getPickerDate($("#datepicker"),1);
	endDate=getPickerDate($("#datepicker2"),2);
	$("#casesName,#entryName").val("");
	$("th[code]").removeClass("desc asc");
	$("th[code='totalModeNum']").addClass("desc");
	behospitalCode =behospitalCodeTemp= ""
	deptName = deptNameTemp = ""
	deptId = deptIdTemp = ""
	$(".selectDept").attr({'title':"全部",'data-id':''}).val("全部")
	getTabData(1)
	//getDeptList()
  })

//查询
  $(".filter").on("click", function(e){
	behospitalCode = behospitalCodeTemp
	deptId = deptIdTemp
	deptName = deptNameTemp
	startDate=getPickerDate($("#datepicker"),1)
	endDate=getPickerDate($("#datepicker2"),2)
	if(startDate > endDate){
	  $.alerModal({"message":'开始时间不能大于结束时间~',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
	  return
	}
	if(deptName == ""){
	  $(".selectDept").attr({'title':"全部",'data-id':''}).val("全部")

	}
	getTabData(1)
  })
});

function getFilterParam(){
  const param = {
	//"isPlacefile":isPlacefile,
	//"deptId": deptName=="全部"?"":deptId||"", //科室id
	"deptName": deptName=="全部"?"":deptName||"",
	"asc":data_asc,     //升序
	"desc":data_desc,       //降序
	"startDate":startDate,
	"endDate":endDate
  }
  return param;
}
/*$(".partTitle a").click(function(){
    //初始菜单选中
    $(".menu .page",parent.document).removeClass("active").eq(0).addClass("active");
    $(".container",parent.document).addClass("console-cont");
})
//判断有无某一权限
  function hasData(data){
    let trdObj = JSON.parse(getLocal("trdObj"))
    let lis = trdObj['YH-ZKK-TMQXGSTJ']
    if(!lis){
      return false
    }
    if(lis.indexOf(data)>-1){//有权限
        return true
    }
    return false;
}*/
function getTabData(activePage){
  const param =getFilterParam();
  if(param.start > param.end){
    $.alerModal({"message":'开始时间不能大于结束时间~',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
    return
  }
  $('.pagination').html("")
  $('.tbody').html(emptyBox('努力加载中...','',1))
  post(api.getQcClick,param,{noPlacefile:true}).then(res =>{
	if(res.data.code == '0'){
	  const detail = res.data.data||[];
	  /*const totalPage = data.pages;
	  const totalNum = data.total;*/
	  renderTab(detail,detail.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) =>{

  })
}
//表格dom渲染
function renderTab(data,hisId,activePage){
  let str = ``
  for(let i = 0; i < data.length; i++){
	const item = data[i];

	str += `
            <tr data-index=${i} data-deptid="${item.deptId}" data-dept="${item.deptName}">
                <td  class="textCenter">${(activePage-1)*15 + i+1}</td>
                <td >${item.deptName || "-"}</td>
                <td><a class="goHomeDetail">${item.singleModeNum}</a></td>
                <td><a class="goHomeDetail">${item.totalModeNum}</a></td>
            </tr>
        `
  }
  $('.tbody').html(str?str:emptyBox())
  $(".goHomeDetail").click(function(){
	let deptName = $(this).parents("tr").attr("data-dept")
	let deptId = $(this).parents("tr").attr("data-deptid")
	$(parent.document).find("#contentIframe").attr("src", "useStatisticsDept.html?deptName=" + deptName + "&deptId=" + deptId+ "&startDate=" + startDate+ "&endDate=" + endDate)
  })
}
function getDeptList(val){
  post(api.getQcClickDeptList,{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 " 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")
	deptNameTemp=deptItemName=="全部"?"":deptItemName;
	deptIdTemp =deptItemId||''
	$('.selectDept').val(deptItemName)
	$('.selectDept ').attr('title',deptItemName)
	$(".deptList").css("display", "none")
  })
  //科室下拉显示、选中事件
  $('.selectDept').on("focus", function(e){
	e.stopPropagation()
	$(".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)
  })
}
/*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 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)
	}
  })

}

