const $ = require('jquery');
require("../css/appealExamine.less");
require('./modal.js');
require('jquery-templates');
const { api } = require('./api.js')
const { post, getCookie, getUrlArgObjectNew, getLogoParam, listenScroll, exportTimeLimit } = require('./utils.js')
require('./../resource/jquery-ui/jquery-ui.min.js');
require('./../resource/jquery-ui/jquery-ui.min.css');
listenScroll()
let srcUrl = $("#contentIframe", parent.document).attr("src")
const id = getUrlArgObjectNew("id", srcUrl) || "";
const hospitalId = getUrlArgObjectNew("hospitalId", srcUrl) || "";
const behospitalCode = getUrlArgObjectNew("behospitalCode", srcUrl) || "";
const casesEntryId = getUrlArgObjectNew("casesEntryId", srcUrl) || "";
const qcresultDetailId = getUrlArgObjectNew("qcresultDetailId", srcUrl) || "";
const appealOperationType = getUrlArgObjectNew("appealOperationType", srcUrl) || "";
const form = getUrlArgObjectNew("form", srcUrl) || "";
const page = getUrlArgObjectNew("page", srcUrl) || "";
let behosDateStart = getUrlArgObjectNew("behosDateStart", srcUrl) || ""
let behosDateEnd = getUrlArgObjectNew("behosDateEnd", srcUrl) || ""
let deptId = getUrlArgObjectNew("deptId", srcUrl) || ""
let deptName = getUrlArgObjectNew("deptName", srcUrl) || ""
let moduleName = getUrlArgObjectNew("moduleName", srcUrl) || ""
let name = getUrlArgObjectNew("name", srcUrl) || ""
let operationType = getUrlArgObjectNew("operationType", srcUrl) || ""
let state = getUrlArgObjectNew("state", srcUrl) || ""
let patientName = getUrlArgObjectNew("patientName", srcUrl) || ""
let appealInfo, appealExamineRecordDTOList, auditNumber;
(function () {
    getApprovedView()
    if (form == 2) {
        $(".bot").hide();
        $('.appealExamine h2').html('申诉信息 > 申诉审核 > 查看');
    } else if (form == 3) {
        $(".bot").hide();
        $('.appealExamine h2').html('申诉信息 > 申诉记录 > 查看');
    }
})();
//获取审核详情
function getApprovedView() {
    const param = {
        id: id,
        behospitalCode: behospitalCode,
        casesEntryId: casesEntryId,
        hospitalId: hospitalId,
        qcresultDetailId: qcresultDetailId,
    }
    return post(api.getApprovedView, param).then(res => {
        if (res.data.code == '0') {
            data = res.data.data
            console.log();
            appealExamineRecordDTOList = {
                casesEntryName: data.appealExamineRecordDTOList[data.appealExamineRecordDTOList.length - 1].casesEntryName,
                value: data.appealExamineRecordDTOList[data.appealExamineRecordDTOList.length - 1].value,
                msg: data.qcresultDetailMsg,
                explainInfo: data.appealExamineRecordDTOList[data.appealExamineRecordDTOList.length - 1].appealRemark,
            };
            appealInfo = {
                exampleOperation: 2,
                casesEntryName: data.casesEntryName,
                casesEntryMsg: data.casesEntryMsg,
                remark: data.remark,
                behospitalCode: data.behospitalCode,
                modeId: data.modeId,
                qcResultAlgVO: {
                    casesEntryId: casesEntryId,
                    id: data.qcresultDetailId,
                    casesScore: data.appealExamineRecordDTOList[data.appealExamineRecordDTOList.length - 1].casesScore,
                    msg: data.qcresultDetailMsg,
                    score: data.qcresultDetaiValue,
                    isReject: data.appealExamineRecordDTOList[data.appealExamineRecordDTOList.length - 1].isReject,
                    explainInfo: data.appealExamineRecordDTOList[data.appealExamineRecordDTOList.length - 1].appealRemark,
                }
            };
            $('.info').html('');
            $('.content').html('');
            $('.history').html('');
            getInfo(data);
            getCon(data);
            getHistory(data.appealExamineRecordDTOList)
            // getAppealInfo(id, behospitalCode, casesEntryId, hospitalId, qcresultDetailId);
        } 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 getAppealInfo(id, behospitalCode, casesEntryId, hospitalId, qcresultDetailId) {
    const param = {
        id: id,
        behospitalCode: behospitalCode,
        casesEntryId: casesEntryId,
        hospitalId: hospitalId,
        qcresultDetailId: qcresultDetailId,
    }
    return post(api.getAppealInfo, param).then(res => {
        if (res.data.code == '0') {
            data = res.data.data.appealExamineRecordDTOList
            getHistory(data)
        } 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 getInfo(data) {
    let str = ''
    str += `<span class="info-title">病案号：${data.behospitalCode || '-'}</span>
        <span class="info-title">姓名：${data.name || '-'}</span>
        <span class="info-title">性别：${data.sex || '-'}</span>
        <span class="info-title">年龄：${data.age || '-'}</span>
        <span class="info-title">科室：${data.behDeptName || '-'}</span>
        <span class="info-title">主管医生：${data.doctorName || '-'}</span>
        <span class="info-title">入院时间：${data.behospitalDate || '-'}</span>
        <span class="info-title">出院时间：${data.leaveHospitalDate || '-'}</span>`;
    $('.info').append(str);
}
function getCon(data) {
    let str = ''
    str += `<p class="con-title">申诉模块：${data.modeName || '-'}</p>
        <p class="con-title">病历内容：${data.defectContent || '-'}</p>
        <p class="con-title">缺陷详情：${data.qcresultDetailMsg || '-'}</p>
        <p class="con-title">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 评分：${data.qcresultDetaiValue == 0 ? '0' : data.qcresultDetaiValue ? -data.qcresultDetaiValue : '-'}</p>
        <p class="con-title">病案详情：<span class="goDetail">查看</span></p>`;
    $('.content').append(str);
    $('.goDetail').on('click', function (e) {
        scoreDetail(data.behospitalCode, data.age, 'YH-BLZK-ZKSSKS', data.name, data.modeName)
    })

}

function getHistory(data) {
    let str = ''
    for (let i = 0; i < data.length; i++) {
        const item = data[i]
        console.log(item);
        str += `<div class="box" style="border-top: 1px solid #333;margin-top: 10px;padding-top: 10px;">
            <p class="con-title"><span>申诉时间：${item.appealCreateDate || '-'}</span><span>申诉人：${item.claimantName || '-'}</span><span>审核人：${item.checkName || '-'}</span></p>
            <p class="con-title">操作类型：${item.appealOperationType == 0 ? '删改条目' : item.appealOperationType == 1 ? '新增已有条目' : item.appealOperationType == 2 ? '新增缺失条目' : '恢复条目'}</p>
            ${item.appealOperationType == 1 ?
                `<p class="con-title">质控条目：${item.casesEntryName || '-'}</p>
                <p class="con-title">提示信息：${item.casesEntryMsg || '-'}</p>
                <p class="con-title">分值：${item.value == 0 ? '0' : item.value ? item.value : '-'}</p>
                <p class="con-title">备注：${item.appealRemark || '-'}</p>
                `: ""}
            <p class="con-title">申诉说明：${item.appealExplain || '-'}</p>
            ${item.exampleStatus == 2 ?
                `<p class="con-title" ><span>审核时间：${item.appealExamineDate || '-'}</span><span>审核人：${item.checkName || '-'}</span></p>
                <p class="con-title">审核结果：审核通过</p>
                <p class="con-title">${item.appealOperationType == 2 ? '处理结果：' : '处理方式：'}${item.appealOperationType == 2 ? item.processResult : item.exampleOperation == 1 ? '修改' : item.exampleOperation == 2 ? '删除' : item.exampleOperation == 3 ? '新增已有' : item.exampleOperation == 4 ? '新增缺失' : '恢复'}</p>`
                : ""}
                
                ${item.exampleStatus == 2 && item.appealOperationType != 2 ?
                `<p class="con-title">质控条目：${item.casesEntryName || '-'}</p>
                <p class="con-title">提示信息：${item.msg || '-'}</p>
                <p class="con-title">分值：${item.score == 0 ? '0' : item.score ? item.score : '-'}</p>
                <p class="con-title">备注：${item.exampleRemark || '-'}</p>`
                : ""}
                ${item.exampleStatus == 1 ?
                `<p class="con-title" ><span>审核时间：${item.appealExamineDate || '-'}</span><span>审核人：${item.checkName || '-'}</span></p>
                <p class="con-title">审核结果：驳回</p>
                <p class="con-title">驳回理由：${item.rejectReason || '-'}</p>`
                : ""}
        </div>`;
    }
    $('.history').append(str);
}


function scoreDetail(id, age, code, name, casesName) {
    const logoParam = getLogoParam();
    window.open(`./appealUserPage.html?id=${id}&age=${age}&code=${code}&hid=${getCookie('hospitalid')}&name=${name}&form=44&casesName=${casesName || '缺陷总览'}` + logoParam)
}

$(document).on("click", "input[type=radio][value=1]", (e) => {
    $(".endis").attr("disabled", false);
});
$(document).on("click", "input[type=radio][value=2]", (e) => {
    $(".endis").attr("disabled", true);
});
$(document).on("click", ".btn-sure", (e) => {
    $("#delModal .modal-body").html("");
    $("#delModal .modal-header .title").html('审核');
    $("#delModal").show();
    if (appealOperationType == 0) {
        $("#appealDel").tmpl(appealExamineRecordDTOList).appendTo("#delModal .modal-body");
        $("#delModal .confirm").text("确定").unbind("click").click(function () {
            approved(1)
        });
    } else if (appealOperationType == 1) {
        $("#appealAdd").tmpl(appealExamineRecordDTOList).appendTo("#delModal .modal-body");
        $("#delModal .confirm").text("确定").unbind("click").click(function () {
            approved(2)
        });
    } else if (appealOperationType == 2) {
        $("#appealDef").tmpl(appealExamineRecordDTOList).appendTo("#delModal .modal-body");
        $("#delModal .confirm").text("确定").unbind("click").click(function () {
            approved(3)
        });
    } else if (appealOperationType == 3) {
        $("#appealRec").tmpl(appealExamineRecordDTOList).appendTo("#delModal .modal-body");
        $("#delModal .confirm").text("确定").unbind("click").click(function () {
            approved(4)
        });
    }
});



$(document).on("click", ".goback", (e) => {
    console.log(form);
    if (form == 1 || form == 2) {
        $(parent.document).find("#contentIframe").attr("src", './appealCheck.html?page=' + page + "&name=" + name + "&operationType=" + operationType + "&state=" + state + "&behosDateStart=" + behosDateStart + "&behosDateEnd=" + behosDateEnd + "&deptId=" + deptId + "&deptName=" + deptName + "&moduleName=" + moduleName);
    } else {
        $(parent.document).find("#contentIframe").attr("src", './appealHistory.html?page=' + page + "&patientName=" + patientName + "&name=" + name + "&operationType=" + operationType + "&state=" + state + "&behosDateStart=" + behosDateStart + "&behosDateEnd=" + behosDateEnd + "&deptId=" + deptId + "&deptName=" + deptName + "&moduleName=" + moduleName);
    }

});


$(document).on("click", ".btn-cancel", (e) => {
    $("#delModal .modal-body").html("");
    $("#delModal").show();
    $("#delModal .modal-header .title").html('驳回');
    $("#appealReject").tmpl(appealExamineRecordDTOList[0]).appendTo("#delModal .modal-body");
    $("#delModal .confirm").text("确定").unbind("click").click(function () {
        rejected()
    });
});
//审核
function approved(type) {
    console.log(type);
    if (type == 1) {
        appealInfo.exampleOperation = $('input:radio:checked').val()
        if ($('input:radio:checked').val() == 2) {
            appealInfo.delStatus == 0
        } else {
            appealInfo.casesEntryMsg == $(".case").val().trim()
            appealInfo.qcResultAlgVO.score = $('.score').val().trim()
            appealInfo.qcResultAlgVO.explainInfo = $('.explainInfo').val().trim()
            appealInfo.qcResultAlgVO.msg = $('.msg').val().trim()
            let val = $(".msg").val().trim()
            let score = $(".score").val().trim()
            if (!val) {
                $(".appealDel .warning .red").text("提示信息不能为空~");
                $(".appealDel .warning").show();
                return
            }
            if (!score) {
                $(".appealDel .warning .red").text("分值不能为空~");
                $(".appealDel .warning").show();
                return
            }
        }
    } else if (type == 2) {
        appealInfo.exampleOperation = 3
        appealInfo.qcResultAlgVO.score = $('.score').val().trim()
        appealInfo.qcResultAlgVO.explainInfo = $('.explainInfo').val().trim()
        appealInfo.qcResultAlgVO.msg = $('.msg').val().trim()
        let val = $(".msg").val().trim()
        let score = $(".score").val().trim()
        if (!val) {
            $(".appealAdd .warning .red").text("提示信息不能为空~");
            $(".appealAdd .warning").show();
            return
        }
        if (!score) {
            $(".appealAdd .warning .red").text("分值不能为空~");
            $(".appealAdd .warning").show();
            return
        }
        
    } else if (type == 3) {
        appealInfo.exampleOperation = 4
        appealInfo.processResult = $(".textarea").val().trim()
        let val = $(".textarea").val().trim()
        let num = 500
        if (!val) {
            $(".appealDef .warning .red").text("处理结果不能为空~");
            $(".appealDef .warning").show();
            return
        } else if (val.length > num) {
            $(".appealDef .warning .red").text("处理结果不能超过" + num + "个字~");
            $(".appealDef .warning").show();
            return
        }
    } else if (type == 4) {
        appealInfo.exampleOperation = 5
        appealInfo.qcResultAlgVO.score = $('.score').val().trim()

    }
    const param = {
        'id': id,
        ...appealInfo,
    };
    post(api.approved, param).then(function (res) {
        if (res.data.code === '0') {
            $("#delModal").hide();
            $(".bot").hide();
            getApprovedView()
            getAuditNumber()
            $.alerModal({ "message": "审核成功", type: "tip", time: '1000', win: true });
        } else {
            $.alerModal({ "message": res.data.msg || '失败,请重试~', type: "tip", time: '1000', win: 'warn' });

        }
    }).catch(() => {
        $.alerModal({ "message": '失败,请重试~', type: "tip", time: '1000', win: 'default' });

    });
}

//驳回
function rejected() {
    let val = $(".textarea2").val().trim()
    let num = 500
    if (!val) {
        $(".appealReject .warning .red").text("驳回理由不能为空~");
        $(".appealReject .warning").show();
        return
    } else if (val.length > num) {
        $(".appealReject .warning .red").text("驳回理由不能超过" + num + "个字~");
        $(".appealReject .warning").show();
        return
    }
    const param = {
        'behospitalCode': behospitalCode,
        'id': id,
        rejectedReason: $(".textarea2").val().trim()
    };
    post(api.rejected, param).then(function (res) {
        if (res.data.code === '0') {
            $("#delModal").hide();
            $(".bot").hide();
            getApprovedView()
            getAuditNumber()
            $.alerModal({ "message": "驳回成功", type: "tip", time: '1000', win: true });
        } else {
            $.alerModal({ "message": res.data.msg || '失败,请重试~', type: "tip", time: '1000', win: 'default' });
        }
    }).catch(() => {
        $.alerModal({ "message": '失败,请重试~', type: "tip", time: '1000', win: 'default' });
    });
}

//获取待审核数量
function getAuditNumber() {
    let isPlacefile = getCookie('isPlacefile') || 1
    return post(api.getAuditNumber, { analyzeType: isPlacefile }).then(res => {
        if (res.data.code == '0') {
            auditNumber = res.data.data > 99 ? '99+' : res.data.data
            if (auditNumber == 0) {
                $(".menu .page", parent.document).children('.reds').hide()
                $(".menu .dian", parent.document).hide()
                $(".menu-mini .page", parent.document).children('.reds').hide()
                $(".menu-mini .dian", parent.document).hide()
            } else {
                $(".menu .page", parent.document).children('.reds').html(auditNumber)
                $(".menu-mini .page", parent.document).children('.reds').html(auditNumber)
            }
        } 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) => {

    })
}