//@ sourceURL=west_pharmacy_dispensing.js
var LODOP; //声明为全局变量
var printIndex;
var mzCfPrintIndex;
var ekCfPrintIndex;
var jzCfPrintIndex;
$(function () {
    openSocket("PY");

    $("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();
    initTable();
    $('#dispensingStatusSearch').selectpicker('refresh');
    $("#btn_query").click(function (t) {
        initTable();
    });
    //重置查询参数
    $('#btn_clean').click(function () {
        cleanParams();
    });
});


/**
 * 获取按钮组选择的下标
 * @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;
}

/**
 * 查询处方信息
 */
function initTable() {
    $('#prescription_table').bootstrapTable("destroy");
    $('#prescription_table').bootstrapTable({
        url: '/thmz/listMzChargeOrder',         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: queryParams,           //传递参数（*）
        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: [
            {
                title: '操作',
                field: 'op',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    var str = '<button type="button" class="registration-no-color-foot-button" title="打印" onclick="printPrescription(\'' + row.patientId + '\',\'' + row.times+ '\',\'' + row.orderNo + '\')"  style="color: #35D082;"><i class="fa fa-print"></i></button>';
                    if(row.isRadSend == 0 && row.confirmFlag !=5 && row.confirmFlag !=1){
                        str += '<button type="button" class="registration-no-color-foot-button" title="配药完成" onclick="dispensingDispose(\'' + row.patientId + '\',\'' + row.orderNo + '\',\'' + row.times + '\')"><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: 'no',
                title: '序号',
                align: "center",
                valign: 'middle',
                width: 40,
                formatter: function (value, row, index) {
                    return index + 1;
                }
            }, {
                field: 'patientId',
                title: '病人ID',
                align: "center",
                valign: 'middle'
            }, {
                field: 'name',
                title: '病人姓名',
                align: "center",
                valign: 'middle'
            }, {
                field: 'realNo',
                title: '流水号',
                align: "center",
                valign: 'middle'
            }, {
                field: 'orderNo',
                title: '处方号',
                align: "center",
                valign: 'middle'
            }, {
                field: 'chargeDate',
                title: '缴费时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value == null ? "-" : format(value, "yyyy-MM-dd HH:mm:ss");
                }
            }
        ],
        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   //数据
            };
        },

        onDblClickRow: function (row) {
            printPrescription(row.patientId,row.times,row.orderNo);
        }
    });
}

/**
 * 查询病人处方明细
 */
function prescriptionDetail(realNo, groupNo, orderNo, receiptNo, times, patientId) {
    var temp = {
        groupNo: groupNo,
        realNo: realNo,
        orderNo: orderNo,
        receiptNo: receiptNo,
        times: times,
        patientId: patientId
    };
    $('#tb_table_detail').bootstrapTable("destroy");
    $('#tb_table_detail').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   //数据
            };
        },
    });
    $("#cfxxModal").modal();
}

/**
 * 构建列表查询参数
 * @param params
 */
function queryParams(params) {
    var rePortRangeArr = getRePortRangeArr();
    var temp = {
        /* pageSize: params.limit,   //页面大小
         pageIndex: params.offset / params.limit,  //页码*/
        beginTime: new Date(rePortRangeArr[0]),
        endTime: new Date(rePortRangeArr[1]),
        mzChargeDetail: {
            patientId: $("#patientIdSearch").val() == "" ? null : $("#patientIdSearch").val(),
            name: $("#nameSearch").val() == "" ? null : $("#nameSearch").val(),
            confirmFlag: $("#dispensingStatusSearch").val() == "" ? null : $("#dispensingStatusSearch").val(),
            payMark: 0, //已收费
            groupNo: 71, //门诊西药房
            windowsNoYf: '04' //4号窗口
        }
    };
    return temp;
};

/**
 * 配药处理
 */
function dispensingDispose(patientId, orderNo, times) {
    /*if (!confirm("确定要对当前处方进行配药处理吗？")) {
        return;
    }*/
    var tem = {
        "patientId": patientId,
        "orderNo": orderNo,
        "times": times
    }
    $.ajax({
        type: "POST",
        url: '/thmz/dispensingMedicineProcessing',
        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) {
                successMesage(res);
                initTable();
            } else {
                errorMesage(res);
            }
        }
    });
}

/**
 * 打印处方
 */
