const $ = require('jquery');
require("../css/creatCheckTask.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 iconDisCheck = require("./../images/icon_dis.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 = [], global_level = "", global_status = "0",
    global_deptId = [], global_deptName = "", global_score = '',
    data_desc = ["leaveHospitalDate"], data_asc = [], global_taskList = [], global_delOrAdd = 1;//1生成0取消
let global_activeTabCode = '0';    //激活的tab  code
let global_scoreMap = {};  //病历类型枚举
let isPlacefile = getCookie('isPlacefile') || 1

$(function () {
    $(window.parent.document).find(".modaltip").hide();//切换页面过快时toast隐藏
    const checkAuth = getCookie('checkAuth');
    /*if(!checkAuth){
        $(".tabs").hide();
        toast("没有质控核查权限!");
        return
    }*/
    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;
    //获取科室列表
    if (global_activeTabCode == "0") {
        getSubDeptList();
    } else {
        getDeptList();
    }
    $(".tabs [data-code=" + global_activeTabCode + "]").addClass("active");
    $('.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-SCHCRW]").addClass("active")

    $(".filter").on("click", function (e) {
        global_taskList = [];
        const isCreated = (global_status == "1");
        const text = isCreated ? '取消' : '生成';
        $(".modal-body p").text("确定要" + text + "这些任务吗？");
        $("th[code]").removeClass("asc desc");
        if (isCreated) {
            $(".creatTask").addClass("disabled");
            $(".cancelTask").removeClass("disabled");
        } else {
            $(".creatTask").removeClass("disabled");
            $(".cancelTask").addClass("disabled");
        }

        //已生成筛选时按生成日期倒序筛选
        if (isCreated) {
            global_delOrAdd = 0;
            data_desc = ["jobCreateTime"];
            $("th[code=jobCreateTime]").addClass("desc");
            $("th[code=leaveHospitalDate]").removeClass("desc");
        } else {
            global_delOrAdd = 1;
            data_desc = ["leaveHospitalDate"];
            $("th[code=leaveHospitalDate]").addClass("desc");
            $("th[code=jobCreateTime]").removeClass("desc");
        }
        getTabData(1)
    })
    $(".abnormalClear").on("click", function (e) {
        clearFilter();
        getTabData(1)
    })
    //切换tab
    $(".tabBox .tabs button").on("click", (e) => {
        const me = e.target;
        $('.selectDept i').text('全部')
        $(".deptItem.active").removeClass("active");
        $(".deptList").css("display", "none")
        global_deptId = [];
        global_deptName = "";
        global_activeTabCode = $(me).attr("data-code");
        if (global_activeTabCode == "0") {
            getSubDeptList();
        } else {
            getDeptList();
        }
        $(".tabBox .tabs button").removeClass("active");
        $(me).addClass("active");
        //更新列表并重置筛选条件
        $(".filter").click();
    });
    //选择生成状态
    $('.selectStatus').on("click", function (e) {
        e.stopPropagation()
        const showList = $(".statusList ").css("display")
        if (showList == "none" || !showList) {
            $(".levelList ").css("display", "none")
            $(".deptList ").css("display", "none")
            $(".scoreList ").css("display", "none")
            $(".statusList ").css("display", "block")
        } else {
            $(".statusList ").css("display", "none")
        }
    })
    //选择病历等级
    $('.selectLevel').on("click", function (e) {
        e.stopPropagation()
        $(".deptList ").css("display", "none")
        const showList = $(".levelList ").css("display")
        if (showList == "none" || !showList) {
            $(".deptList ").css("display", "none")
            $(".statusList ").css("display", "none")
            $(".scoreList ").css("display", "none")
            $(".levelList ").css("display", "block")
        } else {
            $(".levelList ").css("display", "none")
        }
    })
    //科室选择
    $('.selectDept').on("click", function (e) {
        e.stopPropagation();
        $(".levelList ").css("display", "none")
        $(".statusList ").css("display", "none")
        $(".scoreList ").css("display", "none")
        $(".deptList ").css("display", "block")
    })

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

    $(".creatTask,.cancelTask").click(function () {
        if ($(this).is(".disabled")) {
            return;
        }
        if (!global_taskList.join("").length) {
            toast("至少勾选一个任务");
            return;
        }
        $(".modal-container").show();
    });
    $(".modal-container .confirm").click(function () {
        creatTask(global_delOrAdd)
    });
    $(".modal-container .cancel,.modal-container .close").click(function () {
        /*if(global_delOrAdd==0){
            global_taskList=[];
        }*/
        $(".modal-container").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
    };
    const days = new Date().getDate() - 1;
    let startDate = "-" + days + "d", endDate = new Date();
    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#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);
    getScoreTabList((data) => {
        //调换病历类型键值，以便列表转换用
        for(let i in data){
		  global_scoreMap[data[i]] = i;
        }
        rendeScoreList(global_scoreMap)
    })
    //获取列表数据
    getTabData(1)
    //状态选择
    bindStatusSelect()
    //等级选择
    bindLeveldSelect()
    //关闭下拉
    $(document).on("click", function () {
        $(".levelList ").css("display", "none")
        $(".deptList ").css("display", "none")
        $(".statusList ").css("display", "none")
        $(".scoreList ").css("display", "none")
    })
});
//判断有无某一权限
function hasData(data) {
    let trdObj = JSON.parse(getLocal("trdObj"))
    let lis = trdObj['YH-ZKHC-SCRW']
    if (!lis) {
        return false
    }
    if (lis.indexOf(data) > -1) {//有权限
        return true
    }
    return false;
}

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 bindOrder() {
    $("th[code]").off("click").on("click", function (e) {
        const code = $(this).attr("code");
        if (data_asc[0] === 'age') {

        } else {

        }
        if ((data_asc[0] === code && code !== 'age') || (data_desc[0] === 'birthday' && code == 'age')) {
            if (code == 'age') {
                $("th[code]").removeClass("asc desc");
                $(this).addClass("desc");
                data_desc = [];
                data_asc = ['birthday'];
            } else {
                $("th[code]").removeClass("asc desc");
                $(this).addClass("desc");
                data_desc = [code];
                data_asc = [];
            }
        } else {
            if (code == 'age') {
                $("th[code]").removeClass("asc desc");
                $(this).addClass("asc");
                data_desc = ['birthday'];
                data_asc = [];
            } else {
                $("th[code]").removeClass("asc desc");
                $(this).addClass("asc");
                data_desc = [];
                data_asc = [code];
            }

        }

        getTabData(1);
    });
}
function bindCancelTaskEvent() {
    $(".taskCancel").unbind("click").click(function () {
        global_delOrAdd = 0;
        global_taskList = [$(this).attr("code")];
        $(".modal-container .modal-body p").text("确定要取消该任务吗？");
        $(".modal-container").show();
    });
}

//生成任务
function creatTask() {
    const param = {
        behospitalCodeList: global_taskList,
        jobType: global_activeTabCode,
        checkStatus: global_delOrAdd,
    };
    post(ywCheckApi.addCheck, param).then(res => {
        if (res.data.code == '0') {
            global_taskList = [];
            $(".modal-container").hide();
            toast("操作成功！");
            getTabData(1)
        } else {
            toast(res.data.msg);
        }
    }).catch((e) => {

    })
}

function getTabData(activePage) {
    const filterData = getFilterData();
    const { smallDay, bigDay, startDate, endDate } = filterData;
    if (+smallDay > +bigDay) {
        toast("住院天数区间有误~");
        return;
    }
    if (new Date(startDate).getTime() > new Date(endDate).getTime()) {
        toast("出院日期开始时间不能大于结束时间~");
        return;
    }
    const param = {
        jobType: global_activeTabCode,     //科室/质控科/院级
        creatStatus: global_status,
        current: activePage,
        hospitalId: '',
        level: global_level,//病历等级
        values: global_score.trim() ? [global_score] : [],
        department: global_deptId,
        asc: data_asc,     //升序
        desc: data_desc,       //降序
        size: 15,
        ...filterData,
        startDate: filterData.startDate + " 00:00:00",
        endDate: filterData.endDate + " 23:59:59",
    }
    $('.pagination').html("")
    $('.tbody').html(emptyBox('努力加载中...', '', 17))
    return post(ywCheckApi.getTaskList, 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 > 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 {
                toast(res.data.msg);
            }

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

    })
}

function toast(msg) {
    $.alerModal({ "message": msg, type: "tip", time: '1000', isFather: true, fatherWrapper: $("#mainBox", parent.document) });
}

function renderTab(data) {
    let str = ``, code = "";
    let hasSelectAll = true;
    if (data.length === 0) {
        $('.tbody').html(emptyBox(null, 17))
        //   initScroll("qcList","YX",1)
        return;
    }
    const titles = $(".tabTitle th[code]");
    for (let i = 0; i < data.length; i++) {
        const item = data[i]

        str += `
            <tr  data-index=${i}>
                <td class="operaItem taskCheck textCenter"><img code="${item.behospitalCode}" src="${iconUnCheck}" alt=""></td>`;
        for (let i = 0; i < titles.length; i++) {
            code = $(titles[i]).attr('code');
            if(code==="score"){
			  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 += `<td class="operaItem textCenter ${(item.creatStatus == '已生成' && item.delFlag) ? 'taskCancel' : 'disable'}" code="${item.behospitalCode}">取消</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)
    $(".allCheck  img").attr("src", iconUnCheck);    //全选改为可用状态
    bindOrder();
    bindTaskCheckEvent();
    bindCancelTaskEvent();
}

function bindTaskCheckEvent() {
    $(".taskCheck img").unbind("click").click(function () {
        const code = $(this).attr("code");
        if ($(this).is(".active")) {
            let str = global_taskList.join(",") + ",";
            str = str.replace(code + ",", "").replace(/^,|,$/, '');
            global_taskList = str.split(",");
            $(".allCheck img").attr('src', iconUnCheck).removeClass("active");
            $(this).attr('src', iconUnCheck).removeClass("active");
        } else {
            global_taskList.push(code);
            $(this).attr('src', iconCheck).addClass("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_taskList = [];
        } else {
            $(this).attr("src", iconCheck).addClass("active");
            checks.attr("src", iconCheck).addClass("active");
            let codes = [];
            checks.map((i) => {
                codes.push($(checks[i]).attr("code"));
            });
            global_taskList = codes;
        }
        console.log(global_taskList)

    });
}

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

//生成状态选择
function bindStatusSelect() {
    $('.statusItem').on("click", function () {
        const statusItemName = $(this).attr("data-name")
        global_status = $(this).attr("data-id")
        $('.selectStatus i').html(statusItemName)
        $(".statusList").css("display", "none")
        $('.selectStatus').removeClass('unSelect')
    })
}

//病历等级选择
function bindLeveldSelect() {
    $('.levelItem').on("click", function () {
        const levelItemName = $(this).attr("data-name")
        const levelItemItemId = $(this).attr("data-id")
        global_level = levelItemItemId
        $('.selectLevel i').html(levelItemName)
        $(".levelList").css("display", "none")
        //$(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    })
}
//获取科室任务对应的列表
function getSubDeptList() {
    post(api.getDept, {}).then(res => {
        if (res.data.code == '0') {
            const deptList = res.data.data || []
            rendeDeptList(deptList)
        } else { rendeDeptList([]) }
    }).catch((e) => {

    })
}
//科室列表
function getDeptList() {
    post(api.getDeptList, {}).then(res => {
        if (res.data.code == '0') {
            const deptList = res.data.data || []
            rendeDeptList(deptList)
        } else { rendeDeptList([]) }
    }).catch((e) => {

    })
}
function rendeDeptList(deptList) {
    if (deptList.length == 0) {
        $('.deptList').html("")
        return
    }
    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 (e) {
        e.stopPropagation();
        const deptItemName = $(this).attr("data-name");
        let str = global_deptId.join(",") + ",";
        const code = $(this).attr("data-id")
        if (!code.trim()) {
            $(".deptItem").removeClass("active");
            global_deptId = [];
            global_deptName = "";
            $('.selectDept i').text('全部')
            $('.selectDept').attr('title', '全部')
            return;
        }
        if ($(this).is(".active")) {
            global_deptName = global_deptName.replace(deptItemName + ",", '');
            str = str.replace(code + ",", "").replace(/^,|,$/, '');
            global_deptId = str.split(",");
        } else {
            global_deptName = global_deptName + deptItemName + ",";
            global_deptId.push(code);
        }
        $(this).toggleClass("active");
        const name = global_deptName.replace(/,$/, '');
        $('.selectDept i').text(name)
        $('.selectDept').attr('title', name)
    })
}
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 clearFilter() {
    const days = new Date().getDate() - 1;
    let startDate = "-" + days + "d", endDate = new Date();
    $(".creatTask").removeClass("disabled");
    $(".cancelTask").addClass("disabled");
    $(".filterBox input").val("");
    data_desc = ["leaveHospitalDate"];
    //默认日期为本月
    $("#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);
    $('.selectDept i').text('全部')
    $(".deptItem.active").removeClass("active");
    $(".deptList").css("display", "none")
    global_deptId = [];
    global_deptName = "";
    $('.selectLevel i').html('全部')
    $(".levelList").css("display", "none")
    global_level = "";
    $('.selectStatus i').html('未生成')
    $(".statusList").css("display", "none")
    $('.selectScore i').html('全部')
    $(".scoreList").css("display", "none")
    global_score = '';
    global_status = '0'
    $("th[code]").removeClass("asc desc")
}

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

}
