const $ = require('jquery');
require("../css/quexianDetailControl.less");
require('./../resource/jquery-ui/jquery-ui.min.js');
require('./modal.js');
const {api} = require('./api.js')
const {post,getCookie,getUrlArgObjectNew,emptyBox,setDatePicker,getPickerDate} = require('./utils.js')
const switchIconOpen = require("./../images/btn_open.png")
const switchIconClose = require("./../images/btn_close.png")
const iconDown= require("./../images/arrow_down.png")
const iconUp = require("./../images/arrow_up.png")
const arrowLeft= require("./../images/arrow_left.png")
const arrowRight = require("./../images/arrow_right.png")

let casesId="", name="", isReject ="",deptName="",data_asc=[],data_desc=["casesName"], isUsed ="",casesIdTemp="",casesIds="", nameTemp="", isRejectTemp ="", isUsedTemp ="",from="",deptIdTemp="",deptItemId="",deptId=""
$(".selectModuleType").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
$(".selectReject").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
$(".selectUsed").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
$(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
let deptList = []
$(function(){
    dateChange()
    let srcUrl = $("#contentIframe",parent.document).attr("src")
    deptName = getUrlArgObjectNew("deptName",srcUrl)||""
    deptId = deptIdTemp = getUrlArgObjectNew("caseName",srcUrl)||""
    from = getUrlArgObjectNew("from",srcUrl)||""
    isReject = isRejectTemp = getUrlArgObjectNew("shijian",srcUrl)||""
    casesIds = getUrlArgObjectNew("casesId",srcUrl)||""
    let startDateParam = getUrlArgObjectNew("startDateParam",srcUrl)||""
    let endDateParam = getUrlArgObjectNew("endDateParam",srcUrl)||""
    if(isReject == 1){
        $(".monthYear .mon").css({
            backgroundColor:'#00A1FF',
            color:'#fff'
        }).siblings().css({
            color:'#00A1FF',
            backgroundColor:'#fff'
        })
        setDatePicker($("#datepicker"),$("#datepicker2"),1)
    }else if(isReject == 2){
        $(".monthYear .year").css({
            backgroundColor:'#00A1FF',
            color:'#fff'
        }).siblings().css({
            color:'#00A1FF',
            backgroundColor:'#fff'
        })
        setDatePicker($("#datepicker"),$("#datepicker2"),2)
    }else if(isReject == 3){
        setDatePicker($("#datepicker"),$("#datepicker2"),3,new Date(startDateParam),new Date(endDateParam))
    }
    if(!isReject){
        setDatePicker($("#datepicker"),$("#datepicker2"),'default')
    }
    $(".selectDepts").html(deptName)
    // if(from == 1){
        $(".partTitle .titlePic ").html(`<a class="consoleD" href="console.html">控制台 / </a><a class="consoleP" href="deptScoreDetailControl.html">各科室缺陷占比 / </a>缺陷详情`)
        $(".partTitle .consoleD").click(function(){
            $(".menu .page",parent.document).removeClass("active").eq(0).addClass("active");
            $(".container",parent.document).addClass("console-cont");
        })
    // }
    // else{
    //     $(".partTitle .titlePic").html(`<a class="consoleD" href="console.html">控制台 / </a><a class="consoleP" href="deptScoreDetailControl.html">各科室缺陷占比 / </a>缺陷详情`)
    //     $(".partTitle .consoleD").click(function(){
    //         $(".menu .page",parent.document).removeClass("active").eq(0).addClass("active");
    //         $(".container",parent.document).addClass("console-cont");
    //     })
    // }
    getTabData(1)//条目缺陷
    
    $(".abnormalClear").click(function(){
        setDatePicker($("#datepicker"),$("#datepicker2"),"default")
        name =nameTemp= ""
        deptId = deptIdTemp = ""
        $(".selectDept").html("全部").attr("data-id","").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
        $(".patientNumInp").val("")
        getTabData(1)
    })
    getMolist()
})

function getMolist(){
    post(api.getQcCases).then(res =>{
        if(res.data.code == '0'){
            data = res.data.data
            deptList = data
            getDeptList()
        }else{}
    }).catch((e) =>{
    
    })
}
bindDeptSelect()
//科室选择
function bindDeptSelect(){
    $(document).on("click",'.deptItem',function(){
        const deptItemName = $(this).attr("data-name")||""
        const deptItemId = $(this).attr("data-id")
        deptIdTemp = deptId = 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').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)
    }
})

//科室处理

function getDeptList(){
    let str = ``
    if(deptList.length<=0)return
    for(let i = 0;i < deptList.length;i++){
        let tmp = deptList[i]
        str += `<li class="deptItem ellipsis" title="${tmp.name}" data-id="${tmp.name}" data-name="${tmp.name}">${tmp.name}</li>`
    }
    $(".quexianDetailControl .filterDropList").html('<li class="deptItem ellipsis" title="" data-id="" data-id="" data-name="全部">全部</li>'+str)
}

$("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 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,
        type: 0,//1-本月，2-本年,0-自定义时间（现在 都是自定义时间，都会传具体时间进去）
        name: name, //条目名
        doctorName:"",
        casesName:deptId,
        deptName:deptName=="全院"?"":(deptName||""),
        casesId:casesIds||"",
        globalType:1,
        ascs:data_asc,
        descs:data_desc,
        size: 15,
        "startDate":dateStatrt,
        "endDate":dateEnd
    }
    post(api.entryCountGroupByEntryPage,param).then(res =>{
        if(res.data.code == '0'){
            const data = res.data.data.records
            const totalPage = res.data.data.pages
            const totalNum = res.data.data.total
            renderTab(data,activePage)
            if(totalPage > 1){
                renderPagination(totalPage,Number(activePage),totalNum)
            } else{
                $('.pagination').html("")
            }
        }else{}
    }).catch((e) =>{
    
    })
}
//所有数据切换日期筛选
function dateChange(){
    $(".monthYear .mon").click(function(){
        $(this).css({
            backgroundColor:'#00A1FF',
            color:'#fff'
        }).siblings().css({
            color:'#00A1FF',
            backgroundColor:'#fff'
        })
        isReject = isRejectTemp = 1
        setDatePicker($("#datepicker"),$("#datepicker2"),1)
        getTabData(1)
    })
    $(".monthYear .year").click(function(){
        $(this).css({
            backgroundColor:'#00A1FF',
            color:'#fff'
        }).siblings().css({
            color:'#00A1FF',
            backgroundColor:'#fff'
        })
        isReject = isRejectTemp = 2
        setDatePicker($("#datepicker"),$("#datepicker2"),2)
        getTabData(1)
    })
}
//判断有无某一权限
function hasData(data){
    let lis = JSON.parse(getCookie("codeLis"))||[]
    if(lis.indexOf(data)>-1){//有权限
        return true
    }
    return false;
}

