const $ = require('jquery');
require("../../css/dataAnalysis/statisticsDetail.less");
require('../modal.js');
const {api} = require('../api.js')
const {post,getCookie,getLocal,getUrlArgObjectNew,emptyBox,downloadExportedData,expJson,getLogoParam,focusMenuItem,listenScroll,exportTimeLimit} = 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 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 isPlacefile = getCookie('isPlacefile')||1

let srcUrl = $("#contentIframe",parent.document).attr("src")
let deptIdPram = getUrlArgObjectNew("deptId",srcUrl)||""
let deptNamePram = getUrlArgObjectNew("deptName",srcUrl)||""
let startDateParam = getUrlArgObjectNew("startDate",srcUrl)||""
let endDateParam = getUrlArgObjectNew("endDate",srcUrl)||""
let from = getUrlArgObjectNew("from",srcUrl)||""
let typeMark= getUrlArgObjectNew("typeMark",srcUrl)||"";       //0-总数量，1-已改善数量，2-待改善数量
let defectName = getUrlArgObjectNew("defectName",srcUrl)||"";
let casesId = getUrlArgObjectNew("casesId",srcUrl)||"";
let deptListDept = JSON.parse(getCookie("deptList"))||[]
let doctorNameUrl = getUrlArgObjectNew("doctorName", srcUrl) || ""
let currentPage;
deptNameTemp = docName = doctorNameUrl
listenScroll()
let tabList = [], name = "", behospitalCode="", behosDateStart="", level="",behosDateEnd="",
	nameTemp = "", behospitalCodeTemp="",levelTemp="", deptId="",deptIdTemp="", doctorName="", deptName="", deptNameTemp="",doctorNum="",doctorNameTemp="",doctorNumTemp="",
	data_desc="behospitalDate",data_asc="";
