//@ sourceURL=west_pharmacy_send.js
var LODOP; //声明为全局变量
var zsdPrintIndex;
var bqPrintIndex;
var fskPrintIndex;
$(function () {
    openSocket("FY");


    $("input").each(function () {
        this.onkeydown = function (e) { // 监听键盘事件
            let theEvent = window.event || e;
            let code = theEvent.keyCode || theEvent.which;
            if (code == 13) {//回车事件
                $("#btn_query").click(); //触发搜索按钮点击事件
            }
        }
    });
    init_daterangepicker();
    initTbTable();
    //重置查询参数
    $('#btn_clean').click(function () {
        cleanParams();
    });

    $("#btn_query").click(function (t) {
        initTbTable();
    });
    $("#sendAndMatch").click(function (t) {
        initTbTable();
    });
    $("#btn_radiology_send").click(function (t) {
        initRadiologyTable();
    });
    $("#btn_ty").click(function (t) {
        saveRefundMedicine();
    });

    $(".selectpicker").selectpicker({
        dropuAuto: false
    });
});

/**
 * 获取按钮组选择的下标
 * @param id
 * @returns {number}
 */
function getIndex(id) {
    var index = 0;
    var item = $("#" + id).find("button");
    for (var i = 0; i <= item.length; i++) {
        if ($(item[i]).hasClass("btn-primary")) {
            index = i;
            break;
        }
    }
    return index;
}

/**
 * 设置病人id
 */
function setPatientId() {
    var patientId_or_cardNo = $("#patientId_or_cardNo").val();
    if (patientId_or_cardNo == '') {
        return $("#patientId").val("");
    }
    $.ajax({
        type: "GET",
        url: '/thmz/getByIcCardNo?icCardNo=' + patientId_or_cardNo,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                if (res.data != null) {
                    $("#patientId").val(res.data.patientId);
                } else {
                    $("#patientId").val(patientId_or_cardNo);
                }
            }
        }
    });
}

/**
 * 列表类型按钮切换事件
 * @param object
 * @param realIndex 下标
 */
function sendRefundButtonChange(object, realIndex) {
    $("#send_refund_group").find("button").each(function (index, element) {
        if ($(element).hasClass("btn-primary")) {
            $(element).removeClass("btn-primary").addClass("btn-default");
        }
    });
    if (realIndex == 0) {
        $("#confirmFlagSearch").empty();
        $("#confirmFlagSearch").append("<option value='0' selected>未发药</option>");
        $("#confirmFlagSearch").append("<option value='1'>已发药</option>");
        $("#confirmFlagSearch").selectpicker('refresh');
        $("#tb_table_right_ty").css("display", "none");
        $("#return_total_amount").css("display", "none");
        $("#btn_ty").addClass("hidden");
        $("#btn_radiology_send").removeClass("hidden");
    } else {
        $("#confirmFlagSearch").empty();
        $("#confirmFlagSearch").append("<option value='2' selected>待退药</option>");
        $("#confirmFlagSearch").append("<option value='3'>已退药</option>");
        $("#confirmFlagSearch").selectpicker('refresh');
        $("#tb_table_right_ty").css("display", "");
        $("#btn_ty").removeClass("hidden");
        $("#btn_radiology_send").addClass("hidden");
    }
    $(object).removeClass("btn-default").addClass("btn-primary");
    initTbTable();
}

/**
 * 发药处理
 */
function sendMedicineProcessing(realNo, groupNo, orderNo, receiptNo, times, patientId, name) {
    if (!confirm("确定要对当前处方进行发药处理吗？")) {
        return;
    }
    var temp = {
        groupNo: groupNo,
        realNo: realNo,
        orderNo: orderNo,
        receiptNo: receiptNo,
        times: times,
        patientId: patientId,
        name: name,
        windowsNoYf: '04'
    };
    $.ajax({
        type: "POST",
        url: '/thmz/sendMedicineProcessing',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify(temp),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                successMesage(res);
                initTbTable();
            } else {
                errorMesage(res);
            }
        }
    });
}

/**
 * 查询处方信息
 */
