const $ = require('jquery');
require("../css/allotCheckTask.less");
require('./modal.js');
const {api,ywCheckApi} = require('./api.js')
const {post,getCookie,emptyBox,listenScroll,getScoreTabList} = 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 iconRadio=require("./../images/radio.png")
const iconUnRadio=require("./../images/unradio.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")
listenScroll()
let tabList = [], data_desc=["jobCreateTime"],data_asc=[],task_desc=["leaveHospitalDate"],task_asc=[];
let global_DeptCheckers = [],global_Checkers={4:[],5:[],6:[]},
    global_CheckerId='',global_CheckerName='',      //左边质检员选中id，name
    global_CheckerNumId='',global_CheckerNumName='',      //左边质检员数字id，name
    global_checkerFilterName="",//左边核查员名字筛选
    global_DeptId='',//左边质控员科室筛选id
    global_DeptMId="",  //左边质检员选中科室id
    global_DeptNumId='',//左边质检员数字点击科室id
    global_DeptAllId='',    //右边任务科室筛选id(非科室任务才有）
    global_deptData = {},global_activeTabCode='0',
    global_TaskCodes=[],global_TaskDept=[],global_deleted=false,global_score='';
let global_scoreMap = {};  //病历类型枚举

let isPlacefile = getCookie('isPlacefile')||1
/*if(isPlacefile != 1){
    data_desc=["behospital_date"]
}*/

$(function() {
    $(window.parent.document).find(".modaltip").hide();//切换页面过快时toast隐藏
    const checkAuth = getCookie('checkAuth');
    /*if(!checkAuth){
        $(".tabs").hide();
        toast("没有质控核查权限!");
        return
    }*/
    $("#filterToggler").click(function () {
        const text = $(this).text();
        $(".toggle-item").slideToggle();
        $(this).text(text === "收起筛选" ? "展开筛选" : "收起筛选").toggleClass("up");
    });
    const tabs = (checkAuth||'').replace(/[^456]/g,'');
    if(tabs.length===0){
        //$(".tabs").hide();
        toast("没有质控核查权限!");
        return;
    }else if(tabs.length>1){
        //多于一个权限，显示tab切换
        $(".tabs").show();
        const last = "456".replace(tabs,'');
        $(".tabs [data-code="+(last-4)+"]").parent().hide();
    }
    global_activeTabCode=tabs.substr(0,1)-4;
    $(".tabs [data-code="+global_activeTabCode+"]").addClass("active");
    if(global_activeTabCode=='0'){
        $(".patDeptFilter").hide();
    }
    //初始化日期
    $.datepicker.regional['zh-CN'] = {
        clearText: '清除',
        clearStatus: '清除已选日期',
        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']);
    const days = new Date().getDate()-1;
    let startDate = "-"+days+"d",endDate=new Date();
    $( "#datepicker" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy-mm-dd",
    }).datepicker( "setDate", startDate);
    $( "#datepicker2" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy-mm-dd",
    }).datepicker( "setDate",endDate);
    $( "#datepicker3" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy-mm-dd",
    });
    $( "#datepicker4" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy-mm-dd",
    });

    $('.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()
    })
    //保存分配
    $(".save-btn").click(function(){
        allotTask(0);
    })
    //菜单选中状态
    $(".menu .page", parent.document).removeClass("active")
    $(parent.document).find(".menu .page[code=YH-ZKHC-FPHCRW]").addClass("active")
    //表格容器高度计算
    setBoxHeight();
    $(window).resize(function() {
        setBoxHeight();
    });

//切换tab
    $(".tabBox .tabs button").on("click",(e)=>{
        const me = e.target;
        global_checkerFilterName='';    //切换tab清空核查员筛选
        global_activeTabCode = $(me).attr("data-code");
        $(".tabBox .tabs button").removeClass("active");
        $(me).addClass("active");
        if(global_activeTabCode=='0'){
            $(".patDeptFilter").hide();
        }else{
            $(".patDeptFilter").show();
        }
        clearCheckerFilter();
        clearFilter();
        //刷新质控员、任务列表
        //getCheckerList();
        //const data = global_Checkers[+global_activeTabCode+4];
        getCheckerList();
        getTabData(1);
        /*rendeDeptList();
        rendeCheckerList();
        renderCheckerTable();*/
    });

