//@ sourceURL=mzsrmx.js
var amount;
var total;
$(function () {
    init_daterangepicker();
    //daterangepicker(getAllOperator);
      initMzsrmxTable();
    //重置查询参数
    $('#btn_clean').click(function () {
        cleanParams();
    });
    //初始化页面上面的按钮事件
    $("#btn_query").click(function (t) {
        initMzsrmxTable();
    });

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

    //初始化页面上面的按钮事件
    $("#btn_excel").click(function (t) {
        exportExcel();
    });
    initSelect();
});



/**
 * 初始化下拉选
 */
function initSelect() {
    $(".selectpicker").selectpicker({
        dropuAuto: false
    });
    initDeptSelect();
    initDoctorSelect();
    initHsmNameSelect();
    initBillItemSelect();
    var type = '<option value="0">结算</option><option value="1">收费</option>';
    $('#timeParam').html(type);
    $('#timeParam').selectpicker('refresh');
    $("#timeParam").selectpicker('val', 0);//默认选中
    $("#timeParam").selectpicker('refresh');
}




/**
 * 父类码下拉选
 */
function initBillItemSelect() {
    //科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/getAllParentCodes',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (data) {
            if (data == '401' || data == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(data.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#parentCode').html(html);
            $('#parentCode').selectpicker('refresh');
        }
    });
}

/**
 * 核算码下拉选
 */
function initHsmNameSelect() {
    //科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/getAllHsmName',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (data) {
            if (data == '401' || data == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(data.data, function (commentIndex, comment) {
                html += '<option value="' + comment + '">' + comment + '</option>';
            });
            $('#hsm').html(html);
            $('#hsm').selectpicker('refresh');
        }
    });
}

/**
 * 挂号列表中的科室列表
 */
function initDeptSelect() {
    //科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/allMzUnitCode',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (data) {
            if (data == '401' || data == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(data.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '(' + comment.pyCode + ')</option>';
            });
            $('#jzSqDept').empty();
            $('#jzSqDept').html(html);
            $('#jzSqDept').selectpicker('refresh');
            $('#execDept').empty();
            $('#execDept').html(html);
            $('#execDept').selectpicker('refresh');
        }
    });
}


/**
 * 挂号列表中的医生列表初始化
 */
function initDoctorSelect() {
    //医生列表
    $.ajax({
        type: "GET",
        url: '/thmz/listEmployeeByDepts?depts=' + $('#jzSqDept').val(),
        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;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.employeeCode + '">' + comment.employeeName + '</option>';
            });
            $('#jzSqDoctor').empty();
            $('#jzSqDoctor').html(html);
            $('#jzSqDoctor').selectpicker('destroy').selectpicker('refresh');
        }
    });
}


/**
 * 门诊收入明细
 */
function initMzsrmxTable() {
    amount=null;
    total=-1;
    $('#tb_table').bootstrapTable("destroy");
    $('#tb_table').bootstrapTable({
        url: '/thmz/getThmzmxsr',         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        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,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        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: 'xm',
                title: '姓名',
                align: "center",
                valign: 'middle'
            }, {
                field: 'patientId',
                title: '病人ID',
                align: "center",
                valign: 'middle',
            }, {
                field: 'chargeDate',
                title: '缴费时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return format(value, "yyyy-MM-dd HH:mm:ss");
                }
            }, {
                field: 'jzSqDept',
                title: '就诊/申请科室',
                align: "center",
                valign: 'middle',
            }, {
                field: 'jzSqDoctor',
                title: '就诊/申请医生',
                align: "center",
                valign: 'middle',
            }, {
                field: 'execEept',
                title: '执行科室',
                align: "center",
                valign: 'middle'
            }, {
                field: 'xmm',
                title: '收费项目',
                align: "center",
                valign: 'middle'
            }, {
                field: 'hsm',
                title: '核算码',
                align: "center",
                valign: 'middle',
            }, {
                field: 'parentCode',
                title: '父类码',
                align: "center",
                valign: 'middle'
            }, {
                field: 'quty',
                title: '数量',
                align: "center",
                valign: 'middle'
            }, {
                field: 'price',
                title: '单价',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            }, {
                field: 'je',
                title: '金额',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            }
        ],
        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": {}   //数据
                };
            }
            $("#totalAmount").text(ress.totalAmount.toFixed(2));
            amount=ress.totalAmount.toFixed(2);
            total=ress.total;
            return {
                "total": ress.total,//总页数
                "rows": ress.data   //数据
            };
        },
    });
}

/**
 * 构建列表查询参数
 * @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],
        commonParams: $('#commonParams').val(),
        caseType: $('#timeParam').val(),
        jzSqDept:$("#jzSqDept").val(),
        jzSqDoctor:$("#jzSqDoctor").val(),
        execDept:$("#execDept").val(),
        hsm:$("#hsm").val(),
        parentCode:$("#parentCode").val(),
        xmm:$("#xmm").val(),
        pageSize: params.limit,
        offset:params.offset,
        amount:amount,
        total:total
    };
    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'));
    $("#commonParams").val(null);
    $("#timeParam").selectpicker('val', 0);//默认选中
    $("#timeParam").selectpicker('refresh');
    $("#jzSqDept").selectpicker('val', null);//默认选中
    $("#jzSqDept").selectpicker('refresh');
    $("#jzSqDoctor").selectpicker('val', null);//默认选中
    $("#jzSqDoctor").selectpicker('refresh');
    $("#execDept").selectpicker('val', null);//默认选中
    $("#execDept").selectpicker('refresh');
    $("#parentCode").selectpicker('val', null);//默认选中
    $("#parentCode").selectpicker('refresh');
    $("#hsm").selectpicker('val', null);//默认选中
    $("#hsm").selectpicker('refresh');
    $("#xmm").val(null);
}

/**
 * 导出excel
 */
function exportExcel() {
    var rePortRangeArr = getRePortRangeArr();
    window.location.href = "/thmz/excelThmzmxsr?beginDate=" + rePortRangeArr[0] + "&endDate=" + rePortRangeArr[1]+"&commonParams="+$('#commonParams').val()
        +"&caseType="+$('#timeParam').val()+"&jzSqDept="+$("#jzSqDept").val()+"&jzSqDoctor="+$("#jzSqDoctor").val()+"&execDept="+$("#execDept").val()+"&hsm="
        +$("#hsm").val()+"&parentCode="+$("#parentCode").val()+"&xmm="+$("#xmm").val()+"&pageSize="+total;
}