function initTbTable() {
    var sendRefundGroup = getIndex("send_refund_group");
    var visible = false;
    var url = "/thmz/getSendMedicinePrescription";
    if (sendRefundGroup == 1) {
        visible = true;
        url = "/thmz/getYfRefundMedicine";
        $("#tb_table_div").attr("class", "col-md-7 col-sm-7 col-xs-12");
    } else {
        $("#tb_table_div").attr("class", "");
    }
    $('#tb_table').bootstrapTable("destroy");
    $('#tb_table').bootstrapTable({
        url: url,         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: queryParams,           //传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        singleSelect: true,           // 单选checkbox
        strictSearch: true,
        showColumns: false,                  //是否显示所有的列
        showRefresh: false,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,
        //rowStyle:rowStyle,//通过自定义函数设置行样式
        ajaxOptions: {
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
            }
        },
        columns: [
            {
                title: '操作',
                align: "center",
                valign: 'middle',
                visible: !visible,
                formatter: function (value, row, index) {
                    var str = "";
                    if (sendRefundGroup == 0) {
                        str = '<button type="button" class="registration-no-color-foot-button" title="打印" onclick="printInjectionOralMedicine(\'' + row.patientId + '\',\'' + row.orderNo + '\',\'' + row.realNo + '\',\'' + row.times + '\',\'' + row.receiptNo + '\');" style="color: #35D082;"><i class="fa fa-print"></i></button>';
                        str += '<button type="button" class="registration-no-color-foot-button" title="叫号" onclick="callNumber(\'' + row.patientId + '\',\'' + row.name + '\')"><i class="glyphicon glyphicon-bullhorn"></i></button>';
                        if(row.confirmFlag ==5 || row.confirmFlag ==0){
                            str += '<button type="button" class="registration-no-color-foot-button" title="发药" onclick="sendMedicineProcessing(\'' + row.realNo + '\',\'' + 71 + '\',\'' + row.orderNo + '\',\'' + row.receiptNo + '\',\'' + row.times + '\',\'' + row.patientId + '\',\'' + row.name + '\')"><i class="fa fa-check-square-o"></i></button>';
                        }
                        str += '<button type="button" class="registration-no-color-foot-button" title="详细" onclick="prescriptionDetail(\'' + row.realNo + '\',\'' + 71 + '\',\'' + row.orderNo + '\',\'' + row.receiptNo + '\',\'' + row.times + '\',\'' + row.patientId + '\')"><i class="fa fa-plus"></i></button>';
                    }
                    return str;
                }
            },{
                field: 'checked',
                checkbox: true,
                align: "center",
                valign: 'middle',
                visible: visible,
                formatter: function (value, row, index) {
                    if (index == 0 && sendRefundGroup == 1) {
                        $("#return_total_amount").css("display", "");
                        fitfymx(row.patientId, row.times, row.receiptNo, row.orderNo, row.groupNo);
                        return {
                            checked: true//设置选中
                        };
                    }
                }
            }, {
                field: 'patientId',
                title: '病人ID',
                align: "center",
                valign: 'middle'
            }, {
                field: 'name',
                title: '姓名',
                align: "center",
                valign: 'middle'
            }, {
                field: 'orderNo',
                title: '处方号',
                align: "center",
                valign: 'middle'
            }, {
                field: 'warnDeptName',
                title: '申请科室',
                align: "center",
                valign: 'middle',
            }, {
                field: 'employeeName',
                title: '医生',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == null) {
                        return row.doctorName;
                    }
                    return value;
                }
            }, {
                field: 'chargeDate',
                title: '缴费日期',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value != null && value != "") {
                        return format(value, "yyyy-MM-dd HH:mm:ss");
                    }
                    return "";
                }
            }, {
                field: 'realNo',
                title: '流水号',
                align: "center",
                valign: 'middle',
            }, {
                field: 'confirmTime',
                title: '确认日期',
                align: "center",
                valign: 'middle',
                visible: visible,
                formatter: function (value, row, index) {
                    if (value != null && value != "") {
                        return format(value, "yyyy-MM-dd HH:mm:ss");
                    }
                    return "";
                }
            }
            /*, {
                field: 'doctorFlag',
                title: '医生处方',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value == 1 ? "是" : "否";
                }
            }*/
        ],
        onClickRow: function (row) {
            if (sendRefundGroup == 1) {
                fitfymx(row.patientId, row.times, row.receiptNo, row.orderNo, row.groupNo);
            }
        },
        onDblClickRow: function (row) {
            if (sendRefundGroup == 0) {
                printInjectionOralMedicine(row.patientId, row.orderNo, row.realNo, row.times, row.receiptNo);
            }
        },
        responseHandler: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var ress = eval(res);
            if (ress.code == -1) {
                if (ress.message != null && ress.message != '') {
                    new PNotify({
                        title: '错误提示',
                        text: ress.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
                return {
                    "total": 0,//总页数
                    "rows": {}   //数据
                };
            }
            return {
                "total": ress.total,//总页数
                "rows": ress.data   //数据
            };
        },
    });
}

/**
 * 加载放射科发药记录
 */
