const $ = require('jquery');
require("../css/quality.less");
require('./../resource/jquery-ui/jquery-ui.min.js');
require('./modal.js');
const { api } = require('./api.js')
const { post, getCookie, getUrlArgObjectNew, emptyBox, setDatePicker, getPickerDate, listenScroll } = require('./utils.js')
const switchIconOpen = require("./../images/btn_open.png")
const switchIconClose = require("./../images/btn_close.png")
const iconDown = require("./../images/arrow_down.png")
const iconUp = require("./../images/arrow_up.png")
const iconCalenBlue = require("./../images/icon_calen_blue.png")
const iconCalenGrey = require("./../images/icon_calen_grey.png")
let casesId = "", name = "", isReject = "", isUsed = "", casesName = "", casesNameTemp = "", casesIdTemp = "", nameTemp = "", isRejectTemp = "", isUsedTemp = "", from = "", deptIdTemp = "", deptId = "", data_asc = [], data_desc = ['percent'], startDateParam = "", endDateParam = ""

$(function () {
    listenScroll('.mukuai')
    dateChange()
    let srcUrl = $("#contentIframe", parent.document).attr("src")
    // deptName = getUrlArgObjectNew("deptName",srcUrl)||""
    isRejectTemp = isReject = getUrlArgObjectNew("dateType", srcUrl) || ""
    from = getUrlArgObjectNew("from", srcUrl) || ""
    name = nameTemp = getUrlArgObjectNew("name", srcUrl) || ""
    let startDateParam = getUrlArgObjectNew("startDateParam", srcUrl) || ""
    let endDateParam = getUrlArgObjectNew("endDateParam", srcUrl) || ""

    $(".partTitle a").click(function () {
        //初始菜单选中
        $(".container", parent.document).addClass("console-cont");
        focusMenuItem('YH-KZT')
    })
    $(".abnormalClear").click(function () {
        // window.location.reload()
        name = nameTemp = ""
        casesName = casesNameTemp = ""
        data_asc = [],
            data_desc = ['percent']
        setDatePicker($("#datepicker"), $("#datepicker2"), 1)
       
        $("th[code]").removeClass("asc desc").addClass("desc");
        $(".moduleScore").addClass("desc")
        $(".patientNumInp").val("")
        $(".selectModuleType ").val("全部")
        getTabData(1)
        getmoduleTypeList()
    })

    if (isReject == 1) {
        $(".monthYear .mon").css({
            backgroundColor: '#00A1FF',
            color: '#fff'
        }).siblings().css({
            color: '#00A1FF',
            backgroundColor: '#fff'
        })
        setDatePicker($("#datepicker"), $("#datepicker2"), 1)
    } else if (isReject == 2) {
        $(".monthYear .year").css({
            backgroundColor: '#00A1FF',
            color: '#fff'
        }).siblings().css({
            color: '#00A1FF',
            backgroundColor: '#fff'
        })
        setDatePicker($("#datepicker"), $("#datepicker2"), 2)
    } else if (isReject == 3) {
        setDatePicker($("#datepicker"), $("#datepicker2"), 3, new Date(startDateParam), new Date(endDateParam))
    } else {
        setDatePicker($("#datepicker"), $("#datepicker2"), 1)
    }
    if (!isReject) {
        setDatePicker($("#datepicker"), $("#datepicker2"), 1)
    }
    getTabData(1)//条目缺陷
})

function focusMenuItem(code) {
    const ele = $(parent.document).find(".menu .page[code=" + code + "]");
    const parEle = ele.parents(".list-1");
    if (!parEle.is(".list-1-show")) {
        parEle.click();
    }
    //console.log($(parent.document).find(".menu .page[code='YH-ZKK-GMKQXZB_XQ']"))
    ele.click();
}