//任务筛选
    $(".filter").on("click", function(e){
        const behosDateStart1 = $("#datepicker").val()         //生成日期
        const behosDateEnd1 = $("#datepicker2").val()
        const behosDateStartTime1 = new Date(behosDateStart1).getTime()
        const behosDateEndTime1 = new Date(behosDateEnd1).getTime()
        const behosDateStart = $("#datepicker3").val()         //出院日期
        const behosDateEnd = $("#datepicker4").val()
        const behosDateStartTime = new Date(behosDateStart).getTime()
        const behosDateEndTime = new Date(behosDateEnd).getTime()
        console.log(222,behosDateStartTime1,behosDateEndTime1)
        if(behosDateStartTime1 > behosDateEndTime1){
            $.alerModal({"message":'生成日期开始时间不能大于结束时间~',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
            return
        }
        if(behosDateStartTime > behosDateEndTime){
            $.alerModal({"message":'出院日期开始时间不能大于结束时间~',type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
            return
        }
        data_desc = ["jobCreateTime"];
        $("th[code]").removeClass("asc desc")
        $("th[code='jobCreateTime']").addClass('desc');
        getTabData(1)
    })
//重置
    $(".abnormalClear").on("click", function(e){
        clearFilter();
        getTabData(1)
    })

//关闭弹窗事件
    $(".modal-container .close").click(function(){
        $(".modal-container").hide();
        global_DeptNumId='';
        global_CheckerNumId='';
        global_CheckerNumName='';
        if(global_deleted){
            //移除后关闭弹窗时清空质控员选中状态：质控员id/name/科室id及右侧选中任务code
            //并刷新左侧和右侧列表
            global_CheckerId='';
            global_CheckerName='';
            global_DeptMId='';
            global_TaskCodes=[];
            getCheckerList();
            getTabData(1);
        }
    });

//科室选择
    $('.selectDept').on("click", function(e){
        e.stopPropagation()
        $(".checkerList ").css("display", "none")
        $(".deptAllList ").css("display","none")
        $(".scoreList ").css("display","none")
        $(".selectChecker .arrow").attr("src",iconDown)
        $(".deptList ").css("display","block")

    })

    //筛选分值选择
    $('.selectScore').on("click", function(e){
        e.stopPropagation();
        $(".deptList ").css("display","none")
        $(".checkerList ").css("display", "none")
        $(".deptAllList ").css("display","none")
        $(".selectDept .arrow").attr("src",iconDown)
        $(".selectScore .arrow").attr("src",iconDown)
        $(".scoreList ").css("display","block")
    })

//病人科室选择
    $('.selectAllDept').on("click", function(e){
        e.stopPropagation()
        $(".checkerList ").css("display", "none")
        $(".scoreList").css("display", "none")
        $(".deptList ").css("display", "none")
        $(".deptAllList ").css("display","block")

    })
//质控员选择
    $('.selectChecker').on("click", function(e){
        e.stopPropagation()
        $(".deptList ").css("display", "none")
        $(".scoreList").css("display", "none")
        $(".checkerList").css("display","block")
    })
//关闭下拉事件
    $(document).on("click", function(){
        $(".deptList ").css("display", "none")
        $(".deptAllList ").css("display", "none")
        $(".checkerList").css("display", "none")
        $(".scoreList").css("display", "none")
        $(".del-pop").remove();
        /*$(".scoreDept .arrow").attr("src",iconDown)
        $(".selectDept .arrow").attr("src",iconDown)
        $(".selectAllDept .arrow").attr("src",iconDown)
        $(".selectChecker .arrow").attr("src",iconDown)*/
    })

    getScoreTabList((data)=>{
	  //调换病历类型键值，以便列表转换用
	  for(let i in data){
		global_scoreMap[data[i]] = i;
	  }
        rendeScoreList(global_scoreMap)
    })
//获取科室列表
    getAllDeptList()

//获取核查人员列表
    getCheckerList()
    getTabData(1)
});

//高度适应
function setBoxHeight() {
    const ht = window.innerHeight;
    let at = 70;
    if($(".tabs:visible").length){  //tab显示时高度
        at=0;
    }
    $('.table-cont').height(ht - (309-at) + 'px');
    $(".patient-table-cont").height(ht - (423-at) + 'px');
    $('.overAuto').height(ht - (249-at) + 'px');
}

//病人列表获取筛选值
function getFilterData(){
    const obj = {};
    $(".overAuto.fr .filterBox input[code]").map((i,it)=>{
        obj[$(it).attr("code")]=$(it).val()
    })
    return obj;
}

//获取分配核查任务列表数据
function getTabData(activePage){
    const filterData = getFilterData();
    let dept = '';
    if(global_activeTabCode!='0'){ //除科室任务外，待分配任务列表科室参数只受筛选项影响
        dept = global_DeptAllId;
    }else{
        dept = global_DeptMId||global_DeptId||global_DeptAllId;
    }
    const deptList=dept.trim()?[dept]:[];
    const param = {
        current:activePage,
        asc:data_asc,     //升序
        desc:data_desc,       //降序
        size: 15,
        jobType:global_activeTabCode,    //0-科室任务 1-院级 2-质控科
        ...filterData,
        deptList:deptList,
        values:global_score.trim()?[global_score]:[],
        endTime:filterData.endTime+" 23:59:59"
    };
    $('.pagination').html("");
    $('.patientTable .tbody').html(emptyBox('努力加载中...','',8))
    return post(ywCheckApi.getAllotCheckList,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)
            renderPagination(totalPage,Number(activePage),totalNum)
            if(totalPage > 0){
                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) =>{

    })
}

function clearCheckerFilter(){
    $('.selectDept i').text('全部')
    $('.selectAllDept i').text('全部')
    $(".deptList").css("display", "none")
    $(".deptAllList").css("display", "none")
    $('.selectChecker i').text('全部')
    $(".checkerList").css("display", "none")
    global_DeptMId="";
    global_DeptId="";
    global_CheckerId="";
    global_CheckerName="";
}

function clearFilter(){
    $(".overAuto.fr input").val("");
    $('.selectAllDept i').text('全部')
    $('.selectAllDept').attr('title','全部')
    $(".deptAllList").css("display", "none")
    $('.selectScore i').html('全部')
    $(".scoreList").css("display", "none")
    global_score='';
    global_DeptAllId="";
    /*if(isPlacefile != 1){
        data_desc=["behospital_date"]
    }*/
    data_asc=[];

    //默认日期为本月
    const days = new Date().getDate()-1;
    let startDate = "-"+days+"d",endDate=new Date();
    $( "#datepicker" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy-mm-dd",
    }).datepicker( "setDate", startDate);
    $( "#datepicker2" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy-mm-dd"
    }).datepicker( "setDate",endDate);
    $( "#datepicker3" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy-mm-dd",
    });
    $( "#datepicker4" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy-mm-dd"
    });
    data_desc=["jobCreateTime"]
    $(".patientTable th[code]").removeClass("asc desc")
    $(".patientTable th[code='jobCreateTime']").addClass('desc');
}
//病人列表排序事件
function bindOrder(){
    $(".patientTable th[code]").off("click").on("click",function(e){
        const code=$(this).attr("code");
        if(data_asc[0]===code){
            data_desc=[code];
            data_asc=[];
            $(".patientTable th[code]").removeClass("asc desc");
            $(this).addClass("desc");
        }else{
            data_desc=[];
            data_asc=[code];
            $(".patientTable th[code]").removeClass("asc desc");
            $(this).addClass("asc");
        }
        getTabData(1);
        // console.log(code)
    });
}
//已分配列表排序事件
function bindTaskOrder(){
    $(".taskTable th[code]").off("click").on("click",function(e){
        const code=$(this).attr("code");
        if(task_asc[0]===code){
            task_desc=[code];
            task_asc=[];
            $(".taskTable th[code]").removeClass("asc desc");
            $(this).addClass("desc");
        }else{
            task_desc=[];
            task_asc=[code];
            $(".taskTable th[code]").removeClass("asc desc");
            $(this).addClass("asc");
        }
        getTasksList();
        // console.log(code)
    });
}
//筛选分值下拉
function rendeScoreList(obj) {
  const list = Object.values(obj);
  if (list.length === 0) {
	$('.scoreList').html("")
	return
  }
    let str = `<li class="scoreItem ellipsis" data-id=" " data-name="全部">全部</li>`;
    for (let i in obj) {
      str += `<li class="scoreItem ellipsis" data-id=${i} data-name=${obj[i]}> ${obj[i]}</li>`
    }
    $('.scoreList').html(str)
    bindScoreSelect()
}
function bindScoreSelect(){
    $('.scoreItem').on("click",function(){
        const scoreItemName = $(this).attr("data-name")
        const scoreItemItemId = $(this).attr("data-id")
        global_score =scoreItemItemId;
        $('.selectScore i').html(scoreItemName)
        $(".scoreList").css("display", "none")
    })
}
//质控员列表渲染
function renderCheckerTable(){
    //console.log(global_DeptId)
    const totalArr = global_DeptId.trim()?global_DeptCheckers[global_DeptId]:global_Checkers[+global_activeTabCode+4];
    let data = totalArr;
    if(global_checkerFilterName){
        data = (totalArr||[]).filter((it)=>global_checkerFilterName===it.doctorName);
    }
    let str = ``,code="";
    global_CheckerId="";
    if(!data||data.length===0){
        $('.checkerTable .tbody').html(emptyBox(null,5))
        //if(!noTasksUpdate){getTabData(1);}
        //   initScroll("qcList","YX",1)
        return;
    }
    //获取任务列表数据
    //if(!noTasksUpdate){getTabData(1);}

    const titles = $(".checkerTable .tabTitle th[valCode]");
    for(let i = 0; i < data.length; i++){
        const item = data[i]

        str += `
            <tr  data-index=${i}>
                <td class="operaItem checkerRadio textCenter" code="${item.doctorId}" data-dept=${item.deptId} data-name="${item.doctorName}"><img src="${iconUnRadio}" alt=""></td>
                `
            for(let i=0;i<titles.length;i++){
                code=$(titles[i]).attr('valCode');
                if(code==="jobNum"){
                    str +=  `<td class="textCenter"><a class="job-num" data-index=${i} data-dept=${item.deptId} data-id="${item.doctorId}" data-name="${item.doctorName}">${ item[code]}</a></td>`
                }else{
                    str +=  `<td class="textCenter"><span data-index=${i} class="dot-over"  title="${ item[code]}">${ item[code]}</span></td>`
                }
            }
        str += "</tr>"
    }
    $('.checkerTable .tbody').html(str);
    selectCheckerTb();
    bindTaskNumEvent();
}
//选中质控员
function selectCheckerTb(){
    $(".checkerRadio").click(function(){
        global_CheckerId=$(this).attr("code");
        global_CheckerName=$(this).attr("data-name");
        global_DeptMId=$(this).attr("data-dept");
        if(global_activeTabCode=='0'){
            global_DeptAllId="";
            getTabData(1)
        }
        $(".checkerRadio img").attr('src',iconUnRadio).removeClass('active');
        $(this).find("img").attr('src',iconRadio).addClass("active");
    });
}
//选中任务
function selectTaskTb(){
    $(".taskCheck").unbind("click").click(function(){
        const id=$(this).attr("code");
        const did=$(this).attr("deptId");
        const it =$(this).find("img");
        const codes = global_TaskCodes.join(",")+",";
        const depts=global_TaskDept.join(",")+",";
        if(it.is(".active")){
            $(this).find("img").attr('src',iconUnCheck);
            $(".allCheck img").attr('src',iconUnCheck).removeClass("active");console.log(codes)
            global_TaskCodes = codes.replace(id+",","").replace(/^,|,$/,'').split(",");
            global_TaskDept = depts.replace(did+",","").replace(/^,|,$/,'').split(",");
        }else{
            $(this).find("img").attr('src',iconCheck);
            global_TaskCodes.push(id);
            global_TaskDept.push(did);
        }
        it.toggleClass('active');

    });

    //全选
    $(".allCheck img").unbind("click").click(function(){
        const checks = $(".taskCheck img");
        if($(this).is(".active")){
            $(this).attr("src",iconUnCheck).removeClass("active");
            checks.attr("src",iconUnCheck).removeClass("active");
            global_TaskCodes=[];
            global_TaskDept=[];
        }else{
            $(this).attr("src",iconCheck).addClass("active");
            checks.attr("src",iconCheck).addClass("active");
            let codes = [],depts=[];
            checks.map((i)=>{
                codes.push($(checks[i]).parent().attr("code"));
                depts.push($(checks[i]).parent().attr("deptid"))
            });
            global_TaskCodes=codes;
            global_TaskDept=depts;
        }
        console.log(global_TaskCodes)

    });
}
//待分配任务列表渲染
function renderTab(data){
    let str = ``,code="";
    global_TaskCodes=[];
    global_TaskDept=[];
    if(!data||data.length===0){
      $('.patientTable .tbody').html(emptyBox(null,8))
    //   initScroll("qcList","YX",1)
      return;
    }
    const titles = $(".patientTable .tabTitle th[valCode]");
    for(let i = 0; i < data.length; i++){
        const item = data[i]

        str += `
            <tr  data-index=${i}>
                <td class="operaItem taskCheck textCenter" code="${item.behospitalCode}" deptId="${item.behospitalDeptId}"><img src="${iconUnCheck}" alt=""></td>`;
        for(let i=0;i<titles.length;i++){
            code=$(titles[i]).attr('valCode');
		  if(code==="value"){
			str += `<td class="textCenter"><span data-index=${i}>${global_scoreMap[+item[code]] || "-"}<span></td>`
		  }else{
			str += `<td class="textCenter"><span data-index=${i}>${item[code] || "-"}<span></td>`
		  }
        }
        str += "</tr>"
    }

    $('.patientTable .tbody').html(str)
    $(".allCheck  img").attr("src",iconUnCheck);    //全选改为可用状态
    selectTaskTb();
    bindOrder()
}
//任务数点击事件
function bindTaskNumEvent(){
    $(".job-num").unbind("click").click(function(){
        global_CheckerNumId = $(this).attr("data-id");
        global_CheckerNumName=$(this).attr("data-name");
        global_DeptNumId=$(this).attr("data-dept");
        $(".modal-container").show();
        global_deleted=false;
        getTasksList();
    })
}
//获取全部科室数据
function getAllDeptList(){
    post(api.getDeptList,{}).then(res =>{
        if(res.data.code == '0'){
           const  deptList = res.data.data||[]
            rendeAllDeptList(deptList)
        }else{rendeAllDeptList([])}
    }).catch((e) =>{

    })
}