function initRadiologyTable() {
    $('#rad_send_record_table').bootstrapTable("destroy");
    $('#rad_send_record_table').bootstrapTable({
        url: "/thmz/getRadSendRecord",         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: radSendRecordQueryParams,           //传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 5,                       //每页的记录行数（*）
        pageList: [5],        //可供选择的每页的行数（*）
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        singleSelect: true,           // 单选checkbox
        strictSearch: true,
        showColumns: false,                  //是否显示所有的列
        showRefresh: false,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,
        paginationDetailHAlign: ' hidden',//隐藏左侧分页信息
        toolbar:'#rad_send_record_toolbar',
        //rowStyle:rowStyle,//通过自定义函数设置行样式
        ajaxOptions: {
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
            }
        },
        columns: [
            {
                field: 'startDate',
                title: '起始时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (index == 0) {
                        initRadiologyStatTable(row.sendDate);
                    }
                    if (value != null && value != "") {
                        return format(value, "yyyy-MM-dd");
                    }
                    return "";
                }
            }, {
                field: 'endDate',
                title: '截止时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (index == 0) {
                        initRadiologyStatTable(row.sendDate);
                    }
                    if (value != null && value != "") {
                        return format(value, "yyyy-MM-dd");
                    }
                    return "";
                }
            }, {
                field: 'name',
                title: '发药人',
                align: "center",
                valign: 'middle'
            }, {
                field: 'sendDate',
                title: '发药时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value != null && value != "") {
                        return format(value, "yyyy-MM-dd");
                    }
                    return "-";
                }
            }
            , {
                title: '操作',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    row.sendDate = (row.sendDate == null) ? '' : row.sendDate;
                    var str = '<button type="button" class="registration-no-color-foot-button" title="打印" onclick="printRadSendMedicineStat(\'' + row.sendDate + '\',\'' + row.startDate + '\',\'' + row.endDate + '\');" style="color: #35D082;background:#fff"><i class="fa fa-print"></i></button>';
                    if (index == 0 && row.pageIndex == 0) {
                        str += '<button type="button" class="registration-no-color-foot-button" title="发药" onclick="sendMedicineProcessingRad()" style="background:#fff"><i class="fa fa-check-square-o"></i></button>';
                    }
                    return str;
                }
            }
        ],
        onClickRow: function (row) {
            initRadiologyStatTable(row.sendDate);
        },
        onDblClickRow: function (row) {
            printRadSendMedicineStat(row.sendDate,row.startDate,row.endDate);
        },
        responseHandler: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var ress = eval(res);
            if (ress.code == -1) {
                if (ress.message != null && ress.message != '') {
                    new PNotify({
                        title: '错误提示',
                        text: ress.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
                return {
                    "total": 0,//总页数
                    "rows": {}   //数据
                };
            }
            return {
                "total": ress.total,//总页数
                "rows": ress.data   //数据
            };
        },
    });
    $("#radiologySendModal").modal();
}

/**
 * 加载放射科发药统计表格数据
 * @param sendDate
 */
function initRadiologyStatTable(sendDate) {
    sendDate = (sendDate == null) ? '' : sendDate;
    $('#rad_send_stat_table').bootstrapTable("destroy");
    $('#rad_send_stat_table').bootstrapTable({
        url: "/thmz/getRadSendStat?confirmTime=" + sendDate,         //请求后台的URL（*）
        method: 'GET',                      //请求方式（*）
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: {},           //传递参数（*）
        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        singleSelect: true,           // 单选checkbox
        strictSearch: true,
        showColumns: false,                  //是否显示所有的列
        showRefresh: false,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,
        paginationDetailHAlign: ' hidden',//隐藏左侧分页信息
        toolbar:'#rad_send_stat_toolbar',
        //rowStyle:rowStyle,//通过自定义函数设置行样式
        ajaxOptions: {
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
            }
        },
        columns: [
            {
                field: 'location',
                title: '货位号',
                align: "center",
                valign: 'middle'
            }, {
                field: 'name',
                title: '品名',
                align: "center",
                valign: 'middle'
            }, {
                field: 'manuName',
                title: '厂商',
                align: "center",
                valign: 'middle'
            }, {
                field: 'specification',
                title: '规格',
                align: "center",
                valign: 'middle'
            }, {
                field: 'quantity',
                title: '<span style="color: green">数量</span>',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return '<span style="color: green">' + value + '</span>'
                }
            }, {
                field: 'stockAmount',
                title: '库存',
                align: "center",
                valign: 'middle'
            }
        ],
        responseHandler: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var ress = eval(res);
            if (ress.code == -1) {
                if (ress.message != null && ress.message != '') {
                    new PNotify({
                        title: '错误提示',
                        text: ress.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
                return {
                    "total": 0,//总页数
                    "rows": {}   //数据
                };
            }
            return {
                "total": ress.total,//总页数
                "rows": ress.data   //数据
            };
        },
    });
}

/**
 * 放射科发药处理
 */
function sendMedicineProcessingRad() {
    if (!confirm("确定要进行发药处理吗？")) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/sendMedicineProcessingRad',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: {},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                successMesage(res);
                initRadiologyTable();
            } else {
                errorMesage(res);
            }
        }
    });
}