$(".moduleItemInp").on("input", function(e){
    const val = $(this).val().trim()
    nameTemp = val
})
$(".filter").on("click", function(e){
    casesId=casesIdTemp, name=nameTemp, isReject =isRejectTemp, isUsed =isUsedTemp,deptId = deptIdTemp
    getTabData(1)
})
$(".filterclear").on("click", function(e){
    nameTemp = ""
    $(".moduleItemInp").val("")
})
$('.selectModuleType').on("click", function(e){
    e.stopPropagation()
    $(".rejectList ").css("display","none")
    $(".usedList ").css("display", "none")
    $(".selectReject .arrow").attr("src",iconDown)
    $(".selectUsed .arrow").attr("src",iconDown)
    const showList =  $(".moduleTypeList ").css("display")
    if(showList == "none" ||!showList){
        $(".moduleTypeList ").css("display","block")
        $(".selectModuleType .arrow").attr("src",iconUp)
    }else{
        $(".moduleTypeList ").css("display", "none")
        $(".selectModuleType .arrow").attr("src",iconDown)
    }
})
$('.selectReject').on("click", function(e){
    e.stopPropagation()
    $(".moduleTypeList ").css("display", "none")
    $(".usedList ").css("display", "none")
    $(".selectModuleType .arrow").attr("src",iconDown)
    $(".selectUsed .arrow").attr("src",iconDown)
    const showList =  $(".rejectList ").css("display")
    if(showList == "none" ||!showList){
        $(".rejectList ").css("display","block")
        $(".selectUsed .arrow").attr("src",iconUp)
    }else{
        $(".rejectList ").css("display", "none")
        $(".selectUsed .arrow").attr("src",iconDown)
    }
})
$('.selectUsed').on("click", function(e){
    e.stopPropagation()
    $(".moduleTypeList ").css("display", "none")
    $(".rejectList ").css("display","none")
    $(".selectModuleType .arrow").attr("src",iconDown)
    $(".selectReject .arrow").attr("src",iconDown)
    const showList =  $(".usedList ").css("display")
    if(showList == "none" ||!showList){
        $(".usedList ").css("display","block")
        $(".selectUsed .arrow").attr("src",iconUp)
    }else{
        $(".usedList ").css("display", "none")
        $(".selectUsed .arrow").attr("src",iconDown)
    }
})
// bindRejectSelect()
// bindUsedSelect()
// getTabData(1)
// getmoduleTypeList()
function renderTab(data,activePage){
    let str = ``;
    const cls = hasData("FUNC000007")?"editItem":"editItemDis";
    for(let i = 0; i < data.length; i++){
        const item = data[i]
        str += `
            <tr data-id=${item.id} data-index=${i}>
                <td  class="textCenter">${(activePage-1)*15 + i+1}</td>
                <td class="textCenter">${item.casesName}</td>
                <td>${item.name}</td>
                <td class="textCenter">${item.num}</td>
                <td  class="textCenter">${item.percentStr}</td>
            </tr>
        `
    }
    $('tbody').html(str?str:emptyBox())
    bindEdit(data,activePage)
}

