const $ = require('jquery');
require("../css/deptScoreDetailControl.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 iconCheck = require("./../images/icon_check.png")
const iconUnCheck = require("./../images/icon_unchecked.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")
const jiantou_up = require("./../images/jiantou_up.png")
const jiantou_down = require("./../images/jiantou_down.png")
let isPlacefile = getCookie('isPlacefile') || 1

listenScroll()
$(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
$(".selectDept").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
$(".selectLeaveHosType").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
let tabList = [], name = "", leaveHosType = "", leaveHosTypeTemp = "", behospitalCode = "", behosDateStart = "", level = "", behosDateEnd = "", scoreSum = 0, statisticsType = "", deptType = "",
    nameTemp = "", behospitalCodeTemp = "", levelTemp = "", deptId = "", deptIdTemp = "", deptName = "", deptNameTemp = "", doctorName = "", doctorNum = "", doctorNameTemp = "", doctorNumTemp = "",
    data_desc = "entryNum", data_asc = "", hospital = getCookie("hospital");
let srcUrl = $("#contentIframe", parent.document).attr("src")
statisticsType = getUrlArgObjectNew("dateType", srcUrl) || ""
deptType = getUrlArgObjectNew("deptType", srcUrl) || ""
let startDateParam = getUrlArgObjectNew("startDateParam", srcUrl) || ""
let endDateParam = getUrlArgObjectNew("endDateParam", srcUrl) || ""

if (deptName) {
    console.log(deptName);
    if (deptName == "全院") {
        deptName = "全部"
    }
    deptNameTemp = deptName
    $('.selectDept').val(deptName)
    $('.selectDept ').attr('title', deptName)
    $(".deptList").css("display", "none")
}

if (hospital == '台州市立') {
    $(".deptListWrap").css("display", "inline-block")
    $('.selectLeaveHosType').html(deptType ? (deptType + '系统') : "全部").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    $(".leaveHosTypeList").css("display", "none")
    $('.selectLeaveHosType').removeClass('unSelect')
    leaveHosType = leaveHosTypeTemp = deptType
    deptName = deptNameTemp
} else {
    $(".deptListWrap").css("display", "none")
}
if (statisticsType == 1) {
    $(".monthYear .mon").css({
        backgroundColor: '#00A1FF',
        color: '#fff'
    }).siblings().css({
        color: '#00A1FF',
        backgroundColor: '#fff'
    })
    setDatePicker($("#datepicker"), $("#datepicker2"), 1)
} else if (statisticsType == 2) {
    $(".monthYear .year").css({
        backgroundColor: '#00A1FF',
        color: '#fff'
    }).siblings().css({
        color: '#00A1FF',
        backgroundColor: '#fff'
    })
    setDatePicker($("#datepicker"), $("#datepicker2"), 2)
} else if (statisticsType == 3) {
    setDatePicker($("#datepicker"), $("#datepicker2"), 3, new Date(startDateParam), new Date(endDateParam))
} else {
    setDatePicker($("#datepicker"), $("#datepicker2"), "default")
}
if (!statisticsType) {
    setDatePicker($("#datepicker"), $("#datepicker2"), "default")
}
$(".abnormalClear").click(function () {
    setDatePicker($("#datepicker"), $("#datepicker2"), "default")
    behospitalCode = behospitalCodeTemp = ""
    deptId = deptIdTemp = ""
    leaveHosType = leaveHosTypeTemp = ""
    deptName = deptNameTemp = ""
    leaveHosType = "";
    leaveHosTypeTemp = "";

    $('.selectLeaveHosType').html('全部')
    $(".leaveHosTypeList").css("display", "none")
    $(".selectLeaveHosType").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    $(".selectDept").attr({ 'title': "全部", 'data-id': '' }).val("全部")
    $(".patientNumInp").val("")
    getTabData(1)
    getDeptList()
})

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

$('.recordScoreBtn').css("opacity", hasData('FUNC000017') ? '1' : '0.5')
dateChange()
//所有数据切换日期筛选
function dateChange() {
    $(".monthYear .mon").click(function () {
        $(this).css({
            backgroundColor: '#00A1FF',
            color: '#fff'
        }).siblings().css({
            color: '#00A1FF',
            backgroundColor: '#fff'
        })
        $(".dayDetail .deptListWrap").css("display", "block")
        $(".dayDetail .dayFilter").css("display", "none")
        statisticsType = 1
        setDatePicker($("#datepicker"), $("#datepicker2"), 1)
        getTabData(1)
    })
    $(".monthYear .year").click(function () {
        $(this).css({
            backgroundColor: '#00A1FF',
            color: '#fff'
        }).siblings().css({
            color: '#00A1FF',
            backgroundColor: '#fff'
        })
        $(".dayDetail .deptListWrap").css("display", "none")
        $(".dayDetail .dayFilter").css("display", "block")
        statisticsType = 2
        setDatePicker($("#datepicker"), $("#datepicker2"), 2)
        getTabData(1)
    })
}
// YH-ZKK-GKSQXZB_XQ
$(".menu .page", parent.document).removeClass("active")
$(parent.document).find(".menu .page[code=YH-ZKK-GKSQXZB_XQ]").addClass("active")

bindleaveHosTypeSelect()
//出院人数类型选择
function bindleaveHosTypeSelect() {
    $('.leaveHosTypeItem').on("click", function () {
        const leaveHosTypeItemName = $(this).attr("data-name")
        const leaveHosTypeItemItemId = $(this).attr("data-id")
        leaveHosTypeTemp = leaveHosTypeItemItemId
        $('.selectLeaveHosType').html(leaveHosTypeItemName)
        $(".leaveHosTypeList").css("display", "none")
        $(".selectLeaveHosType").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
        $('.selectLeaveHosType').removeClass('unSelect')
    })
}
//判断有无某一权限
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 = {
        "asc": data_asc,
        "desc": data_desc,
        "doctorName": behospitalCode || "",
        "name": behospitalCode || "",
        "deptClass": leaveHosType || '',
        "deptName": deptName == "全部" ? "" : deptName || "",
        "type": 0, //1-本月，2-本年,0-自定义时间（现在 都是自定义时间，都会传具体时间进去）
        "startDate": dateStatrt,
        "endDate": dateEnd
    }
    let url = ''

    if (hospital == "台州市立" && hasData('FUNC000092', 'YH-ZKK-GKSQXZB_XQ')) {
        url = api.levelStatisticsByDeptClass
    } else {
        url = api.levelStatistics
    }
    startDateParam = dateStatrt
    endDateParam = dateEnd
    $('.pagination').html("")
    $('.deptScoreDetailControlTable table').html(`<tbody>${emptyBox('努力加载中...', '', 1)}</tbody>`)

    post(url, 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(data, 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 === 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) {
    name = nameTemp
    behospitalCode = behospitalCodeTemp
    level = levelTemp
    deptId = deptIdTemp
    leaveHosType = leaveHosTypeTemp
    deptName = deptNameTemp
    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>
        ${hospital == '台州市立' ? '<th class="beHospitalId textCenter">科室系统</th>' : null}
        <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 == 'sameNum' ? 'asc' : data_desc == 'sameNum' ? 'desc' : ''}" code="sameNum">同比总数</th>
        <th class="beHospitalId textCenter ${data_asc == 'averageValue' ? 'asc' : data_desc == 'averageValue' ? 'desc' : ''}" code="averageValue">质控平均分</th>
        <th class="beHospitalId textCenter ${data_asc == 'sameAvgValue' ? 'asc' : data_desc == 'sameAvgValue' ? 'desc' : ''}" code="sameAvgValue">同比平均分</th>
        <th class="beHospitalId textCenter ${data_asc == 'mrNum' ? 'asc' : data_desc == 'mrNum' ? 'desc' : ''}" code="mrNum">质控病历数</th>
        <th class="beHospitalId textCenter ${data_asc == 'sameMrNum' ? 'asc' : data_desc == 'sameMrNum' ? 'desc' : ''}" code="sameMrNum">同比质控数</th>
        <th class="beHospitalId textCenter ${data_asc == 'firstLevelNum' ? 'asc' : data_desc == 'firstLevelNum' ? 'desc' : ''}" code="firstLevelNum">甲级病历数</th>
        <th class="beHospitalId textCenter ${data_asc == 'sameFirstLevelNum' ? 'asc' : data_desc == 'sameFirstLevelNum' ? 'desc' : ''}" code="sameFirstLevelNum">同比甲级数</th>
        <th class="beHospitalId textCenter ${data_asc == 'secondLevelNum' ? 'asc' : data_desc == 'secondLevelNum' ? 'desc' : ''}" code="secondLevelNum">乙级病历数</th>
        <th class="beHospitalId textCenter ${data_asc == 'sameSecondLevelNum' ? 'asc' : data_desc == 'sameSecondLevelNum' ? 'desc' : ''}" code="sameSecondLevelNum">同比乙级数</th>
        <th class="beHospitalId textCenter ${data_asc == 'thirdLevelNum' ? 'asc' : data_desc == 'thirdLevelNum' ? 'desc' : ''}" code="thirdLevelNum">丙级病历数</th>
        <th class="beHospitalId textCenter ${data_asc == 'sameThirdLevelNum' ? 'asc' : data_desc == 'sameThirdLevelNum' ? 'desc' : ''}" code="sameThirdLevelNum">同比丙级数</th>
        <th class="beHospitalId textCenter ${data_asc == 'firstLevelPercentStr' ? 'asc' : data_desc == 'firstLevelPercentStr' ? 'desc' : ''}" code="firstLevelPercentStr">甲级率</th>
        <th class="beHospitalId textCenter ${data_asc == 'sameFirstLevelPercent' ? 'asc' : data_desc == 'sameFirstLevelPercent' ? 'desc' : ''}" code="sameFirstLevelPercent">同比甲级率</th>
        <th class="beHospitalId textCenter ${data_asc == 'secondLevelPercentStr' ? 'asc' : data_desc == 'secondLevelPercentStr' ? 'desc' : ''}" code="secondLevelPercentStr">乙级率</th>
        <th class="beHospitalId textCenter ${data_asc == 'sameSecondLevelPercent' ? 'asc' : data_desc == 'sameSecondLevelPercent' ? 'desc' : ''}" code="sameSecondLevelPercent">同比乙级率</th>
        <th class="beHospitalId textCenter ${data_asc == 'thirdLevelPercentStr' ? 'asc' : data_desc == 'thirdLevelPercentStr' ? 'desc' : ''}" code="thirdLevelPercentStr">丙级率</th>
        <th class="beHospitalId textCenter ${data_asc == 'sameThirdLevelPercent' ? 'asc' : data_desc == 'sameThirdLevelPercent' ? 'desc' : ''}" code="sameThirdLevelPercent">同比丙级率</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>
                ${hospital == '台州市立' ? ('<td >' + (item.deptClass ? (item.deptClass + '系统') : "-") + '</td>') : ''}
                <td >${item.deptName || "-"}</td>
                <td class="goHomeDetailQuexian goHomeDetail" data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}">
                    ${item.entryNum || "-"}
                    ${item.entrySameNum < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.entrySameNum > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}">${item.sameNum}</td>
                <td class="goHomeDetailAvg goHomeDetail" data-dept="${item.deptName || ""}"  dept-id="${item.deptId || ""}">
                ${item.averageValue || "-"}
                ${item.avSameValue < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.avSameValue > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td >${item.sameAvgValue}</td>
                <td >
                ${item.mrNum || "-"}
                ${item.mrSameNum < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.mrSameNum > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td >${item.sameMrNum}</td>
                <td  class="goHomeDetailB goHomeDetail" data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}" data-c="甲">
                ${item.firstLevelNum + '' || "-"}
                ${item.firSameLevelNum < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.firSameLevelNum > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}" data-c="甲">
                ${item.sameFirstLevelNum + '' || "-"}
                </td>
                <td  class="goHomeDetailB goHomeDetail" data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}" data-c="乙">
                ${item.secondLevelNum + '' || "-"}
                ${item.secSameLevelNum < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.secSameLevelNum > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td  data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}" data-c="乙">
                ${item.sameSecondLevelNum + '' || "-"}
                </td>
                <td  class="goHomeDetailB goHomeDetail" data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}" data-c="丙">
                ${item.thirdLevelNum + '' || "-"}
                ${item.thiSameLevelNum < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.thiSameLevelNum > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td  data-dept="${item.deptName || ""}" dept-id="${item.deptId || ""}" data-c="丙">${item.sameThirdLevelNum + '' || "-"}</td>
                <td >
                ${item.firstLevelPercentStr || "-"}
                ${item.firSameLevelPercent < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.firSameLevelPercent > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td >${item.sameFirstLevelPercentStr}</td>
                <td >
                ${item.secondLevelPercentStr || "-"}
                ${item.secSameLevelPercent < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.secSameLevelPercent > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td >${item.sameSecondLevelPercentStr}</td>
                <td >
                ${item.thirdLevelPercentStr || "-"}
                ${item.thiSameLevelPercent < 0 ? '<img class="updownimg" src="' + jiantou_down + '"/>' : item.thiSameLevelPercent > 0 ? '<img class="updownimg" src="' + jiantou_up + '"/>' : ''}
                </td>
                <td >${item.sameThirdLevelPercentStr}</td>
            </tr>
        `
    }
    $('.deptScoreDetailControlTable table').html(str ? tHead + '<tbody>' + str + '</tbody>' : tHead + `<tbody>${emptyBox()}</tbody>`)
    bindScoreDetail(hisId)
    // 缺陷总数跳转
    $(".goHomeDetailQuexian").click(function () {
        let deptName = $(this).attr("data-dept")
        let deptId = $(this).attr("dept-id")
        $(parent.document).find("#contentIframe").attr("src", "quexianDetailControl.html?deptName=" + deptName + "&deptId=" + deptId + "&from=2" + "&shijian=3" + "&startDateParam=" + startDateParam + "&endDateParam=" + endDateParam)
    })
    //质控平均分跳转
    $(".goHomeDetailAvg").click(function () {
        let deptName = $(this).attr("data-dept")
        let deptId = $(this).attr("dept-id")
        $(parent.document).find("#contentIframe").attr("src", "doctorQcAverageDetail.html?deptName=" + deptName + "&deptId=" + deptId + "&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")
        focusMenuItem("YH-BLZK-ZKPF");
        $(parent.document).find("#contentIframe").attr("src", "qcList.html?deptName=" + deptName + "&from=2" + "&shijian=3&chengdu=" + deptC + "&deptId=" + deptIds + "&startDateParam=" + startDateParam + "&endDateParam=" + endDateParam)
    })
    // initScroll("deptScoreDetailControl","YX",1)
}

function scoreDetail(id, age, hid, code) {
    window.open(`./qcScore.html?id=${id}&age=${age}&hid=${hid}&code=${code}`)
}
function bindScoreDetail(hisId) {
    $('.patientNameSpan').on('click', function (e) {
        const index = $(this).attr("data-index")
        const type = $(this).attr("data-type")
        const item = tabList[index]
        midifyMsgBox(item, type)
    })
}


function midifyMsgBox(item, type) {
    const itemCopy = JSON.parse(JSON.stringify(item))
    let msgBox = ''
    if (type == 1) {
        msgBox = `<div class="midifyMsgBox">
            <div class="mask"></div>
            <div class="midifyMsgContent abnormal">
                <p class="midifyMsgTitle">修改 <img class="iconClose" src=${require('./../images/icon_close_default.png')} alt="关闭" /></p>
                <div class="itemMsgInfoBox">
                    <span class="itemMsgLab abnormalLeft">状态：</span> 
                    <span class="abnormalAll" data-status="${itemCopy.status}">${itemCopy.status == 0 ? "未处理" : "已处理"}</span>
                    <ul class="abnormalStatusLis">
                        <li data-status="0">未处理</li>
                        <li data-status="1">已处理</li>
                    </ul>
                </div>
                <div class="itemMsgInfoBox">
                    <span class="itemMsgLab abnormalLeft abnormalMark">备注：</span> 
                    <span class="itemInfoRight"> 
                        <textarea class="abnormalTxt" placeholder="请输入内容" >${itemCopy.remark}</textarea>
                    </span>
                </div>
                <div  class="itemMsgInfoTips">支持≥0的数字输入，最多保留小数点后1位~</div>
                <div class="midifyMsgBtn abnormalBtn">
                    <span class="midifyEdit">保存</span>
                </div>
            </div>
        </div>`
    } else {
        msgBox = `<div class="midifyMsgBox">
            <div class="mask"></div>
            <div class="midifyMsgContent midifyMsgContentDel">
                <p class="midifyMsgTitle">修改 <img class="iconClose" src=${require('./../images/icon_close_default.png')} alt="关闭" /></p>
                <p class="delTips">确认要删除该条异常记录？</p>
                <div class="midifyMsgBtn midifyMsgBtnDel">
                    <span class="midifyEdit midifyEditDel">删除</span>
                    <span class="midifyEdit midifyEditQuit">取消</span>
                </div>
            </div>
        </div>`
    }
    $("#mainBox", parent.document).append(msgBox)
    $(".midifyEditDel", parent.document).on("click", function () {
        delModifyOne(itemCopy)
    })
    $(".midifyEditQuit", parent.document).on("click", function () {
        $("#mainBox .midifyMsgBox", parent.document).remove()
    })
    $(".abnormalAll", parent.document).on("click", function () {
        $(".abnormalStatusLis", parent.document).slideToggle()
    })
    $(".abnormalStatusLis li", parent.document).on("click", function () {
        let status = $(this).attr("data-status")
        let str = $(this).html()
        $(".abnormalAll", parent.document).attr("data-status", status).html(str)
        $(".abnormalStatusLis", parent.document).slideToggle()
    })
    $("#mainBox .midifyMsgBox .iconClose", parent.document).on("click", function (e) {
        $("#mainBox .midifyMsgBox", parent.document).remove()
    })
    $("#mainBox .midifyMsgBox .itemScore", parent.document).on("keypress", function (event) {
        return (/[\d\.]/.test(String.fromCharCode(event.keyCode)))
    })
    $("#mainBox .midifyMsgBox .itemScore", parent.document).on("input", function (e) {
        const val = $(this).val()
        itemCopy.score = val
    })
    $("#mainBox .midifyMsgBox .midifyEdit", parent.document).on("click", function (e) {
        saveModifyOne(itemCopy)
    })
}
//保存修改
function delModifyOne(itemCopy) {
    let param = {
        "id": itemCopy.id
    }
    post(api.delQcAnnormal, param).then(res => {
        if (res.data.code == '0') {
            const data = res.data.data;
            getTabData(1)
            $("#mainBox .midifyMsgBox", parent.document).remove()
            $.alerModal({ "message": '删除成功', type: "tip", time: '1000', isFather: true, win: true, fatherWrapper: $("#mainBox", parent.document) });
        } else {
            $.alerModal({ "message": '删除失败,请重试~', type: "tip", time: '1000', win: 'default', isFather: true, fatherWrapper: $("#mainBox", parent.document) });

        }
    }).catch((e) => {
        $.alerModal({ "message": '删除失败,请重试~', type: "tip", time: '1000', win: 'default', isFather: true, fatherWrapper: $("#mainBox", parent.document) });

    })
}
//保存修改
function saveModifyOne(itemCopy) {
    let txt = $(".abnormalTxt", parent.document).val()
    let status = $(".abnormalAll", parent.document).attr("data-status")
    let param = {
        "id": itemCopy.id,
        "remark": txt,
        "status": status
    }
    post(api.saveQcAnnormal, param).then(res => {
        if (res.data.code == '0') {
            const data = res.data.data;
            getTabData(1)
            $("#mainBox .midifyMsgBox", parent.document).remove()
            $.alerModal({ "message": '修改成功', type: "tip", time: '1000', isFather: true, win: true, fatherWrapper: $("#mainBox", parent.document) });
        } else {
            $.alerModal({ "message": '修改失败,请重试~', type: "tip", time: '1000', isFather: true, win: 'default', fatherWrapper: $("#mainBox", parent.document) });

        }
    }).catch((e) => {
        $.alerModal({ "message": '修改失败,请重试~', type: "tip", time: '1000', isFather: true, win: 'default', fatherWrapper: $("#mainBox", parent.document) });

    })
}

//选择出院人数类型
$('.selectLeaveHosType').on("click", function (e) {
    e.stopPropagation()
    $(".deptList ").css("display", "none")
    $(".selectDept .arrow").attr("src", iconDown)
    $(".levelList ").css("display", "none")
    $(".checkList ").css("display", "none")
    $(".selectCheck .arrow").attr("src", iconDown)
    $(".selectLeaveHosType").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    const showList = $(".leaveHosTypeList ").css("display")
    if (showList == "none" || !showList) {
        $(".leaveHosTypeList ").css("display", "block")
        $(".selectLeaveHosType .arrow").attr("src", iconUp)
    } else {
        $(".leaveHosTypeList ").css("display", "none")
        $(".selectLeaveHosType .arrow").attr("src", iconDown)
    }
})

bindLeveldSelect()
//是否启用选择
function bindLeveldSelect() {
    $('.levelItem').on("click", function () {
        const levelItemName = $(this).attr("data-name")
        const levelItemItemId = $(this).attr("data-id")
        levelTemp = levelItemItemId
        $('.selectLevel').html(levelItemName)
        $(".levelList").css("display", "none")
        $(".selectLevel").append(`<img class="arrow" src=${iconDown} alt="下拉">`)
    })
}

//全选绑定
$('.selectDept').on("focus", function (e) {
    e.stopPropagation()
    $(".levelList ").css("display", "none")
    $(".selectLevel .arrow").attr("src", iconDown)
    $(".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()
}
$('.recordScoreBtn').on("click", function (e) {
    if (!hasData('FUNC000017', 'YH-BLZK-ZKPF')) {
        return
    }
    let scoreList = []
    for (let i = 0; i < tabList.length; i++) {
        if (tabList[i].hasSelect) {
            scoreList.push(tabList[i].behospitalCode)
        }
    }
    if (scoreList.length === 0) {
        $.alerModal({ "message": '请选择要评分的项！', type: "tip", time: '1000', isFather: true, fatherWrapper: $("#mainBox", parent.document) });
        return
    } else {
        loading()
        for (let j = 0; j < scoreList.length; j++) {
            recordScore(scoreList[j], scoreList.length)
        }
    }
})
function recordScore(behospitalCode, totalNum) {
    const param = {
        behospitalCode: behospitalCode
    }
    post(api.recordScore, param).then(res => {
        if (res.data.code == '0') {
            scoreSum++
            if (scoreSum === totalNum) {
                hideLoading()
                scoreSum = 0
                const activePage = $(".activePage").attr('data-page') || 1

                getTabData(activePage)
            }

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

    })
}
$(".patientNumInp").on("input", function (e) {
    const val = $(this).val().trim()
    behospitalCodeTemp = val
})
$(".patientNameInp").on("input", function (e) {
    const val = $(this).val().trim()
    nameTemp = val
})
$(".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)
        }
    })

}

$(document).on("click", function () {
    $(".levelList ").css("display", "none")
    $(".selectLevel .arrow").attr("src", iconDown)

})

$(function () {
    const iconCalenBlue = require("./../images/darkDate.png")
    const iconCalenGrey = require("./../images/icon_calen_grey.png")
    $('.datapickerBox').append(`<img class="iconCalen" src=${iconCalenGrey} />`)
    $('.iconCalen').on("mouseenter", function (e) {
        $(this).attr("src", iconCalenBlue)
    })
    $('.iconCalen').on("mouseleave", function (e) {
        $(this).attr("src", iconCalenGrey)
    })
    $('.iconCalen').on("click", function (e) {
        $(this).parent().find("input").focus()
    });
    $('.export').click(function () {
        const start = new Date(startDateParam).getTime()
        const end = new Date(endDateParam).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,
            "name": behospitalCode || "",
            "doctorName": behospitalCode || "",
            "deptClass": leaveHosType || '',
            "deptName": deptName == "全部" ? "" : deptName || "",
            "type": statisticsType || 2, //1-本月，2-本年
            "startDate": startDateParam,
            "isPlacefile": isPlacefile,
            "endDate": endDateParam
        };
        const url = hospital == '台州市立' ? api.exportDeptFlawsTz : api.exportDeptFlaws;
        expJson(url, param).then(res => {
            downloadExportedData(res.data, "各科室缺陷占比.xls")
        })
    })
});