/**
 * 打印注射卡口服药品
 */
function printInjectionOralMedicine(patientId, orderNo, realNo, times, receiptNo) {
    var tem = {
        patientId: patientId,
        orderNo: orderNo,
        realNo: realNo,
        times: times,
        receiptNo: receiptNo,
        groupNo: 71
    };
    $.ajax({
        type: "POST",
        url: '/thmz/getPrintInjectionData',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify(tem),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                var injections = new Array();//注射液
                var drugs = new Array();//普通药品
                for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].classCode == 2 || res.data[i].classCode == 7) {//给药方式 2：输液、雾化吸入、副药等等 7：注射、皮试、副药等等
                        injections[injections.length] = res.data[i];
                    } else if (res.data[i].classCode != 6) {//给药方式 6：领药 9：外用、局麻、喷用等等
                        drugs[drugs.length] = res.data[i];
                    }
                }
                if (injections.length == 0 && drugs.length == 0) {
                    return errorMesageSimaple('当前处方，无需打印注射单和标签');
                }
                let age = getBirthSlot(res.data[0].birthDay,res.data[0].priceTime);
                if(age.substring(0,age.indexOf('岁')) >= 7){
                    age = age.substring(0,age.indexOf('岁')+1);
                }
                setPrint();
                if (injections.length > 0) {
                    $(".zsd_two_tr").remove();
                    $(".zsd_one_tr").remove();
                    $(".zsd_yp_tr").remove();
                    $("#dateTime").html(format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    var sex = '';
                    if (res.data[0].sex == 1) {
                        sex = '男';
                    } else if (res.data[0].sex == 2) {
                        sex = '女';
                    } else {
                        sex = '未知';
                    }
                    var patientInfoHtm = '<tr class="zsd_one_tr">\n' +
                        '                                        <td style="vertical-align: middle !important;width: 35px;text-align: center;"\n' +
                        '                                            valign="top">姓名\n' +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 75px;">\n' + res.data[0].name +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 55px;text-align: center;">\n' +
                        '                                            性别\n' +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 45px;text-align: left;">\n' + sex +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 55px;text-align: center;">\n' +
                        '                                            年龄\n' +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 55px;text-align: left;">\n' + age +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 65px;text-align: center;">\n' +
                        '                                            ID号\n' +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 55px;text-align: left;">\n' + res.data[0].patientId +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 55px;text-align: center;">\n' +
                        '                                            诊断\n' +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 135px;text-align: left;">\n' + res.data[0].icdText +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 55px;text-align: center;">\n' +
                        '                                            医生\n' +
                        '                                        </td>\n' +
                        '                                        <td style="vertical-align: middle !important;width: 55px;text-align: left;">\n' + res.data[0].employeeName +
                        '                                        </td>\n' +
                        '                                    </tr>';
                    $('#zsd_one').prepend(patientInfoHtm);
                    var zsdYpHtm = '';
                    for (let i = 0; i < injections.length; i++) {
                        let data = injections[i];
                        let manufactoryName = (data.manufactoryName == null || data.manufactoryName == '') ? '' : '(' + data.manufactoryName + ')';
                        let groupOrder = (data.groupOrder == '' || data.groupOrder == null) ? data.chargeItemCode : data.groupOrder;
                        zsdYpHtm += '<tr class="zsd_yp_tr">\n' +
                            '                                                    <td>&nbsp;&nbsp;</td>\n' +
                            '                                                    <td style="vertical-align: middle !important;width: 10px;text-align: center;">\n' + groupOrder +
                            '                                                    </td>\n' +
                            '                                                    <td style="vertical-align: middle !important;width: 200px;text-align: center;">\n' + data.drugname + manufactoryName +
                            '                                                    </td>\n' +
                            '                                                    <td style="vertical-align: middle !important;width: 60px;text-align: center;">\n' + data.drugQuan +
                            '                                                    </td>\n' +
                            '                                                    <td style="vertical-align: middle !important;width: 60px;text-align: center;">\n' + data.drugUnitName +
                            '                                                    </td>\n' +
                            '                                                    <td style="vertical-align: middle !important;width: 120px;text-align: center;">\n' + data.printName +
                            '                                                    </td>\n' +
                            '                                                    <td style="vertical-align: middle !important;width: 60px;text-align: center;">\n' + data.frequency +
                            '                                                    </td>\n' +
                            '                                                    <td style="vertical-align: middle !important;width: 60px;text-align: center;">\n' + data.orderDays +
                            '                                                    </td>\n' +
                            '                                                    <td style="vertical-align: middle !important;width: 120px;text-align: left;">\n' + data.specification +
                            '                                                    </td>\n' +
                            '                                                </tr>';
                    }
                    $('#zsd_yp').append(zsdYpHtm);
                    var htm = '';
                    for (let i = 0; i < 10; i++) {
                        htm += '<tr class="zsd_two_tr">\n' +
                            '                                        <td style="vertical-align: middle !important;width: 30px;text-align: center;">&nbsp;&nbsp;月&nbsp;&nbsp;日</td>\n' +
                            '                                        <td style="vertical-align: middle !important;width: 30px;text-align: right;"></td>\n' +
                            '                                        <td style="vertical-align: middle !important;width: 30px;text-align: right;"></td>\n' +
                            '                                        <td style="vertical-align: middle !important;width: 30px;text-align: right;"></td>\n' +
                            '                                        <td style="vertical-align: middle !important;width: 30px;text-align: right;"></td>\n' +
                            '                                        <td style="vertical-align: middle !important;width: 30px;text-align: center;">&nbsp;&nbsp;月&nbsp;&nbsp;日</td>\n' +
                            '                                        <td style="vertical-align: middle !important;width: 30px;text-align: right;"></td>\n' +
                            '                                        <td style="vertical-align: middle !important;width: 30px;text-align: right;"></td>\n' +
                            '                                        <td style="vertical-align: middle !important;width: 30px;text-align: right;"></td>\n' +
                            '                                        <td style="vertical-align: middle !important;width: 30px;text-align: right;"></td>\n' +
                            '                                    </tr>';
                    }
                    $('#zsd_two').append(htm);
                    LODOP = getLodop();
                    LODOP.PRINT_INITA(6, 0, "210mm", "148mm", "泰和医院门、急诊注射单");
                    LODOP.SET_PRINT_STYLE("FontSize", 9); //字体大小
                    //设置默认打印机
                    LODOP.SET_PRINTER_INDEX(zsdPrintIndex);
                    LODOP.SET_PRINT_PAGESIZE(1, '210mm', '148mm', "CreateCustomPage");
                    LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "210mm");
                    LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", "148mm");
                    LODOP.SET_PRINT_MODE("CREATE_CUSTOM_PAGE_NAME", "泰和医院门、急诊注射单");//对新建的纸张重命名
                    LODOP.ADD_PRINT_HTM("5mm", "3mm", "210mm", "148mm", $("div[id='print_view_zsd']").html());
                    LODOP.PRINT();
                    //LODOP.PREVIEW();
                }
                if (drugs.length > 0) {
                    LODOP = getLodop();
                    LODOP.PRINT_INITA(6, 0, "80mm", "60mm", "患者药品标签");
                    LODOP.SET_PRINT_STYLE("FontSize", 9); //字体大小
                    //设置默认打印机
                    LODOP.SET_PRINTER_INDEX(bqPrintIndex);
                    LODOP.SET_PRINT_PAGESIZE(1, '80mm', '60mm', "CreateCustomPage");
                    LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "80mm");
                    LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", "60mm");
                    LODOP.SET_PRINT_MODE("CREATE_CUSTOM_PAGE_NAME", "患者药品标签");//对新建的纸张重命名
                    for (let j = 0; j < drugs.length; j++) {
                        for (var key in drugs[j]) {
                            $("#ypbq_" + key + "").attr("value", drugs[j][key]);
                            $("#ypbq_quantity").attr("value", parseInt(drugs[j]['quantity']));
                        }
                        $("#dataTime").attr("value", format(new Date(), "yyyy-MM-dd HH:mm"));
                        $("#ypbq_sex").attr("value", getSex(drugs[0].sex));
                        $("#ypbq_age").attr("value", age);
                        $("#NO").attr("value", j + 1 + "/" + drugs.length);
                        if(drugs[j].drugUnitName == '粒' || drugs[j].drugUnitName == '片'|| drugs[j].drugUnitName == '支'){
                            $("#ypbq_comm").attr("value", drugs[j].comm + ',每次' + drugs[j].drugQuan + drugs[j].drugUnitName);
                        }else if((drugs[j].weight == null && drugs[j].volum == null) || (drugs[j].weight != null && drugs[j].volum != null)){
                            $("#ypbq_comm").attr("value", drugs[j].comm + ',每次' + drugs[j].drugQuan + drugs[j].drugUnitName);
                        }else{
                            let weight = (drugs[j].weight == '' || drugs[j].weight == null) ? drugs[j].volum : drugs[j].weight;
                            var drugQuan = (drugs[j].drugQuan / weight).toFixed(2);
                            if(drugQuan == 0.5) {
                                $("#ypbq_comm").attr("value", drugs[j].comm + ',每次半' + drugs[j].miniUnitName);
                            } else if(drugQuan < 1){
                                $("#ypbq_comm").attr("value", drugs[j].comm + ',每次' + drugs[j].drugQuan + drugs[j].drugUnitName);
                            }else{
                                drugQuan = Math.round(drugQuan*100)/100;
                                $("#ypbq_comm").attr("value", drugs[j].comm + ',每次' + drugQuan + drugs[j].miniUnitName);
                            }
                        }
                        LODOP.ADD_PRINT_HTM("5mm", "5mm", "80mm", "60mm", $("div[id='print_view_bq']").html());
                        LODOP.NewPage();//下一页
                    }
                    LODOP.PRINT();
                    //LODOP.PREVIEW();
                }
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}

