const $ = require('jquery');
require("../css/qcList.less");
require('./modal.js');
const {api} = require('./api.js')
const {post,getCookie} = 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  iconCalenBlue= require("./../images/icon_calen_blue.png")
const  iconCalenGrey= require("./../images/icon_calen_grey.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")

$(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
$(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
let tabList = [], name = "", behospitalCode="", behosDateStart="", level="",behosDateEnd="", scoreSum = 0,
  nameTemp = "", behospitalCodeTemp="",levelTemp="", deptId="",deptIdTemp="", doctorName="", doctorNum="",doctorNameTemp="",doctorNumTemp="",
  data_desc=[],data_asc=[];

$('.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()
})
$('.recordScoreBtn').css("opacity",hasData('FUNC000017')?'1':'0.5')
// $(".abnormalClear").click(function(){
//     window.location.reload()
// })
//判断有无某一权限
  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 param = {
        current:activePage,
        behospitalCode: behospitalCode,
        name: name, //条目名
        level:level,//病历等级
        deptId: deptId,
        asc:data_asc,     //升序
        desc:data_desc,       //降序
        doctorName: doctorName,
        doctorCode: doctorNum,
        leaveHosDateStart: behosDateStart, //1-单项否决 0-非
        leaveHosDateEnd: behosDateEnd, //0-未启用 1-启用
        size: 15
    }
    post(api.qcList,param).then(res =>{
        if(res.data.code == '0'){
            const data = res.data.data;
            tabList = data.records;
            const totalPage = data.pages;
            const totalNum = data.total;
            renderTab(tabList,data.hospitalId);
            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){
    behosDateStart = $("#datepicker").val().trim()
    behosDateEnd = $("#datepicker2").val().trim()
    const start = new Date(behosDateStart).getTime()
    const end = new Date(behosDateEnd).getTime()
    if(start > end){
        $.alerModal({"message":'开始时间不能大于结束时间~',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
        return
    }
    if(behosDateStart){
        behosDateStart = behosDateStart.replace(/\//g,'-') + ' 00:00:00'
    }
    if(behosDateEnd){
        behosDateEnd = behosDateEnd.replace(/\//g,'-') + ' 23:59:59'
    }
    name = nameTemp
    behospitalCode = behospitalCodeTemp
    level = levelTemp==="全部"?"":levelTemp
    deptId = deptIdTemp
    doctorName = doctorNameTemp
    doctorNum = doctorNumTemp
    getTabData(1)
})
$(".abnormalClear").on("click", function(e){
    tabList = []; 
    name = ""; 
    behospitalCode="";  
    behosDateStart="";  
    level=""; 
    behosDateEnd="";  
    scoreSum = 0; 
    nameTemp = "";  
    behospitalCodeTemp=""; 
    levelTemp="";  
    deptId=""; 
    deptIdTemp="";  
    doctorName=""; 
    doctorNum=""; 
    doctorNameTemp=""; 
    doctorNumTemp=""; 
    data_desc=[]; 
    data_asc=[];
    $('.patientNumInp').val('')
    $('.patientNameInp').val('')
    $('.doctorInp').val('')
    $('.doctorNumInp').val('')
    $('.doctorInp').val('')
    $('#datepicker').val('')
    $('#datepicker2').val('')
    $('.selectDept ').html('选择科室')
    $(".deptList").css("display", "none")
    $(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    $('.selectDept ').addClass('unSelect')
    $('.selectLevel').html('选择病历等级')
    $(".levelList").css("display", "none")
    $(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    $('.selectLevel ').addClass('unSelect')
    $("th[code]").removeClass("asc desc")
    getTabData(1)
})
function renderTab(data,hisId){
    let str = ``
    let hasSelectAll = true;
    if(data.length===0){
      $('tbody').html(`<tr><td colspan="17" style="text-align: center;color: #aaa">
          <img style="margin-top:50px;width:100px;" src="${require('../images/empty.png')}" />
          <p style="margin-top:20px;margin-bottom:30px;color:#ccc;position:relative;left:5px;">暂无数据~</p>
      </td></tr>`)
      return;
    }
    for(let i = 0; i < data.length; i++){
        const item = data[i]
        if(!item.hasSelect){
            hasSelectAll = false
        }
        str += `
            <tr  data-index=${i}>
                <td class="scoreOperaItem textCenter">${item.hasSelect ? `<img class="iconCheck" src=${iconCheck} />`:`<img class="iconCheck" src=${iconUnCheck} />`}</td>
                <td  class="recordScoreOperaBtn textCenter" style="opacity:${hasData('FUNC000017')?'1':'0.5'}">评分</td>
                <td >${item.behospitalCode || "-"}</td>
                <td>${item.fileCode || "-"}</td>
                <td  class="textCenter"><span data-index=${i} class="patientNameSpan">${item.name || "-"}<span></td>
                <td  class="textCenter">${item.sex || "-"}</td>
                <td  class="textCenter">${item.age || "-"}</td>
                <td  class="textCenter">${item.bedCode || "-"}</td>
                <td  class="textCenter">${item.behospitalDate&&item.behospitalDate.slice(0,10) || "-"}</td>
                <td  class="textCenter">${item.leaveHospitalDate&&item.leaveHospitalDate.slice(0,10)|| "-"}</td>
                <td  class="textCenter">${item.behDoctorName   || "-"}</td>
                <td  class="textCenter">${item.doctorName || "-"}</td>
                <td  class="textCenter">${item.directorDoctorName || "-"}</td>
                <td  class="textCenter">${item.behDeptName || "-"}</td>
                <td  class="textCenter">${item.level || "-"}</td>
                <td  class="textCenter">${item.scoreRes || "-"}</td>
                <td  class="textCenter">${item.gradeTime&&item.gradeTime.slice(0,10) || "-"}</td>
            </tr>
        `
    }
    if(data.length === 0){
        hasSelectAll = false
    }
    if(hasSelectAll){
        $('.scoreOpera img').attr("src" ,iconCheck)
        $('.scoreOpera').attr("data-selectall",true)
    }else{
        $('.scoreOpera img').attr("src" ,iconUnCheck)
        $('.scoreOpera').attr("data-selectall",false)
    }
    $('tbody').html(str)
    bindScoreOperaItem()
    bindRecordScoreOper()
    bindScoreDetail(hisId)
}

function scoreDetail(id,age,hid,code){
    window.open(`./qcScore.html?id=${id}&age=${age}&hid=${hid}&code=${code}`)
}
function bindScoreDetail(hisId){
    $('.patientNameSpan').on('click',function(e){
        const index = $(this).attr("data-index")
        const id = tabList[index].behospitalCode
        const age = tabList[index].age;
        const noScore = tabList[index].level == '未评分'
        if(noScore){
            $.alerModal({"message":'请先进行评分！',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
            return
        } else{
            scoreDetail(id,age,hisId,'YH-BLZK-ZKPF')
        }
       
    })
}

//选择病历等级
$('.selectLevel').on("click", function(e){
    e.stopPropagation()
    $(".deptList ").css("display", "none")
    $(".selectDept .arrow").attr("src",iconDown)
    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)
    }
})

bindLeveldSelect()
//是否启用选择
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')
    })
}

//全选绑定
bindOperaAll()
function bindScoreOperaItem(){
    $(".scoreOperaItem").on("click",  function(e){
        const index = $(this).parent().attr("data-index")
        tabList[index].hasSelect = tabList[index].hasSelect ? false:true
        renderTab(tabList)
    })
}
function bindRecordScoreOper(){
    $(".recordScoreOperaBtn").on("click",  function(e){
        if(!hasData('FUNC000017')){
            return
        }
        const index = $(this).parent().attr("data-index")
        const behospitalCode = tabList[index].behospitalCode
        loading()
        recordScore(behospitalCode,1,true)
    })
}
function bindOperaAll(){
    $('.scoreOpera').on("click", function(e){
        const hasSelectAll = $('.scoreOpera').attr("data-selectall")
        if(hasSelectAll == 'true'){

            for(let i = 0; i < tabList.length; i++){
                tabList[i].hasSelect = false
            }
        }else{
            for(let i = 0; i < tabList.length; i++){
                tabList[i].hasSelect = true
            }
        }
        renderTab(tabList)
    })
}

$('.selectDept').on("click", function(e){
    e.stopPropagation()
    $(".levelList ").css("display","none")
    $(".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)
    }
})

//获取科室列表
getDeptList()
function getDeptList(){
    post(api.getDeptList,{inputStr:""}).then(res =>{
        if(res.data.code == '0'){
           const  deptList = res.data.data
           rendeDeptList(deptList)
        }else{}
    }).catch((e) =>{

    })
}


function rendeDeptList(deptList){
    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("click",function(){
        const deptItemName = $(this).attr("data-name")
        const deptItemId = $(this).attr("data-id")
        deptIdTemp =deptItemId
        if(deptItemName.length > 10){
            $('.selectDept').html(deptItemName.substring(0,8)+'...')
        }else{
            $('.selectDept').html(deptItemName)
        }
        $('.selectDept ').attr('title',deptItemName)
        $(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
        $(".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()
}
$('.recordScoreBtn').on("click",function(e){
    if(!hasData('FUNC000017')){
        return
    }
    let scoreList = []
    for(let i = 0; i <tabList.length; i++){
        if(tabList[i].hasSelect){
            scoreList.push(tabList[i].behospitalCode)
        }
    }
    if(scoreList.length === 0){
        $.alerModal({"message":'请选择要评分的项！',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
        return
    } else{
        loading()
        for(let j = 0; j < scoreList.length; j++){
            recordScore(scoreList[j],scoreList.length,true)
        }
    }
})
$("th[code]").on("click",function(e){
    const code=$(this).attr("code");
    if(data_asc[0]===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);
    // console.log(code)
});
function recordScore(behospitalCode,totalNum,hasToast){
    const param = {
        behospitalCode: behospitalCode
    }
    post(api.recordScore,param).then(res =>{
        if(res.data.code == '0'){
            scoreSum++
            if(scoreSum === totalNum){
                hideLoading()
                scoreSum = 0
                const activePage = $(".activePage").attr('data-page') || 1

                getTabData(activePage)
                if(hasToast){
                  $.alerModal({"message":'评分成功',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
                }
            }
            
        }else{
            hideLoading()
            if(hasToast){
                $.alerModal({"message":'评分失败',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
            }
        }
    }).catch((e) =>{
        hideLoading()
        if(hasToast){
            $.alerModal({"message":'评分失败',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
        }
    })
}
$(".patientNumInp").on("input", function(e){
    const val = $(this).val().trim()
    behospitalCodeTemp = val
})
$(".patientNameInp").on("input", function(e){
    const val = $(this).val().trim()
    nameTemp = val
})
$(".doctorInp").on("input", function(e){
    const val = $(this).val().trim()
    doctorNameTemp = val
})
$(".doctorNumInp").on("input", function(e){
  const val = $(this).val().trim();
    doctorNumTemp = val
})
$(function() {
    $.datepicker.regional['zh-CN'] = {
    clearText: '清除',
    clearStatus: '清除已选e799bee5baa6e59b9ee7ad9431333361303131日期',
    closeText: '关闭',
    closeStatus: '不改变当前选择',
    prevText: '<上月',
    prevStatus: '显示上月',
    prevBigText: '<<',
    prevBigStatus: '显示上一年',
    nextText: '下月>',
    nextStatus: '显示下月',
    nextBigText: '>>',
    nextBigStatus: '显示下一年',
    currentText: '今天',
    currentStatus: '显示本月',
    monthNames: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'],
    monthNamesShort: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'],
    yearNamesShort: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'],
    monthStatus: '选择月份',
    yearStatus: '选择年份',
    weekHeader: '周',
    weekStatus: '年内周次',
    dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
    dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
    dayNamesMin: ['日','一','二','三','四','五','六'],
    dayStatus: '设置 DD 为一周起始',
    dateStatus: '选择 m月 d日, DD',
    dateFormat: 'yy-mm-dd',
    firstDay: 1,
    initStatus: '请选择日期',
    isRTL: false};
    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);

    $( "#datepicker" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy/mm/dd",
    }).datepicker( "setDate", "-1m" );
    $( "#datepicker2" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy/mm/dd"
    }).datepicker( "setDate", new Date());
    $(".filter").click();   //初始查询
});

//分页渲染
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)
        }
    })
    
}

$(document).on("click", function(){
    $(".levelList ").css("display", "none")
    $(".deptList").css("display", "none")
    $(".selectLevel .arrow").attr("src",iconDown)
    
})

$((function($){
})($));