function getCheckerList(){
    post(ywCheckApi.getCheckUserMap,{jobType:+global_activeTabCode+4}).then(res =>{
        if(res.data.code == '0'){
            const list = res.data.data||{};
            global_deptData = list;
            formatDeptChecker(list);
        }else{rendeCheckerList([])}
    }).catch((e) =>{

    })
}

//获取质控员任务列表
function getTasksList(){
    post(ywCheckApi.getTaskByUserId,{
        jobType:global_activeTabCode,
        checkId:global_CheckerNumId,
        deptList:global_DeptNumId.trim()?[global_DeptNumId]:[],
        asc:task_asc,
        desc:task_desc,
        size:500,
        current:1}
        ).then(res =>{
        if(res.data.code == '0'){
            const list = res.data.data||{};
            renderTaskTable(list.records);
        }else{rendeCheckerList()}
    }).catch((e) =>{

    })
}

//质控员任务列表渲染
function renderTaskTable(data) {
    let str = ``, code = "";
    if (!data || data.length === 0) {
        $('.taskTable .tbody').html(emptyBox(null, 8))
        return;
    }

    const titles = $(".taskTable .tabTitle th[valCode]");
    const docHide = "name,behospitalDept,attendingDoctor,jobDistributorName";   //过长...的字段
    for (let i = 0; i < data.length; i++) {
        const item = data[i];
        str += `<tr data-index=${i}>`;
        for (let i = 0; i < titles.length; i++) {
            code = $(titles[i]).attr('valCode');
            if(docHide.indexOf(code)>-1){
                str += `<td class="textCenter"><span class="dot-hide" data-index=${i} title="${ item[code]}">${ item[code] || "-"}</span></td>`

            }else if(code === 'leaveHospitalDate'){
                str += `<td class="textCenter"><span class="dot-long-hide" data-index=${i} title="${ item[code]}">${ item[code] || "-"}</span></td>`
            }else if(code === 'value'){
			  str += `<td class="textCenter"><span data-index=${i}>${global_scoreMap[+item[code]] || "-"}<span></td>`
			}else{
                str += `<td class="textCenter"><span data-index=${i} title="${ item[code]}">${ item[code] || "-"}</span></td>`
            }
        }
        str+=`<td class="operaItem textCenter"><a class="delete ${item.delFlag?'':'disable'}" deptId="${item.behospitalDept}" code="${item.behospitalCode}">移除</a></td><tr>`
    }
    $('.taskTable .tbody').html(str);
    bindDeleteEvent();
    bindTaskOrder();
}
//移除任务事件
function bindDeleteEvent(){
    const dom = `<div class="del-pop">
                        <div class="pop-body">
                            <div class="pop-title">确定移除该任务吗？</div>
                            <div class="pop-btns">
                                <button class="del-confirm">确定</button>
                                <button class="cancel">取消</button>
                            </div>
                        </div></div>`;
    $(".taskTable .delete:not(.disable)").unbind("click").click(function(e){
        e.stopPropagation();
        global_TaskCodes=[$(this).attr("code")];
        global_TaskDept=[$(this).attr("deptId")];
        $(".del-pop").remove();
        $(dom).insertAfter($(this)).show();
        $(".del-pop .cancel").unbind("click").click(function(ev){
            ev.stopPropagation();
            $(".del-pop").hide();
        });
        $(".del-pop .del-confirm").unbind("click").click(function(ev){
            ev.stopPropagation();
            global_deleted=true;
            $(".del-pop").hide();
            allotTask(1);
        });
    });
}