/**
 * 打印放射科发药药品统计
 */
function printRadSendMedicineStat(sendDate,startDate,endDate) {
    $.ajax({
        type: "GET",
        url: "/thmz/getPrintRadSendStat?confirmTime=" + sendDate,         //请求后台的URL（*）
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: {},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                var list = res.data;
                if (list.length == 0) {
                    return errorMesageSimaple('当前记录无发药药品统计数据');
                }
                $(".fsk_tr").remove();
                var htm = '';
                for (let i = 0; i < list.length; i++) {
                    var data = list[i];
                    htm += '<tr class="fsk_tr">' +
                        '                                <td style="vertical-align: middle !important;width: 30px;text-align: center;">' +(data.location==null?'-':data.location)+
                        '                                </td>' +
                        '                                <td style="vertical-align: middle !important;width: 30px;text-align: center;">' +data.name+
                        '                                </td>' +
                        '                                <td style="vertical-align: middle !important;width: 30px;text-align: center;">' +data.manuName+
                        '                                </td>' +
                        '                                <td style="vertical-align: middle !important;width: 30px;text-align: center;">' +data.specification+
                        '                                </td>' +
                        '                                <td style="vertical-align: middle !important;width: 30px;text-align: center;">' +data.quantity+
                        '                                </td>' +
                        '                            </tr>';
                }
                $('#fsk_tbody').append(htm);
                $('#startDate').html(format(startDate, "yyyy-MM-dd"));
                $('#endDate').html(format(endDate, "yyyy-MM-dd"));
                setPrint();
                LODOP = getLodop();
                LODOP.PRINT_INITA(6, 0, "241mm", "93.3mm", "放射科发药记录单");
                LODOP.SET_PRINT_STYLE("FontSize", 9); //字体大小
                //设置默认打印机
                LODOP.SET_PRINTER_INDEX(fskPrintIndex);
                LODOP.SET_PRINT_PAGESIZE(1, '241mm', '93.3mm', "CreateCustomPage");
                LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "241mm");
                LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", "93.3mm");
                LODOP.SET_PRINT_MODE("CREATE_CUSTOM_PAGE_NAME", "放射科发药记录单");//对新建的纸张重命名
                LODOP.ADD_PRINT_HTM("5mm", "20%", "60%", "93.3mm", $("div[id='print_view_fsk']").html());
                LODOP.PRINT();
                //LODOP.PREVIEW();
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}

/**
 * 返回性别
 */
function getSex(code) {
    var sex = '';
    if (code == 1) {
        sex = '男';
    } else if (code == 2) {
        sex = '女';
    } else {
        sex = '未知';
    }
    return sex;
}

/**
 * 已发药和未发药记录构建列表查询参数
 * @param params
 */
function queryParams(params) {
    var rePortRangeArr = getRePortRangeArr();
    var temp = {
        pageSize: params.limit,   //页面大小
        pageIndex: params.offset / params.limit,  //页码
        beginDate: rePortRangeArr[0],
        endDate: rePortRangeArr[1],
        name: $("#nameSearch").val() == "" ? null : $("#nameSearch").val(),
        patientId: $("#patientId").val() == "" ? null : $("#patientId").val(),
        confirmFlag: $("#confirmFlagSearch").val(),
        realNo: $("#realNoSearch").val() == "" ? null : $("#realNoSearch").val(),
        groupNoOut: '71',
        isSendAndMatch: $('#sendAndMatch').prop('checked')?1:0
    };
    return temp;
};

/**
 * 放射科发药记录构建列表查询参数
 * @param params
 */
function radSendRecordQueryParams(params) {
    var temp = {
        pageSize: params.limit,   //页面大小
        pageIndex: params.offset / params.limit  //页码
    };
    return temp;
};

/**
 * 获取时间选择器的时间数组
 * @returns {string[]}
 */
function getRePortRangeArr() {
    var rePortRange = $('#reportrange span').html();
    var rePortRangeArr = rePortRange.split(" - ");
    rePortRangeArr[0] = rePortRangeArr[0] + " 00:00:00"
    rePortRangeArr[1] = rePortRangeArr[1] + " 23:59:59"
    return rePortRangeArr;
}


/**
 * 清空查询条件
 */
function cleanParams() {
    $('#reportrange span').html(moment().format('YYYY-MM-DD') + ' - ' + moment().format('YYYY-MM-DD'));
    $("#nameSearch").val(null);
    $("#patientId_or_cardNo").val(null);
    $("#patientIdSearch").val(null);
    $("#realNoSearch").val(null);
    var sendRefundGroup = getIndex("send_refund_group");
    sendRefundGroup == 0 ? $("#confirmFlagSearch").selectpicker('val', 0) : $("#confirmFlagSearch").selectpicker('val', 2);
    $("#confirmFlagSearch").selectpicker('refresh');
    $("#patientId_or_cardNo").focus();
}


/**
 * 查询病人处方明细
 */
var $table;

function prescriptionDetail(realNo, groupNo, orderNo, receiptNo, times, patientId) {
    var temp = {
        groupNo: groupNo,
        realNo: realNo,
        orderNo: orderNo,
        receiptNo: receiptNo,
        times: times,
        patientId: patientId
    };
    $('#tb_table_right').bootstrapTable("destroy");
    $table = $('#tb_table_right').bootstrapTable({
        url: '/thmz/getFyclPrescriptionDetail',         //请求后台的URL（*）
        method: 'POST',                      //请求方式（*）
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: JSON.stringify(temp),           //传递参数（*）
        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        strictSearch: true,
        showColumns: false,                  //是否显示所有的列
        showRefresh: false,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,
        //rowStyle:rowStyle,//通过自定义函数设置行样式
        ajaxOptions: {
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
            }
        },
        columns: [
            {
                field: 'location',
                title: '货位号',
                align: "center",
                valign: 'middle'
            }, {
                field: 'drugname',
                title: '品名',
                align: "center",
                valign: 'middle',
            }, {
                field: 'specification',
                title: '规格',
                align: "center",
                valign: 'middle',
            }, {
                field: 'quantity',
                title: '<span style="color: green">数量</span>',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return '<span style="color: green">' + value + '</span>'
                }
            }, {
                field: 'ypUnitName',
                title: '单位',
                align: "center",
                valign: 'middle',
            }, {
                field: 'abbrName',
                title: '生产厂家',
                align: "center",
                valign: 'middle',
            }, {
                field: 'drugQuan',
                title: '一次剂量',
                align: "center",
                valign: 'middle',
            }, {
                field: 'drugUnitName',
                title: '单位',
                align: "center",
                valign: 'middle',
            }, {
                field: 'frequency',
                title: '频率',
                align: "center",
                valign: 'middle',
            }, {
                field: 'decAmount',
                title: '<span style="color: red">退药量</span>',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value == null ? '<span style="color: red">-</span>' : '<span style="color: red">' + value + '</span>'
                }
            }, {
                field: 'printName',
                title: '给药方式',
                align: "center",
                valign: 'middle',
            }, {
                field: 'unitPrice',
                title: '单价',
                align: "center",
                valign: 'middle',
            }
             , {
                 field: 'drugFlag',//毒麻标志:1:毒;2:麻;3:精神1;4:精神2
                 title: '<span style="color: red">毒麻</span>',
                 align: "center",
                 valign: 'middle',
                 formatter: function (value, row, index) {
                     if(value == 1){
                         return '<span style="color: red">毒</span>'
                     }else if(value == 2){
                         return '<span style="color: red">麻</span>'
                     }else if(value == 3){
                         return '<span style="color: red">精神1</span>'
                     }else if(value == 3){
                         return '<span style="color: red">精神2</span>'
                     }else{
                         return '<span style="color: red">-</span>'
                     }
                 }
             }
            , {
                field: 'stockAmount',
                title: '当前库存',
                align: "center",
                valign: 'middle',
            }
        ],
        responseHandler: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var ress = eval(res);
            if (ress.data.length > 0) {
                $("#employeeNameLabel").val(ress.data[0].employeeName);
                $("#warnDeptNameLabel").val(ress.data[0].warnDeptName);
                $("#chargeDateLabel").val(format(ress.data[0].chargeDate, "yyyy-MM-dd HH:mm:ss"));
                $("#icdTextLabel").val(ress.data[0].icdText);
            }
            if (ress.code == -1) {
                if (ress.message != null && ress.message != '') {
                    new PNotify({
                        title: '错误提示',
                        text: ress.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
                return {
                    "total": 0,//总页数
                    "rows": {}   //数据
                };
            }
            return {
                "total": ress.data.length,//总页数
                "rows": ress.data   //数据
            };
        },
        onLoadSuccess: function (res) {  //加载成功时执行
            var sendTotalAmount = 0;
            for (var i=0;i<res.rows.length;i++) {
                sendTotalAmount +=parseFloat(res.rows[i].quantity*res.rows[i].unitPrice);
            }
            $('#sendTotalAmount').html(sendTotalAmount.toFixed(2));//toFixed(2),保留2位小数,避免js中小数相加小数点后面多出很多位
        },
    });
    $("#cfxxModal").modal();
}

