//@ sourceURL=charge_list.js
var LODOP; //声明为全局变量
//默认打印机下标
var printIndex = -1;
var canPrint = false;
$(function () {
    init_daterangepicker();
    initChargeListByPatient();
    //  initFeeTable();
    //重置查询参数
    $('#btn_clean').click(function () {
        cleanParams();
    });
    //初始化页面上面的按钮事件
    $("#btn_daily").click(function (t) {
        print();
    });

    $("#btn_query").click(function (t) {
        initChargeListByPatient();
    });

    setTimeout(function () {
        getLodop();
    }, 400);

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


/**
 * 查询病人缴费记录
 */
function initChargeListByPatient() {
    $('#tb_table').bootstrapTable("destroy");
    $('#tb_table').bootstrapTable({
        url: '/thmz/getChargeListByPatient',         //请求后台的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: [
            {
                field: 'patient_id',
                title: '病人ID',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    var text = value;
                    if (row.serial_no < 0) {
                        text = '<span style="color:#ff6b91">' + value + '</span>';
                    }
                    return text;
                }
            }, {
                field: 'cheque_type',
                title: '收费方式',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    var text = value;
                    if (row.serial_no < 0) {
                        text = '<span style="color:#ff6b91">' + value + '</span>';
                    }
                    return text;
                }
            }, {
                field: 'name',
                title: '姓名',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if(value==null || value==undefined){
                        value="";
                    }
                    var text = value;
                    if (row.serial_no < 0) {
                        text = '<span style="color:#ff6b91">' + value + '</span>';
                    }
                    return text;
                }
            }, {
                field: 'times',
                title: '次数',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    var text = value;
                    if (row.serial_no < 0) {
                        text = '<span style="color:#ff6b91">' + value + '</span>';
                    }
                    return text;
                }
            }, {
                field: 'charge_date',
                title: '就诊日期',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    var text = value;
                    if (row.serial_no < 0) {
                        text = '<span style="color:#ff6b91">' + value + '</span>';
                    }
                    return text;
                }
            }, {
                field: 'serial_no',
                title: '机制流水号',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    var text = value;
                    if (value < 0) {
                        text = '<span style="color:#ff6b91">' + value + '</span>';
                    }
                    return text;
                }
            }
        ],
        onClickRow: function (row) {
            fitfymx(row.patient_id, row.real_no);
        },
        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.mzChargeDetailList.length,//总页数
                "rows": ress.mzChargeDetailList   //数据
            };
        },
    });
    fitAllfymx();

}


/**
 * 构建列表查询参数
 * @param params
 * @returns {{mzChargeDetail: {patientId: string | number | string[] | undefined | jQuery, warnDept: string | number | string[] | undefined | jQuery, doctorCode: string | number | string[] | undefined | jQuery, name: string | number | string[] | undefined | jQuery, payMark: number}, beginTime: Date, endTime: Date, pageSize: *, pageIndex: number}}
 */
function queryParams(params) {
    var rePortRangeArr = getRePortRangeArr();
    var temp = {
        beginDate: rePortRangeArr[0],
        endDate: rePortRangeArr[1],
        hisData: $('#hisData').is(':checked') ? 0 : 1,
        name: $("#name").val(),
        patientId: $("#patientId").val(),
        serialNo: $("#serialNo").val()
    };
    return temp;
};


/**
 * 设置病人id
 */
function setPatientId() {
    var patientId_or_cardNo = $("#patientId_or_cardNo").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);
                }
            }
        }
    });
}


/**
 * 获取时间选择器的时间数组
 * @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 setPrint() {
    if (printIndex >= 0) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/getLastWindowsByCurrentUser',
        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) {
                printIndex = res.data.cgPrintIndex;
            } else {
                printIndex = -1;
            }
        }
    });
}


/**
 * 清空查询条件
 */
function cleanParams() {
    $('#reportrange span').html(moment().format('YYYY-MM-DD') + ' - ' + moment().format('YYYY-MM-DD'));
    $("#hisData").removeAttr("checked");
    $("#name").val(null),
        $("#patientId").val(null),
        $("#serialNo").val(null),
        $("#patientId_or_cardNo").val(null)
}

/**
 * 打印报表
 */
function print() {
    if (!canPrint) {
        new PNotify({
            title: '警告提示',
            text: '没有选择合适的报表，无需打印',
            hide: false,
            styling: 'bootstrap3'
        });
        return;
    }
    setPrint();
    LODOP = getLodop();
    LODOP.PRINT_INITA(6, 0, "210mm", "297mm", "门诊病人费用清单");
    //设置默认打印机
    LODOP.SET_PRINTER_INDEX(printIndex);
    LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "297mm");
    LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", "210mm");
    LODOP.ADD_PRINT_TABLE(150, "5%", "90%", 800, document.getElementById("fymx_table").innerHTML);
    LODOP.SET_PRINT_STYLEA(0, "Vorient", 3);
    LODOP.ADD_PRINT_HTM(26, "5%", "90%", 109, document.getElementById("right_title").innerHTML);
    LODOP.SET_PRINT_STYLEA(0, "ItemType", 1);
    LODOP.SET_PRINT_STYLEA(0, "LinkedItem", 1);
    LODOP.ADD_PRINT_HTM(950,"5%","90%",54,document.getElementById("foot").innerHTML);
    LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
    LODOP.SET_PRINT_STYLEA(0,"LinkedItem",1);
    LODOP.PRINT();
    //LODOP.PREVIEW();
}