function bindEdit(data,activePage){
    if(!hasData('FUNC000007')){
        return
    }
    $('.editItem').click(function(e){
        const index = $(this).parent().attr('data-index') 
        editItem(data[index],activePage)
    })
}

//修改
function editItem(item,activePage){
    const itemCpoy = JSON.parse(JSON.stringify(item))
    $('.pop-box').remove()
    $('.container').append('<div class="pop-box"></div>')
    const str = `
        <div class="itemMsgBox">
            <div class="mask"></div>
            <div class="itemMsgContent">
                <p class="itemMsgTitle">修改 <img class="iconClose" src=${require('./../images/icon_close_default.png')} alt="关闭" /></p>
                <div class="itemMsgContentBox">
                    <div class="itemMsgInfoBox"><span class="itemMsgLab">模块名称：</span> <span class="itemInfoRight">${itemCpoy.casesName}</span></div>
                    <div class="itemMsgInfoBox"><span class="itemMsgLab">条目名称：</span> <span class="itemInfoRight"> ${itemCpoy.name}</span></div>
                    <div class="itemMsgInfoBox"><span class="itemMsgLab">提示信息：</span> <span class="itemInfoRight"> <input class="itemTipMsg" value="${itemCpoy.msg}" /></span></div>
                    <div class="itemMsgInfoBox"><span class="itemMsgLab">
                        分值：
                        </span> <span class="itemInfoRight"> 
                            <input class="itemScore" type="number" min="0" value=${itemCpoy.score} />
                        </span>
                        <p class="itemMsgInfoTips">支持≥0的数字输入，最多保留小数点后1位~</p>
                    </div>
                 
                    <div class="itemMsgInfoBox"><span class="itemMsgLab">单项否决：</span><span class="itemInfoRight itemReject">${item.isReject == '1' ? `<img class="switchImg" src=${switchIconOpen} /><span class="imgInfo">  是</span>`:`<img class="switchImg" src=${switchIconClose} /> <span class="imgInfo"> 否</span>`}</span></div>
                    <div class="itemMsgInfoBox"><span class="itemMsgLab">启用：</span><span class=" temInfoRight itemUsed">${item.isUsed == '1' ? `<img class="switchImg" src=${switchIconOpen} /><span class="imgInfo"> 是</span>`:`<img class="switchImg" src=${switchIconClose} /> <span class="imgInfo"> 否</span>`}</span></div>
                </div>
                
                <div class="confirmEditBox"><span class="confirmEdit">保存</span></div>
            </div>
        </div>
       
    `
    $("#mainBox", parent.document).append(str)
    $("#mainBox .itemMsgBox .iconClose", parent.document).on("click", function(e){
        $("#mainBox .itemMsgBox", parent.document).remove()
    })
    $("#mainBox .itemMsgBox .itemTipMsg", parent.document).on("input", function(e){
        const val = $(this).val().trim()
        itemCpoy.msg = val
    })
    $("#mainBox .itemMsgBox .itemScore", parent.document).on("keypress", function(e){
        return (/[0-9\.]/.test(String.fromCharCode(e.keyCode)))
    })
    $("#mainBox .itemMsgBox .itemScore", parent.document).on("input", function(e){
        const val = $(this).val()
        itemCpoy.score = val
    })
    $("#mainBox .itemMsgBox .itemReject", parent.document).on("click", function(e){
        itemCpoy.isReject = itemCpoy.isReject == 1 ? 0 : 1
        $('#mainBox .itemMsgBox', parent.document).remove()
        editItem(itemCpoy,activePage)
    })
    $("#mainBox .itemMsgBox .itemUsed", parent.document).on("click", function(e){
        itemCpoy.isUsed = itemCpoy.isUsed == 1 ? 0 : 1
        $('#mainBox .itemMsgBox', parent.document).remove()
        editItem(itemCpoy,activePage)
    })
    
    $("#mainBox .itemMsgBox .confirmEdit", parent.document).on("click", function(){
        var reg = new RegExp(/^\d+(\.\d)?$/);
        if(reg.test(itemCpoy.score)){
            // console.log('itemCopy', itemCpoy)
            if(!itemCpoy.msg.trim()){
                $.alerModal({"message":"提示信息不能为空~",type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
                return 
            }
            
            saveEdit(itemCpoy,activePage)
            $("#mainBox .itemMsgBox .itemMsgInfoTips", parent.document).css("display","none")
            $('#mainBox .itemMsgBox', parent.document).remove()
            return 
        }else{
            $("#mainBox .itemMsgBox .itemMsgInfoTips", parent.document).css("display","block")
            
            return
        }
      
    })
   
    
}

//保存修改
function saveEdit(item,activePage){
    const param = {
        id: item.id,
        isReject: item.isReject,
        isUsed: item.isUsed,
        msg: item.msg,
        score: item.score
    }

    post(api.updataQcCasesEntry,param).then(res =>{
        if(res.data.code == '0'){
            // const data = res.data.data
            $.alerModal({"message":"修改成功",type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
            getTabData(activePage)
        }else{}
    }).catch((e) =>{
    
    })
}

//获取模块类型
function getmoduleTypeList(){
    post(api.getQcCasesAll).then(res =>{
        if(res.data.code == '0'){
           const  moduleTypeList = res.data.data
           renderModuleTypeList(moduleTypeList)
        }else{}
    }).catch((e) =>{
    
    })
}


function renderModuleTypeList(moduleTypeList){
    let str = `<li class="modeTypeItem " data-id=" " data-name="全部">全部</li>`
    for(let i = 0; i < moduleTypeList.length; i++){
        str += `<li class="modeTypeItem ellipsis" title=${moduleTypeList[i].name} data-id=${moduleTypeList[i].id} data-name=${moduleTypeList[i].name}> ${moduleTypeList[i].name}</li>`
    }
    $('.moduleTypeList').html(str)
    bindModuleTypeSelect()
}

//模块类型选择
function bindModuleTypeSelect(){
    $('.modeTypeItem').on("click",function(){
        const modeTypeItemName = $(this).attr("data-name")
        const modeTypeItemId = $(this).attr("data-id")
        casesIdTemp =modeTypeItemId
        $('.selectModuleType').html(modeTypeItemName).attr("title",modeTypeItemName)
        $(".selectModuleType").append(`<img class="arrow" src=${iconDown} alt="下拉">`)

        $(".moduleTypeList ").css("display", "none")
    })
}
//单项否决选择
function bindRejectSelect(){
    $('.rejectItem').on("click",function(){
        const rejectItemName = $(this).attr("data-name")
        const rejectItemId = $(this).attr("data-id")
        isRejectTemp=rejectItemId
        $('.selectReject').html(rejectItemName)
        $(".rejectList ").css("display", "none")
        $(".selectReject").append(`<img class="arrow" src=${iconDown} alt="下拉">`)

    })
}
//是否启用选择
function bindUsedSelect(){
    $('.usedItem').on("click",function(){
        const usedItemName = $(this).attr("data-name")
        const usedItemItemId = $(this).attr("data-id")
        isUsedTemp =usedItemItemId
        $('.selectUsed').html(usedItemName)
        $(".usedList").css("display", "none")
        $(".selectUsed").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    })
}




//分页渲染
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(){
    $(".moduleTypeList ").css("display", "none")
    $(".rejectList ").css("display","none")
    $(".usedList ").css("display", "none")
    $(".selectModuleType .arrow").attr("src",iconDown)
    $(".selectReject .arrow").attr("src",iconDown)
    $(".selectUsed .arrow").attr("src",iconDown)
    $(".deptList").css("display", "none")
})
$(function() {
    const  iconCalenBlue= require("./../images/darkDate.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()
    })
});