/**
 * 查询病人处方药品明细
 */
function fitfymx(patientId, times, receiptNo, orderNo, groupNoOut) {
    var temp = {
        patientId: patientId,
        times: times,
        receiptNo: receiptNo,
        orderNo: orderNo,
        groupNoOut: groupNoOut,
        confirmFlag: $("#confirmFlagSearch").val()
    };
    $('#tb_table_right_ty').bootstrapTable("destroy");
    $table = $('#tb_table_right_ty').bootstrapTable({
        url: '/thmz/getRefundYpMx',         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: temp,           //传递参数（*）
        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        strictSearch: true,
        showColumns: false,                  //是否显示所有的列
        showRefresh: false,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,
        paginationDetailHAlign: ' hidden',//隐藏左侧分页信息
        //rowStyle:rowStyle,//通过自定义函数设置行样式
        ajaxOptions: {
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
            }
        },
        columns: [
            {
                field: 'drugname',
                title: '品名',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value != null && value != "") {
                        return value.replace("()", "");
                    }
                    return "";
                }
            }, {
                field: 'specification',
                title: '规格',
                align: "center",
                valign: 'middle',
            }, {
                field: 'quantity',
                title: '数量',
                align: "center",
                valign: 'middle',
            }, {
                field: 'unit_price',
                title: '单价',
                align: "center",
                valign: 'middle',
            }, {
                field: 'dec_amount',
                title: '<span style="color: red">退药量</span>',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return '<span style="color: red">' + value + '</span>'
                }
            }
        ],
        responseHandler: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var ress = eval(res);
            if (ress.code == -1) {
                if (ress.message != null && ress.message != '') {
                    new PNotify({
                        title: '错误提示',
                        text: ress.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
                return {
                    "total": 0,//总页数
                    "rows": {}   //数据
                };
            }
            return {
                "total": ress.data.length,//总页数
                "rows": ress.data   //数据
            };
        },
        onLoadSuccess: function (res) {  //加载成功时执行
            var returnTotalAmount = 0;
            for (var i=0;i<res.rows.length;i++) {
                returnTotalAmount +=parseFloat(res.rows[i].quantity*res.rows[i].unit_price);
            }
            $('#returnTotalAmount').html(returnTotalAmount.toFixed(2));//toFixed(2),保留2位小数,避免js中小数相加小数点后面多出很多位
        },
    });
}


