const $ = require('jquery');
require("../css/checkTaskList.less");
require('./modal.js');
const { api, ywCheckApi } = require('./api.js')
const { post, getCookie, getLogoParam, emptyBox, listenScroll, getScoreTabList } = require('./utils.js')
require('./../resource/jquery-ui/jquery-ui.min.js');
require('./../resource/jquery-ui/jquery-ui.min.css');
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()
$(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
$(".selectStatus").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
$(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`)

let tabList = [], global_deptId = "", global_checkStatus = "", global_score = '', global_level = "", data_desc = ["jobDistributionTime"], data_asc = [];
let isPlacefile = getCookie('isPlacefile') || 1
if (isPlacefile != 1) {
    data_desc = ["jobDistributionTime"]
}

$(function () {
    $(window.parent.document).find(".modaltip").hide();//切换页面过快时toast隐藏
    $('.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()
    })
    //菜单选中
    $(".menu .page", parent.document).removeClass("active")
    $(parent.document).find(".menu .page[code=YH-ZKHC-HCRWLB]").addClass("active")

    //日期初始化
    $.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();
    //let endDate = new Date(),startDate = "-6d";
    $("#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);
    //getPageSet().then(res =>{
    $(".filter").click();   //初始查询
    //})
    //选择病历等级
    $('.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)
        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)
        }
    })

    //选择核查状态
    $('.selectStatus').on("click", function (e) {
        e.stopPropagation()
        $(".scoreList").css("display", "none")
        $(".levelList").css("display", "none")
        $(".deptList ").css("display", "none")
        $(".selectDept .arrow").attr("src", iconDown)
        $(".selectCheck .arrow").attr("src", iconDown)
        const showList = $(".statusList").css("display")
        if (showList == "none" || !showList) {
            $(".statusList").css("display", "block")
            $(".selectStatus .arrow").attr("src", iconUp)
        } else {
            $(".statusList").css("display", "none")
            $(".selectStatus .arrow").attr("src", iconDown)
        }
    })

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

    //筛选
    $(".filter").on("click", function () {
        const filterData = getFilterData();
        const behosDateStartTime = new Date(filterData.jobDistributionTimeStart).getTime()
        const behosDateEndTime = new Date(filterData.jobDistributionTimeEnd).getTime()
        if (behosDateStartTime > behosDateEndTime) {
            $.alerModal({ "message": '生成日期开始时间不能大于结束时间~', type: "tip", time: '1000', isFather: true, fatherWrapper: $("#mainBox", parent.document) });
            return
        }
        data_desc = ["jobDistributionTime"];
        $("th[code]").removeClass("asc desc")
        $("th[code='jobDistributionTime']").addClass('desc');
        getTabData(1)
    })

    $(".abnormalClear").on("click", function (e) {
        clearFilter();
        getTabData(1)
    })
    getScoreTabList((data) => { rendeScoreList(data) }, true)
    getTabData(1)
    bindLeveldSelect()
    bindStatusdSelect()

    $('.selectDept').on("click", function (e) {
        e.stopPropagation()
        $(".levelList ").css("display", "none")
        $(".scoreList").css("display", "none")
        $(".selectLevel .arrow").attr("src", iconDown)
        $(".statusList").css("display", "none")
        $(".selectStatus .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)
        }
    })

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


    //获取科室列表
    getDeptList()
})

//判断有无某一权限
function hasData(data) {
    let trdObj = JSON.parse(getCookie("trdObj"))
    let lis = trdObj['YH-ZKHC-HCRWLB']
    if (!lis) {
        return false
    }
    if (lis.indexOf(data) > -1) {//有权限
        return true
    }
    return false;
}
//列表获取筛选值
function getFilterData() {
    const obj = {};
    $(".filterBox input[code]").map((i, it) => {
        obj[$(it).attr("code")] = $(it).val()
    })
    return obj;
}
//重置筛选项
function clearFilter() {
    $(".filterBox input").val("");
    data_desc = ["jobDistributionTime"];
    /*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);
    $("th[code]").removeClass("asc desc")
    $("th[code='jobDistributionTime']").addClass('desc');

    $('.selectDept ').html('全部')
    $(".deptList").css("display", "none")
    $(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    global_deptId = "";

    $('.selectLevel').html('全部')
    $(".levelList").css("display", "none")
    $(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    global_level = "";

    $('.selectStatus').html('全部')
    $(".statusList").css("display", "none")
    $(".selectStatus").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    global_checkStatus = "";

    $('.selectScore i').html('全部')
    $(".scoreList").css("display", "none")
    global_score = '';
}
function getTabData(activePage) {
    const filterData = getFilterData();
    const param = {
        level: global_level,//病历等级
        asc: data_asc,     //升序
        desc: data_desc,       //降序
        size: 15,
        current: activePage,
        ...filterData,
        checkJobTypes: global_score.trim() ? [global_score] : [],
        behDeptId: global_deptId.trim(),
        status: global_checkStatus,
        jobDistributionTimeStart: filterData.jobDistributionTimeStart + " 00:00:00",
        jobDistributionTimeEnd: filterData.jobDistributionTimeEnd + " 23:59:59"
    }
    $('.pagination').html("")
    $('.tbody').html(emptyBox('努力加载中...', '', 15))
    return post(ywCheckApi.getUserList, param).then(res => {
        if (res.data.code == '0') {
            tabList = res.data.data.records
            const totalPage = res.data.data.pages
            const totalNum = res.data.data.total
            renderTab(tabList, activePage)
            renderPagination(totalPage, Number(activePage), totalNum)
            if (totalPage > 0) {
                renderPagination(totalPage, Number(activePage), totalNum)
            } else {
                $('.pagination').html("")
            }
        } else {
            const token = localStorage.getItem('accessToken');
            if (!token && window.location.href.indexOf('login') == -1) {
                //alert('无token判断，跳回登录')
            } else {
                $.alerModal({ "message": res.data.msg, type: "tip", time: '1000', isFather: true, fatherWrapper: $("#mainBox", parent.document) });
            }

        }
    }).catch((e) => {

    })
}
//排序事件
function bindOrder() {
    $("th[code]").off("click").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);
    });
}

//来源筛选下拉
function rendeScoreList(list) {
    console.log(list)
    const arr = Object.keys(list);
    if (arr.length == 0) {
        $('.scoreList').html("")
        return
    }
    let str = `<li class="scoreItem ellipsis" data-id=" " data-name="全部">全部</li>`;
    for (let i = 0; i < arr.length; i++) {
        str += `<li class="scoreItem ellipsis" data-id=${arr[i]} data-name=${list[arr[i]]}> ${list[arr[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 renderTab(data) {
    let str = ``, code = "";
    if (data.length === 0) {
        $('.tbody').html(emptyBox(null, 15))
        return;
    }
    const titles = $(".tabTitle th[code]");
    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('code');
            str += `<td class="${code == 'name' ? 'beHospitalId' : ''} textCenter"><span data-index=${i}>${item[code] || "-"}<span></td>`
        }
        str += "</tr>"
    }
    $('.tbody').html(str)
    bindScoreDetail()
    bindOrder()
}

function bindScoreDetail() {
    $('.tbody').unbind("click").on('click', 'tr .beHospitalId', function (e) {
        console.log(tabList)
        console.log($(this).parent().index())
        const index = $(this).parent().index()
        const id = tabList[index].behospitalCode
        const name = tabList[index].name
        const age = tabList[index].age;
        const checkStatus = tabList[index].checkStatus
        scoreDetail({ id, age, name, hid: getCookie("hospitalid"), code: 'YH-ZKHC-HCRWLB' })
    });
}
function scoreDetail(obj) {
    const logoParam = getLogoParam();
    window.open(`./qcScore.html?id=${obj.id}&age=${obj.age}&name=${obj.name}&hid=${obj.hid}&code=${obj.code}` + logoParam)
}
//病历等级选择
function bindLeveldSelect() {
    $('.levelItem').on("click", function () {
        const levelItemName = $(this).attr("data-name")
        global_level = $(this).attr("data-id")
        $('.selectLevel').html(levelItemName)
        $(".levelList").css("display", "none")
        $(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    })
}

//病历核查状态选中
function bindStatusdSelect() {
    $('.statusItem').on("click", function () {
        const levelItemName = $(this).attr("data-name")
        global_checkStatus = $(this).attr("data-id")
        $('.selectStatus').html(levelItemName)
        $(".statusList").css("display", "none")
        $(".selectStatus").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    })
}

function getDeptList() {
    post(api.getDeptList, {}).then(res => {
        if (res.data.code == '0') {
            const deptList = res.data.data
            rendeDeptList(deptList)
        } else { }
    }).catch((e) => {

    })
}

function rendeDeptList(deptList) {
    //console.log(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")
        global_deptId = $(this).attr("data-id")
        if (deptItemName.length > 10) {
            $('.selectDept').text(deptItemName.substring(0, 8) + '...')
        } else {
            $('.selectDept').text(deptItemName)
        }
        $('.selectDept ').text(deptItemName).attr('title', deptItemName)
        $(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
        $(".deptList").css("display", "none")
    })
}
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 () {

});

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

}