/**
 * 查询同一病人所有收费明细
 */
function fitAllfymx() {
    var patientId=$("#patientId").val();
    if(patientId ==undefined || patientId==null || patientId==""){
        return;
    }
    var rePortRangeArr = getRePortRangeArr();
    $.ajax({
        type: "POST",
        url: '/thmz/getAllChargeDetailByPatient',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify({
            patientId: $("#patientId").val(),
            beginDate: rePortRangeArr[0],
            endDate: rePortRangeArr[1],
            hisData: $('#hisData').is(':checked') ? 0 : 1
        }),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                formatMx(res);
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
            $("#print_date").html(format(new Date(), "yyyy/MM/dd"));
        }
    });
}

/**
 * 设置病人收费明细
 */
function fitfymx(patientId, serialNo) {
    $.ajax({
        type: "POST",
        url: '/thmz/getChargeDetailByPatient',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify({
            patientId: patientId,
            serialNo: serialNo,
            hisData: $('#hisData').is(':checked') ? 0 : 1
        }),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                formatMx(res);
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
            $("#print_date").html(format(new Date(), "yyyy/MM/dd"));
        }
    });
}




function formatMx(res) {
    $("#receiptBillList").empty();
    $("#receiptBillList").append('<div style="font-weight: 700;margin-left: 8px;padding-top: 4px;padding-bottom: 4px;"><span style="margin-left: 32px;font-size: 13px;">发票:</span><span id="receipt_no" style="margin-left: 50px;"></span></div>');
    if (res.data != null && res.data.length > 0) {
        $("#serialNo_t").html("机制号：" + res.data[0].real_no);
        $("#doctor").html("医生：" + res.data[0].doctor_code);
        if(res.mzReceiptSerial!=undefined && res.mzReceiptSerial!=null){
            $("#cashId").html("收费员：" + res.mzReceiptSerial.operatorId);
        }else {
            $("#cashId").html("收费员：" + res.data[0].op_id);
        }
        $("#patientId_t").html("门诊号：" + res.data[0].patient_id);
        $("#name_t").html("姓名：" + res.data[0].name);
        $("#date_t").html("日期：" + format(res.data[0].charge_date, "yyyy-MM-dd"));
        $("#dept_t").html("科室：" + res.data[0].warn_dept);
        var html = "";
        for (var i = 0; i < res.data.length; i++) {
            var temp = res.data[i];
            html += "<tr>";
            html += ' <td width="17%" style="padding-left: 8px;padding-top: 4px;">' + temp.tybm + '</td>';
            html += ' <td width="45%" style="padding-left: 8px;padding-top: 4px;">' + temp.drugname + '</td>';
            if (temp.specification == null || temp.specification == undefined) {
                html += ' <td width="10%" style="padding-left: 8px;padding-top: 4px;"></td>';
            } else {
                html += ' <td width="10%" style="padding-left: 8px;padding-top: 4px;">' + temp.specification + '</td>';
            }
            if (temp.unit == null || temp.unit == undefined) {
                html += ' <td width="10%" style="padding-left: 8px;padding-top: 4px;"></td>';
            } else {
                html += ' <td width="10%" style="padding-left: 8px;padding-top: 4px;">' + temp.unit + '</td>';
            }
            html += ' <td width="6%" style="padding-left: 8px;padding-top: 4px;">' + temp.unit_price.toFixed(2) + '</td>';
            html += ' <td width="6%" style="padding-left: 8px;padding-top: 4px;">' + temp.quantity + '</td>';
            html += ' <td width="6%" style="padding-left: 8px;padding-top: 4px;">' + temp.total_price.toFixed(2) + '</td>';
            html += "</tr>";
        }
        html+='<tr><td colspan="8"><div style="border:0;border-top:1px solid #000;overflow:hidden;font-size: 13px;"><div style="float: right;font-weight: 700;padding-top: 4px;padding-bottom: 4px;"><span>金额合计:</span><span id="total_count" style="margin-left: 50px;"></span></div></div></td></tr>';
        $("#fymx_table_body").html(html);
        if (res.mzReceiptSerial!= undefined && res.mzReceiptSerial != null) {
            $("#receipt_no").html(res.mzReceiptSerial.receiptBill);
        }else {
            $("#receipt_no").html("");
        }
        if (res.receiptBillList!=null && res.receiptBillList.length>0){
            for (var i=0;i<res.receiptBillList.length;i++){
                if(i==0){
                    $("#receipt_no").html(res.receiptBillList[0]);
                }else if (i>0){
                    $("#receiptBillList").append('<div style="font-weight: 700;margin-left: 8px;padding-top: 4px;padding-bottom: 4px;"><span style="margin-left: 32px;font-size: 13px;color: white;">发票:</span><span style="margin-left: 50px;">'+res.receiptBillList[i]+'</span></div>');
                }
            }
        }
        $("#opId_print").html(res.user.userName);
        $("#total_count").html(res.totalPriceCount.toFixed(2));
        canPrint = true;
    }
}