//科室传参
if(deptIdPram&&deptNamePram){
  deptId=deptIdTemp = deptIdPram
  deptName = deptNameTemp = deptNamePram
  $('.selectDept').text(deptNamePram)
  $('.selectDept ').attr('title',deptNamePram)
}else{
  deptId=deptListDept[0]&&deptListDept[0].deptId;
  deptName=deptListDept[0]&&deptListDept[0].deptName;
  deptNameTemp=deptListDept[0]&&deptListDept[0].deptName;
  deptIdTemp=deptListDept[0]&&deptListDept[0].deptId;
  $('.selectDept').val(deptName)
}
$(function() {
  $(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
  if(isPlacefile != 1){
	data_desc="behospitalDate"
  }
  $(".partTitle .titlePic ").html(`<a class="consoleP" href="improveStatistics.html">条目缺陷改善统计 / </a>病历列表`)

  $("#filterToggler").click(function(){
	const text = $(this).text();
	$(".toggle-item").slideToggle();
	$(this).text(text==="收起筛选"?"展开筛选":"收起筛选").toggleClass("up");
  });
  $(".patientNumInp").on("input", function(e){
	const val = $(this).val().trim();
	let beCode=behospitalCode;
	const patrn = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]/g;
	beCode=val.replace(patrn,function(x){
	  return "\\"+x;
	});
	behospitalCodeTemp = beCode
  });
  $(".patientNameInp").on("input", function(e){
	const val = $(this).val().trim()
	nameTemp = val
  })
  $("body").on("input",".doctorInp", function(e){
	const val = $(this).val().trim()
	doctorNameTemp = doctorNameUrl = val
  })
  $(".doctorNumInp").on("input", function(e){
	const val = $(this).val().trim();
	doctorNumTemp = val
  })
  $(document).on("click", function(){
	$(".levelList ").css("display", "none")
	$(".selectDept .arrow").attr("src",iconDown)
	$(".selectLevel .arrow").attr("src",iconDown)
  })
  bindLeveldSelect();
  getTabData(1);
  //给每一个标题绑定一个排序事件
  $("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);
  });
  //查询
  $(".filter").on("click", function(e){
	name = nameTemp
	behospitalCode = behospitalCodeTemp
	level = levelTemp==="全部"?"":levelTemp
	deptId = deptIdTemp
	deptName = deptNameTemp
	doctorName = doctorNameTemp
	doctorNum = doctorNumTemp
	if(deptName == ""){
	  $(".selectDept").attr({'title':"全部",'data-id':''}).val("全部")
	}
	getTabData(1)
  });
  //重置
  $(".abnormalClear").on("click", function(e){
	tabList = [];
	name = "";
	behospitalCode="";
	level="";
	nameTemp = "";
	behospitalCodeTemp="";
	levelTemp="";
	deptNameTemp="";
	deptIdTemp="";
	doctorName=doctorNameUrl=deptNameTemp="";;
	doctorNum="";
	doctorNameTemp="";
	doctorNumTemp="";
	data_desc="behospitalDate"
	data_asc="";
	$('.patientNumInp').val('')
	$('.patientNameInp').val('')
	$('.doctorInp').val('')
	$('.doctorNumInp').val('')

	deptId = deptIdTemp = deptIdPram
	deptName = deptNameTemp = deptNamePram
	$('.selectDept').val(deptNamePram)
	$('.selectDept ').attr('title',deptNamePram)
	$(".deptList").css("display", "none")

	$('.selectLevel').html('全部')
	$(".levelList").css("display", "none")
	$(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
	$("th[code]").removeClass("asc desc")
	$("th[code='behospitalDate']").addClass("desc");
	getTabData(1)
  })
  //导出事件
  $('.export').click(function(){
	let param = {
	  behospitalCode: behospitalCode,     //病历号
	  typeMark:typeMark,     // 0-总数量，1-已改善数量，2-待改善数量
	  patName: name, //病人姓名
	  entryName: defectName,      //缺陷条目名称
	  entryId:casesId,        //缺陷条目id
	  deptId: deptId||"",     //科室id
	  deptName: deptName == "全部" ? "":deptName||"",       //科室名称
	  doctorId: doctorNum,    //医生id
	  doctorName: doctorNameUrl,      //医生姓名
	  level:level,//病历等级
	  startDate: startDateParam, //选择日期--开始时间
	  endDate: endDateParam, //选择日期--结束时间
	  current:1,     //页码
	  asc:data_asc,     //升序
	  desc:data_desc,       //降序
	  size: 500,       //每页显示条数
	};
	expJson(api.getDefectImproveInnerByExport , param,{noPlacefile:true}).then(res => {
	  downloadExportedData(res.data, '条目缺陷改善统计详情'+startDateParam.substr(0,10).replace(/\//g,'')+"-"+endDateParam.substr(0,10).replace(/\//g,'') + ".xls")
	})
  })
});

//判断有无某一权限
  function hasData(data){
    let trdObj = JSON.parse(getLocal("trdObj"))
    let lis = trdObj['YH-BLZK-ZKPF']
    if(!lis){
      return false
    }
    if(lis.indexOf(data)>-1){//有权限
        return true
    }
    return false;
}
function getTabData(activePage){
    const param = {
        behospitalCode: behospitalCode,     //病历号
	    typeMark:typeMark,     // 0-总数量，1-已改善数量，2-待改善数量
        patName: name, //病人姓名
	    entryName: defectName,      //缺陷条目名称
	    entryId:casesId,        //缺陷条目id
	    deptId: deptId||"",     //科室id
        deptName: deptName == "全部" ? "":deptName||"",       //科室名称
        doctorId: doctorNum,    //医生id
        doctorName: doctorNameUrl,      //医生姓名
        level:level,//病历等级
        startDate: startDateParam, //选择日期--开始时间
        endDate: endDateParam, //选择日期--结束时间
        current:activePage,     //页码
        asc:data_asc,     //升序
        desc:data_desc,       //降序
        size: 15,       //每页显示条数
    }
    $('.pagination').html("")
    $('.tbody').html(emptyBox('努力加载中...','',1))
    return post(api.getEntryDefectImproveInner,param,{noPlacefile:true}).then(res =>{
        if(res.data.code == '0'){
            const data = res.data.data;
            tabList = data.records;
            const totalPage = data.pages;
            const totalNum = data.total;
            currentPage = activePage
            renderTab(tabList,data.hospitalId);
		  if(totalNum>0){
			renderPagination(totalPage,Number(activePage),totalNum)
		  }
        }else{
            $.alerModal({"message":res.data.msg,type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
        }
    }).catch((e) =>{
        console.log(999)
    })
}
function getFilterParam(current){
  const param = {
	//"isPlacefile":isPlacefile,
	"deptId": deptName=="全部"?"":deptId||"", //科室id
	"deptName": deptName=="全部"?"":deptName||"",
	"asc":data_asc,     //升序
	"desc":data_desc,       //降序
	"startDate":startDateParam,
	"endDate":endDateParam,
	current
  }
  return param;
}
function renderTab(data,hisId){
    let str = ``
    if(data.length===0){
      $('.tbody').html(emptyBox(null,11))
      return;
    }
    for(let i = 0; i < data.length; i++){
        const item = data[i]
        str += `<tr  data-index=${i}>
                <td >${item.level || "-"}</td>
                <td >${item.scoreRes || "-"}</td>
                <td >${item.behospitalCode || "-"}</td>
                <td >${item.fileCode || "-"}</td>
                <td >${item.name || "-"}</td>
                <td >${item.age || "-"}</td>
                <td >${item.behospitalDate || "-"}</td>
                <td >${item.leaveHospitalDate || "-"}</td>
                <td >${item.doctorName || "-"}</td>
                <td >${item.behDeptName || "-"}</td>
                <td >${item.gradeTime || "-"}</td>
        str += </tr>`
    }
    $('.tbody').html(str)
}

//选择病历等级
$('.selectLevel').on("click", function(e){
    e.stopPropagation()
    $(".deptList ").css("display", "none")
    $(".selectDept .arrow").attr("src",iconDown)
    $(".checkList ").css("display", "none")
    $(".selectCheck .arrow").attr("src",iconDown)
    $(".qcSelectCheck .arrow").attr("src",iconDown)
    $(".qcCheckList ").css("display", "none")
    const showList =  $(".levelList ").css("display")
    if(showList == "none" ||!showList){
        $(".levelList ").css("display","block")
        $(".selectLevel .arrow").attr("src",iconUp)
    }else{
        $(".levelList ").css("display", "none")
        $(".selectLevel .arrow").attr("src",iconDown)
    }
})

//病历等级选择
function bindLeveldSelect(){
    $('.levelItem').on("click",function(){
        const levelItemName = $(this).attr("data-name")
        const levelItemItemId = $(this).attr("data-id")
        levelTemp =levelItemItemId
        $('.selectLevel').html(levelItemName)
        $(".levelList").css("display", "none")
        $(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
        $('.selectLevel').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 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)
        }
    })
    
}