function printPrescription(patientId, times, orderNo) {
    var tem = {
        patientId: patientId,
        times: times,
        orderNo: orderNo,
        groupNo: 71
    };
    $.ajax({
        type: "POST",
        url: '/thmz/getPrintPrescriptionData',
        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) {
                setPrint();//初始化默认打印机
                $('#print_view input').attr("value", "");
                if (null != res.data) {
                    for (var key in res.data) {
                        $("#" + key + "").attr("value", res.data[key]);
                    }
                    var age = getBirthSlot(res.data['birthDay'],res.data.list[0].priceTime);
                    if(res.data['age'] < 7){
                        $("#age").attr("value", age);
                    }else{
                        $("#age").attr("value", age.substring(0,age.indexOf('岁')+1));
                    }
                }
                var list = res.data.list;
                if (res.data.age < 18) {
                    $('#drugFlag').attr("value", "儿科");
                    printIndex = ekCfPrintIndex;
                } else if (res.data.warnDeptName.indexOf("急诊") != -1) {
                    $('#drugFlag').attr("value", "急诊");
                    printIndex = jzCfPrintIndex;
                } else{
                    $('#drugFlag').attr("value", "普通");
                    printIndex = mzCfPrintIndex;
                }
                if (list[0].drugFlag == 2 || list[0].drugFlag == 3) {
                    $('#drugFlag').attr("value", "麻、精一");
                } else if (list[0].drugFlag == 4) {
                    $('#drugFlag').attr("value", "精二");
                }
                $('#priceTime').attr("value", format(list[0].priceTime, "yyyy-MM-dd HH:mm"));
                $('#employeeName').attr("value", res.data.employeeName + "/" + res.data.employeeCode);
                if (res.data.sex == 1) {
                    $('#sex').attr("value", '男');
                } else if (res.data.sex == 2) {
                    $('#sex').attr("value", '女');
                } else {
                    $('#sex').attr("value", '未知');
                }
                if(res.data.ybCardNo == null || res.data.ybCardNo == ''){
                    $('#ybCardNo').attr("value", res.data.icCardNo);
                }
                var tr = '';
                for (let i = 0; i < list.length; i++) {
                    let printName = list[i].printName==null?"":list[i].printName;
                    let tryResult = '';
                    let tryFlag = '';
                    if(list[i].tryResult == 0){
                        tryResult = '(—)';
                    }else if(list[i].psFlag == 1 && list[i].tryFlag == 0){//药品需要皮试，处方未点需要皮试
                        tryResult = '<span style="color: red">(免试)</span>';
                    }
                    if(list[i].tryFlag == 1){
                        tryFlag = '<span style="color: red">(需皮试)</span>';
                    }
                    var number = i + 1;
                    let manufactoryName = list[i].manufactoryName == null || list[i].manufactoryName == '' ? '' : '(' + list[i].manufactoryName + ')';
                    tr += '<tr>\n' +
                        '                                <td style="margin-bottom: 5px;width: 10px;font-size: 14px;" align="left" valign="top">' + number + "." +
                        '</td>\n' +
                        '                                <td style="margin-bottom: 5px;vertical-align: middle !important;width: 260px;font-size: 14px;">\n' + tryResult + tryFlag + list[i].drugName +
                        '                                </td>\n' +
                        '                                <td style="margin-bottom: 5px;vertical-align: middle !important;width: 120px;text-align: right;font-size: 14px;">' + list[i].specification +
                        '</td>\n' +
                        '                                <td style="margin-bottom: 5px;vertical-align: middle !important;width: 15px;text-align: left;font-size: 14px;">×</td>\n' +
                        '                                <td style="margin-bottom: 5px;vertical-align: middle !important;width: 15px;text-align: left;font-size: 14px;">' + list[i].quantity +
                        '</td>\n' +
                        '                                <td style="margin-bottom: 5px;vertical-align: middle !important;width: 25px;text-align: left;font-size: 14px;">' + list[i].ypUnitName +
                        '</td>\n' +
                        '                            </tr>\n' +
                        '                            <tr>\n' +
                        '                                <td style="margin-bottom: 5px;width: 10px;font-size: 14px;" align="left" valign="top">' +
                        '</td>\n' +
                        '                                <td style="margin-bottom: 5px;vertical-align: middle !important;width: 260px;font-size: 14px;">\n' + manufactoryName +
                        '                                </td>\n' +
                        '                                <td colspan="4" style="padding-left:0px;margin-bottom: 5px;vertical-align: middle !important;text-align: left;font-size: 14px;">用法：' + list[i].drugQuan+"&nbsp;" + list[i].drugUnitName + '/次&nbsp;&nbsp;' + list[i].frequency + '&nbsp;&nbsp;' + printName +
                        '</td>\n' +
                        '                            </tr>'+
                        '                            <tr>\n' +
                        '                                <td style="margin-bottom: 5px;width: 10px;font-size: 14px;" align="left" valign="top">' +
                        '</td>\n' +
                        '                                <td colspan="5" style="margin-bottom: 5px;vertical-align: middle !important;width: 260px;font-size: 14px;">\n' + (list[i].instructionText==null?'':list[i].instructionText) +
                        '                                </td>\n' +
                        '                            </tr><tr><td>&nbsp;</td></tr>';
                }
                $('#tbody_yp').html(tr);
                $('#yxwk').remove();
                if (list.length < 5) {
                    $('#div_yp').append('<span id="yxwk" style="margin-bottom: 5px;font-size: 14px;">以下为空</span>');
                }
                LODOP = getLodop();
                LODOP.PRINT_INITA(6, 0, "140mm", "202mm", "泰和医院处方笺");
                LODOP.SET_PRINT_STYLE("FontSize", 9); //字体大小
                //设置默认打印机
                LODOP.SET_PRINTER_INDEX(printIndex);
                LODOP.SET_PRINT_PAGESIZE(1, '140mm', '202mm', "CreateCustomPage");
                LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "140mm");
                LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", "202mm");
                LODOP.SET_PRINT_MODE("CREATE_CUSTOM_PAGE_NAME", "门诊处方笺");//对新建的纸张重命名
                LODOP.ADD_PRINT_HTM("5mm", "7mm", "140mm", "202mm",  $("div[id='print_view']").html());
                LODOP.PRINT();
                LODOP.NewPage();//下一页
                //LODOP.PREVIEW();
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}

/**
 * 获取时间选择器的时间数组
 * @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'));
    $("#patientIdSearch").val(null);
    $("#nameSearch").val(null);
    $("#dispensingStatusSearch").val(0);
    $("#dispensingStatusSearch").selectpicker('refresh');
}

/**
 * 查询默认打印机
 */
function setPrint() {
    if (mzCfPrintIndex >= 0 && ekCfPrintIndex >= 0 && jzCfPrintIndex >= 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) {
                mzCfPrintIndex = res.data.mzCfPrintIndex;
                ekCfPrintIndex = res.data.ekCfPrintIndex;
                jzCfPrintIndex = res.data.jzCfPrintIndex;
            } else {
                mzCfPrintIndex = -1;
                ekCfPrintIndex = -1;
                jzCfPrintIndex = -1;
            }
        }
    });
}