//科室筛选质控员
function formatDeptChecker(list){
    const k=+global_activeTabCode +4;
    const allCheckArrs = list[k]||[];
    global_Checkers={4:[],5:[],6:[]}
    allCheckArrs.map((it)=>{
        global_DeptCheckers[it.deptId]=it.deptcheckUsers;
        global_Checkers[k].push(...it.deptcheckUsers);
    });
    rendeDeptList();
    rendeCheckerList();
    //院级任务时科室“全部”不遍历
    if(+global_activeTabCode===2){
        //已有科室筛选，则按科室筛选，无则全部，院级全部为-1
        global_DeptId=global_DeptId.trim()?global_DeptId:'-1';
    }
    renderCheckerTable();
}
//渲染科室列表
function rendeAllDeptList(list){
    if(list.length == 0){
      $(".deptAllList").html("")
      return
    }
    let str = `<li class="deptAllItem ellipsis" data-id="" data-name="全部">全部</li>`;
    for(let i = 0; i < list.length; i++){
        str += `<li class="deptAllItem ellipsis" title=${list[i]['deptName']} data-id=${list[i]['deptId']} data-name=${list[i].deptName}> ${list[i].deptName}</li>`
    }
    $(".deptAllList").html(str)
    bindAllDeptSelect()
}