/**
 * 退药处理
 */
function saveRefundMedicine() {
    var row = $("#tb_table").bootstrapTable('getSelections');
    if(row.length < 1){
        return errorMesageSimaple('请先选择一条处方数据');
    }
    if(row[0].confirmFlag == 3){
        return errorMesageSimaple('请勿重复退药');
    }
    var data = $table.bootstrapTable('getData');
    var datas = [];
    var i = 0;
    data.forEach(function (item, index, arr) {
        if (item.dec_amount != 0) {
            var tem = {
                "patientId": item.patient_id,
                "times": item.times,
                "receiptNo": item.receipt_no,
                "orderNo": item.order_no,
                "realNo": item.real_no,
                "decAmount": item.dec_amount,
                "unitPrice": item.unit_price,
                "chargeCode": item.charge_item_code,
                "serial": item.serial,
                "groupNo": item.group_no,
                "itemNo": item.item_no,
                "serialNo": item.serial_no
            }
            datas[i] = tem;
            i++;
        }
    })
    if (datas.length == 0) {
        return errorMesageSimaple('退药处方可退药药品为空');
    }
    if (!confirm("确定要对当前处方的药品进行退药处理吗？")) {
        return;
    }
    $.ajax({
        type: "POST",
        url: '/thmz/refundMedicineProcessing',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify(datas),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                successMesage(res);
                initTbTable();
            } else {
                errorMesage(res);
            }
        }
    });
}

/**
 * 叫号
 * @param patientId
 * @param name
 */
function callNumber(patientId,name) {
    $.ajax({
        type: "GET",
        url: '/thmz/callNumber?patientId=' + patientId+"&name="+name,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}

/**
 * 查询默认打印机
 */
function setPrint() {
    if (zsdPrintIndex >= 0 && bqPrintIndex >= 0 && fskPrintIndex >= 0) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/getLastDispensingWindowsByCurrentUser',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        async: false,
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                zsdPrintIndex = res.data.zsdPrintIndex;
                bqPrintIndex = res.data.bqPrintIndex;
                fskPrintIndex = res.data.fskPrintIndex;
            } else {
                zsdPrintIndex = -1;
                bqPrintIndex = -1;
                fskPrintIndex = -1;
            }
        }
    });
}






