const $ = require('jquery');
require("../css/doctorQcAverageDetail.less");
require('./modal.js');
const { api } = require('./api.js')
const { post, getCookie, getUrlArgObjectNew, focusMenuItem, emptyBox, setDatePicker, getPickerDate, downloadExportedData, expJson, initScroll, listenScroll } = require('./utils.js')
require('./../resource/jquery-ui/jquery-ui.min.js');
require('./../resource/jquery-ui/jquery-ui.min.css');
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")
const jiantou_up = require("./../images/jiantou_up.png")
const jiantou_down = require("./../images/jiantou_down.png")
let isPlacefile = getCookie('isPlacefile') || 1

listenScroll()
//下拉箭头图标添加
$(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`);
let tabList = [], /*statisticsType="",*/
    levelTemp = "", deptId = "", deptIdTemp = "", deptName = "", deptNameTemp = "", doctorName = "", doctorNameTemp = "",
    data_desc = ['entryNum'], data_asc = [], doctorNum = "", doctorNumTemp = "", hospital = getCookie("hospital");
let srcUrl = $("#contentIframe", parent.document).attr("src")
/*statisticsType = getUrlArgObjectNew("dateType",srcUrl)||""*/
deptType = getUrlArgObjectNew("deptType", srcUrl) || ""
deptName = deptNameTemp = getUrlArgObjectNew("deptName", srcUrl) || ""
deptId = deptIdTemp = getUrlArgObjectNew("deptId", srcUrl) || ""

let startDateParam = getUrlArgObjectNew("startDateParam", srcUrl) || ""
let endDateParam = getUrlArgObjectNew("endDateParam", srcUrl) || ""
$('.selectDept').html(deptName).attr("title", deptName)
//传入的日期显示
setDatePicker($("#datepicker"), $("#datepicker2"), 3, new Date(startDateParam), new Date(endDateParam))

//重置按钮事件绑定
$(".abnormalClear").click(function () {
    setDatePicker($("#datepicker"), $("#datepicker2"), "default")
    doctorName = doctorNameTemp = ""
    doctorNum = doctorNumTemp = ""
    $(".selectDept").attr({ 'title': "全部", 'data-id': '' }).val("全部")
    $(".doctorInp").val("")
    $(".doctorNumInp").val("")
    getTabData(1)
    getDeptList()
})

//面包屑点击事件
// $(".partTitle a").click(function () {//初始菜单选中
//     $(".menu .page", parent.document).removeClass("active").eq(0).addClass("active");
//     $(".container", parent.document).addClass("console-cont");
// })


// 各科室缺陷占比菜单选中
$(".menu .page", parent.document).removeClass("active")
$(parent.document).find(".menu .page[code=YH-ZKK-GKSQXZB_XQ]").addClass("active")

//判断有无某一权限
function hasData(data, parent) {
    let codeLis = getCookie("codeLis")
    if (parent) {
        if (codeLis.indexOf(parent) == -1) {//有权限
            return false
        }
    }
    if (codeLis.indexOf(data) > -1) {//有权限
        return true
    }
    return false;
}
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,
        size:  deptName == "全院" ? 15 : 1000,
        "asc": data_asc,
        "desc": data_desc,
        "doctorName": doctorName || "",
        "doctorId": doctorNum || "",
        "deptId": deptId,
        "deptName": deptName == "全院" ? "" : (deptName || ""),
        "type": 0, //1-本月，2-本年,0-自定义时间（现在 都是自定义时间，都会传具体时间进去）
        "startDate": dateStatrt,
        "endDate": dateEnd
    }
    startDateParam = dateStatrt
    endDateParam = dateEnd
    $('.pagination').html("")
    $('.doctorQcAverageDetailTable table').html(`<tbody>${emptyBox('努力加载中...', '', 1)}</tbody>`)

    post(api.doctorAverageStatistics, 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, activePage);
            renderPagination(totalPage, Number(activePage), totalNum)
            if (totalPage > 1) {
                renderPagination(totalPage, Number(activePage), totalNum)
            } else {
                $('.pagination').html("")
            }
        } else {
            $.alerModal({ "message": res.data.msg, type: "tip", time: '1000', isFather: true, fatherWrapper: $("#mainBox", parent.document) });
        }
    }).catch((e) => {

    })
}

getTabData(1)


$("body").on("click", "th[code]", 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);
});
$(".filter").on("click", function (e) {
    deptId = deptIdTemp
    deptName = deptNameTemp
    doctorNum = doctorNumTemp
    doctorName = doctorNameTemp
    if (deptName == "") {
        $(".selectDept").attr({ 'title': "全部", 'data-id': '' }).val("全部")
    }
    getTabData(1)
})
function renderTab(data, hisId, activePage) {
    let str = ``
    let tHead = `
        <thead>
        <th class="moduleName" style="width: 65px;">序号</th>
        <th class="beHospitalId textCenter">科室</th>
        <th class="beHospitalId textCenter">医生姓名</th>
        <th class="beHospitalId textCenter">医生工号</th>
        <th class="beHospitalId textCenter ${data_asc == 'entryNum' ? 'asc' : data_desc == 'entryNum' ? 'desc' : ''}" code="entryNum">缺陷总数</th>
        <th class="beHospitalId textCenter ${data_asc == 'averageValue' ? 'asc' : data_desc == 'averageValue' ? 'desc' : ''}" code="averageValue">质控平均分</th>
        <th class="beHospitalId textCenter ${data_asc == 'firstLevelStrNum' ? 'asc' : data_desc == 'firstLevelStrNum' ? 'desc' : ''}" code="firstLevelStrNum">甲级病历数</th>
        <th class="beHospitalId textCenter ${data_asc == 'secondLevelStrNum' ? 'asc' : data_desc == 'secondLevelStrNum' ? 'desc' : ''}" code="secondLevelStrNum">乙级病历数</th>
        <th class="beHospitalId textCenter ${data_asc == 'thirdLevelStrNum' ? 'asc' : data_desc == 'thirdLevelStrNum' ? 'desc' : ''}" code="thirdLevelStrNum">丙级病历数</th>
        </thead>`
    for (let i = 0; i < data.length; i++) {
        const item = data[i]
        str += `
            <tr  data-index=${i}>
                <td  class="textCenter">${(activePage - 1) * 15 + i + 1}</td>
                <td >${item.deptName || "-"}</td>
                <td >${item.doctorName || "-"}</td>
                <td >${item.doctorId || "-"}</td>
                <td class="goHomeDetailQuexian goHomeDetail" data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}" dept-doc="${item.doctorName || ""}" dept-docId="${item.doctorId || ""}">
                    ${item.entryNum || "-"}
                    ${item.entrySameNum < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.entrySameNum > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td >${item.averageValue || "-"} </td>
                <td  class="goHomeDetailB goHomeDetail" data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}" data-c="甲" dept-doc="${item.doctorName || ""}" dept-docId="${item.doctorId || ""}">
                ${item.firstLevelStrNum + '' || "-"}
                ${item.firSameLevelNum < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.firSameLevelNum > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td  class="goHomeDetailB goHomeDetail" data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}" data-c="乙" dept-doc="${item.doctorName || ""}" dept-docId="${item.doctorId || ""}">
                ${item.secondLevelStrNum + '' || "-"}
                ${item.secSameLevelNum < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.secSameLevelNum > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td  class="goHomeDetailB goHomeDetail" data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}" data-c="丙" dept-doc="${item.doctorName || ""}" dept-docId="${item.doctorId || ""}">
                ${item.thirdLevelStrNum + '' || "-"}
                ${item.thiSameLevelNum < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.thiSameLevelNum > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
            </tr>
        `
    }
    $('.doctorQcAverageDetailTable table').html(str ? tHead + '<tbody>' + str + '</tbody>' : tHead + `<tbody>${emptyBox()}</tbody>`)
    // 缺陷总数跳转
    $(".goHomeDetailQuexian").click(function () {
        let deptName = $(this).attr("data-dept")
        let deptId = $(this).attr("dept-id")
        let doctorName = $(this).attr("dept-doc")
        let doctorId = $(this).attr("dept-docId")
        $(parent.document).find("#contentIframe").attr("src", "doctorQuexianDetailControl.html?deptName=" + deptName + "&deptId=" + deptId + "&doctorName=" + doctorName + "&doctorId=" + doctorId + "&from=2" + "&shijian=3" + "&startDateParam=" + startDateParam + "&endDateParam=" + endDateParam)
    })
    //病历跳转
    $(".goHomeDetailB").click(function () {
        let deptName = $(this).attr("data-dept")
        let deptC = $(this).attr("data-c")
        let deptIds = $(this).attr("dept-id")
        let doctorName = $(this).attr("dept-doc")
        let doctorId = $(this).attr("dept-docId")
        $(parent.document).find("#contentIframe").attr("src", "doctorQcListCopy.html?deptName=" + deptName + "&from=3" + "&shijian=3&chengdu=" + deptC + "&deptId=" + deptIds + "&doctorName=" + doctorName + "&doctorId=" + doctorId + "&startDateParam=" + startDateParam + "&endDateParam=" + endDateParam)
    })
}

//科室下拉事件绑定
$('.selectDept').on("focus", function (e) {
    e.stopPropagation()
    $(".deptList ").css("display", "block")
})

$('.selectDept').on("blur", function (e) {
    $(".deptList ").css("display", "none")
    $(".selectDept .arrow").attr("src", iconDown)
})
$('.selectDept').on("input", function (e) {
    let val = $(this).val().trim()
    deptName = deptNameTemp = val
    getDeptList(deptName)
})

//获取科室列表
getDeptList()
function getDeptList(val) {
    post(api.getDeptList, { inputStr: val == "全部" ? "" : val || "" }).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 " 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("mousedown", function () {
        const deptItemName = $(this).attr("data-name")
        const deptItemId = $(this).attr("data-id")
        deptIdTemp = deptItemId
        deptNameTemp = deptItemName === "全部" ? "" : deptItemName;
        $('.selectDept').val(deptItemName)
        $('.selectDept ').attr('title', deptItemName)
        $(".deptList").css("display", "none")
        $('.selectDept').removeClass('unSelect')
    })
}
function loading() {
    const str = `
    <div class="loadingBox">
            <div class="mask"></div>
            <img class="loadingImg" src=${loadingImg}  alt="loading" />
        </div>
    `
    $("#mainBox", parent.document).append(str)
}
function hideLoading() {
    $("#mainBox .loadingBox", parent.document).remove()
}
$(".doctorInp").on("input", function (e) {
    const val = $(this).val().trim()
    doctorNameTemp = val
})
$(".doctorNumInp").on("input", function (e) {
    const val = $(this).val().trim();
    doctorNumTemp = val
})

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

}

$(function () {

    $(".consoleD").on("click", function () {
        $(parent.document).find("#contentIframe").attr("src", "doctorQcAverageDetail.html?deptName=" + `${deptName == "全部" ? "全院" : deptName}` + "&deptId=" + deptId + "&shijian=3" + "&startDateParam=" + startDateParam + "&endDateParam=" + endDateParam)
    })
    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()
    });
    $('.export').click(function () {
        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 = {
            "asc": data_asc,
            "desc": data_desc,
            "doctorName": doctorName || "",
            "doctorId": doctorNum || "",
            "deptName": deptName == "全院" ? "" : (deptName || ""),
            "deptId": deptId,
            /*"type": statisticsType||2,*/ //1-本月，2-本年
            "startDate": startDateParam,
            "isPlacefile": isPlacefile,
            "endDate": endDateParam
        };
        const url = hospital == '台州市立' ? api.exportDeptFlawsTz : api.exportDeptFlaws;
        expJson(api.doctorAverageStatisticsExport, param).then(res => {
            downloadExportedData(res.data, "医生质控平均分.xls")
        })
    })
});