// YH-ZKK-GMKQXZB_XQ
$(".menu .page", parent.document).removeClass("active")
$(parent.document).find(".menu .page[code=YH-ZKK-YLZLKZZB_XQ]").addClass("active")
//判断有无某一权限
function hasData(data) {
    let lis = JSON.parse(getCookie("codeLis")) || []
    if (lis.indexOf(data) > -1) {//有权限
        return true
    }
    return false;
}
//所有数据切换日期筛选
function dateChange() {
    $(".monthYear .mon").click(function () {
        $(this).css({
            backgroundColor: '#00A1FF',
            color: '#fff'
        }).siblings().css({
            color: '#00A1FF',
            backgroundColor: '#fff'
        })
        isReject = 1
        isRejectTemp = 1
        setDatePicker($("#datepicker"), $("#datepicker2"), 1)
        getTabData(1)
    })
    $(".monthYear .year").click(function () {
        $(this).css({
            backgroundColor: '#00A1FF',
            color: '#fff'
        }).siblings().css({
            color: '#00A1FF',
            backgroundColor: '#fff'
        })
        isReject = 2
        isRejectTemp = 2
        setDatePicker($("#datepicker"), $("#datepicker2"), 2)
        getTabData(1)
    })
}
$("th[code]").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);
    // console.log(code)
});
//获取表格数据
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 = {
        indexName: casesName,
        "startDate": dateStatrt,
        "endDate": dateEnd,
    }
    startDateParam = dateStatrt
    endDateParam = dateEnd
    $('.pagination').html("")
    $('.tbody').html(emptyBox('努力加载中...', '', 1))
    post(api.medicalRecordIndicator, param).then(res => {
        if (res.data.code == '0') {
            const data = res.data.data
            renderTab(data, activePage)
        } else { }
    }).catch((e) => { })
}

$(".filter").on("click", function (e) {
    casesId = casesIdTemp, name = nameTemp, isReject = isRejectTemp, isUsed = isUsedTemp, deptId = deptIdTemp, casesName = casesNameTemp
    if (casesName == "") {
        $(".selectModuleType").attr({ 'title': "全部", 'data-id': '' }).val("全部")
    }
    getTabData(1)
})
$(".filterclear").on("click", function (e) {
    nameTemp = ""
})

// getmoduleTypeList()
function renderTab(data, activePage) {
    let str = ``;
    for (let i = 0; i < data.length; i++) {
        const item = data[i]
        str += `
            <tr data-id=${item.id} data-index=${i}>
                <td  class="textCenter">${(activePage - 1) * 15 + i + 1}</td>
                <td data-model="${item.name}">${item.name}</td>
                <td class="textCenter">${item.notCopiedStr || '-'}</td>
            </tr>
        `
    }
    $('.tbody').html(str ? str : emptyBox())
}

$('.selectModuleType').on("focus", function (e) {
    e.stopPropagation()
    $(".moduleTypeList ").css("display", "block")
})
$('.selectModuleType').on("blur", function (e) {
    $(".moduleTypeList ").css("display", "none")
})
$('.selectModuleType').on("input", function (e) {
    let val = $(this).val().trim()
    casesName = casesNameTemp = val
    getmoduleTypeList(val)
})
getmoduleTypeList()
//获取指标列表数据
function getmoduleTypeList(val) {
    post(api.getMedQualityCoList, { inputStr: val == "全部" ? "" : val || "" }).then(res => {
        if (res.data.code == '0') {
            const moduleTypeList = res.data.data
            renderModuleTypeList(moduleTypeList)
        } else {
            renderModuleTypeList([])
        }
    }).catch((e) => {

    })
}
function renderModuleTypeList(moduleTypeList) {
    if (moduleTypeList.length == 0) {
        $('.moduleTypeList').html("")
        return
    }
    let str = `<li class="modeTypeItem " data-id=" " data-name="全部">全部</li>`
    for (let i = 0; i < moduleTypeList.length; i++) {
        str += `<li class="modeTypeItem ellipsis" title=${moduleTypeList[i].columnName} data-id=${moduleTypeList[i].columnName} data-name=${moduleTypeList[i].columnName}> ${moduleTypeList[i].columnName}</li>`
    }
    $('.moduleTypeList').html(str)
    bindModuleTypeSelect()
}

//模块类型选择
function bindModuleTypeSelect() {
    $('.modeTypeItem').on("mousedown", function () {
        const modeTypeItemName = $(this).attr("data-name")
        const modeTypeItemId = $(this).attr("data-id")
        // deptNameTemp=deptItemName=="全部"?"":deptItemName;
        casesIdTemp = modeTypeItemId
        casesName = casesNameTemp = modeTypeItemName == "全部" ? "" : modeTypeItemName;
        $('.selectModuleType').val(modeTypeItemName).attr("title", modeTypeItemName)
        $(".moduleTypeList ").css("display", "none")
    })
}

$(function () {
    $('.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()
    })
});