//渲染当前用户科室列表
function rendeDeptList(){
    const list = global_deptData[+global_activeTabCode+4];
    if(!list||list.length == 0){
        $(".deptList").html("")
        return
    }
    let str = `<li class="deptItem ellipsis" data-id="" data-name="全部">全部</li>`;
    if(+global_activeTabCode===2){
        str=``;
    }
    for(let i = 0; i < list.length; i++){
        str += `<li class="deptItem ellipsis" title=${list[i]['deptName']} data-id=${list[i]['deptId']} data-name=${list[i].deptName}> ${list[i].deptName}</li>`
    }
    $(".deptList").html(str)
    bindDeptSelect()
}


//质控员列表渲染
function rendeCheckerList(lis){
    const data = lis?lis:global_Checkers[+global_activeTabCode+4];
    const list = delRepeatNames(data);
    if(list.length == 0){
        $(".checkerList").html("")
        return
    }
    let str = `<li class="checkerItem ellipsis" data-id=" " data-name="全部">全部</li>`;
    for(let i = 0; i < list.length; i++){
        str += `<li class="checkerItem ellipsis" data-id=${list[i]['doctorId']} data-dept=${list[i]['deptId']} data-name=${list[i].doctorName}> ${list[i].doctorName}</li>`
    }
    $(".checkerList").html(str)
    bindCheckerSelect()
}
function delRepeatNames(arr){
    let obj = {},name="",newArr=[];
    arr.map((it)=>{
        name = it.doctorName;
        if(!obj[name]){
            newArr.push(it);
        }
        obj[name]=true;
    });
    //console.log(newArr)
    return newArr;
}
//质控员列表科室选择
function bindDeptSelect(){
    $('.deptItem').on("mousedown",function(){
        const deptItemName = $(this).attr("data-name")
        global_DeptId = $(this).attr("data-id")
        if(global_activeTabCode=='0'){
            global_DeptAllId="";
        }
        global_DeptMId="";
        global_checkerFilterName='';
        $('.selectDept i').text(deptItemName)
        $('.selectDept').attr('title',deptItemName)
        $(".deptList").css("display", "none")
        //质控员选择清空
        $('.selectChecker i').text('全部')
        $('.selectChecker').attr('title','全部')
        const data = +global_DeptId?global_DeptCheckers[global_DeptId]:global_Checkers[+global_activeTabCode+4];
        console.log(data,global_DeptId)
        rendeCheckerList(data||[]);
        renderCheckerTable();
        global_activeTabCode=='0'&&getTabData(1);
    })
}
//病人列表科室选择
function bindAllDeptSelect(){
    $('.deptAllItem').on("mousedown",function(){
        const deptItemName = $(this).attr("data-name")
        //global_DeptId="";     //7950bug
        //global_DeptMId="";
        global_DeptAllId = $(this).attr("data-id");
        $('.selectAllDept i').text(deptItemName)
        $('.selectAllDept').attr('title',deptItemName)
        $(".deptAllList").css("display", "none")
        //getTabData(1)
    })
}
//质控员选择
function bindCheckerSelect(){
    $('.checkerItem').on("mousedown",function(){
        const itemName = $(this).attr("data-name")
        const itemId = $(this).attr("data-id")
        $('.selectChecker i').text(itemName)
        $('.selectChecker').attr('title',itemName)
        $(".checkerList").css("display", "none")
        if(global_activeTabCode=='0'){
            global_DeptAllId="";
        }
        const totalArr = global_DeptId.trim()?global_DeptCheckers[global_DeptId]:global_Checkers[+global_activeTabCode+4];
        if(!itemId.trim()){
            global_checkerFilterName='';
            renderCheckerTable();
            return
        }
        //const arr = (totalArr||[]).filter((it)=>itemName===it.doctorName);
        global_checkerFilterName=itemName.trim();
        renderCheckerTable();
    })
}
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 allotTask(flag){
    if(flag!==1&&!global_CheckerId){
        toast("请先选择质控员");
        return;
    }
    if((flag!==1&&(!global_TaskCodes.join("").trim())||global_TaskCodes.length===0)){
        toast("请选择至少一个任务");
        return;
    }
    const param = {
        checkId:flag===1?global_CheckerNumId:global_CheckerId,
        checkName:flag===1?global_CheckerNumName:global_CheckerName,
        distributionType:flag,
        behospitalCodes:global_TaskCodes,
        jobType:global_activeTabCode,
        checkDept:global_DeptNumId||global_DeptMId||global_DeptId,
        behospitalDepts:global_TaskDept,

    }
    post(ywCheckApi.allotTask,param).then(res =>{
        if(res.data.code == '0'){
            //分配成功后清空两侧列表选中状态
            global_TaskCodes=[];
            if(flag){
                //移除时更新已分配任务列表弹窗数据,
                // 不刷新核查人和待核查列表，关闭移除弹窗后再更新，避免第1个移除后id被清除
                getTasksList();
            }else{
                global_CheckerId='';
                global_CheckerName='';
                global_DeptMId='';
                getCheckerList();
                getTabData(1);
            }
            toast("操作成功");
        }else{
            const token = localStorage.getItem('accessToken');
            if (!token && window.location.href.indexOf('login') == -1) {
                //alert('无token判断，跳回登录')
            } else {
                toast(res.data.msg || '保存分配失败,请重试~');
            }
        }
    }).catch((e) =>{

    })
}
//气泡提示
function toast(msg) {
    $.alerModal({"message":msg,type:"tip",time:'1000',isFather: true, fatherWrapper: $("#mainBox", parent.document)});
}
//分页渲染
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)
        }
    })

}
