//@ sourceURL=discount.js
//项目map
var chargeItemMap = null;
//科室map
var deptNoMap = null;
$(function () {
    initSelect();
    daterangepicker(initDiscountList);
    $('#reportrange span').html(moment(new Date('1970')).startOf('year').format('YYYY-MM-DD') + ' - ' + moment(new Date('1970')).startOf('year').format("YYYY-MM-DD"));
    $('#discountBeginTime').datetimepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd hh:ii:ss'
    });
    $('#discountEndTime').datetimepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd hh:ii:ss'
    });
    //重置查询参数
    $('#btn_clean').click(function () {
        $("#delFlag").selectpicker('val', null);//默认选中
        $("#delFlag").selectpicker('refresh');
        $("#deptType").selectpicker('val', null);//默认选中
        $("#deptType").selectpicker('refresh');
        $("#deptNo").selectpicker('val', null);//默认选中
        $("#deptNo").selectpicker('refresh');
        $("#chargeItem").selectpicker('val', null);//默认选中
        $("#chargeItem").selectpicker('refresh');
        $('#reportrange span').html(moment(new Date('1970')).startOf('year').format('YYYY-MM-DD') + ' - ' + moment(new Date('1970')).startOf('year').format("YYYY-MM-DD"));
        initDiscountList();
    });


    $('#btn_add').click(function () {
        $("#myModalLabel").text("新增惠民活动");
        $("div.bs-example-modal-lg").modal();
    });
    setTimeout(function () {
        initDiscountList();
    }, 1200);

});

/**
 * 惠民活动列表
 */
function initDiscountList() {
    $('#tb_table').bootstrapTable("destroy");
    $('#tb_table').bootstrapTable({
        url: '/thmz/listDiscount',         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "desc",                   //排序方式
        queryParams: queryParams,           //传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 5,                       //每页的记录行数（*）
        pageList: [10, 15, 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 = "";
                    if (row.deleteFlag == 0) {
                        str += '<button type="button" class="btn btn-warning  btn-sm" onclick="updateDiscountDelFlag(\'' + row.id + '\',\'' + row.name + '\',1)">停用</button>';
                    } else if (row.deleteFlag == 1) {
                        str += '<button type="button" class="btn btn-success  btn-sm" onclick="updateDiscountDelFlag(\'' + row.id + '\',\'' + row.name + '\',0)">启用</button>';
                    }
                    str += '<button type="button" class="btn btn-primary  btn-sm" onclick="updateDiscount(\'' + row.id + '\')">编辑</button>';
                    str += '<button type="button" class="btn btn-danger  btn-sm" onclick="deleteDiscountDelFlag(\'' + row.id + '\',\'' + row.name + '\')">删除</button>';
                    return [str].join('');
                }
            },
            {
                field: 'name',
                title: '惠民活动名称',
                align: "center",
                valign: 'middle'
            },
            {
                field: 'deptType',
                title: '科室类别',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == 0) {
                        return "申请科室";
                    }
                    return "执行科室";
                }
            }, {
                field: 'deptNo',
                title: '科室编码',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (deptNoMap != null) {
                        return deptNoMap.get(value);
                    }
                }
            }, {
                field: 'discountBeginTime',
                title: '惠民活动开始时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == null || value == "") {
                        return "";
                    }
                    return format(value, "yyyy-MM-dd HH:mm:ss");
                }
            }, {
                field: 'discountEndTime',
                title: '惠民活动结束时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == null || value == "") {
                        return "";
                    }
                    return format(value, "yyyy-MM-dd HH:mm:ss");
                }
            }, {
                field: 'chargeItemCodes',
                title: '惠民活动收费项目',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (chargeItemMap != null) {
                        if (value != null && value != "") {
                            var arr = value.split(",");
                            var name = null;
                            for (var i = 0; i < arr.length; i++) {
                                if (name == null) {
                                    name = chargeItemMap.get(arr[i]);
                                } else {
                                    name += "," + chargeItemMap.get(arr[i]);
                                }
                            }
                            return name;
                        }
                    }
                }
            }, {
                field: 'discountType',
                title: '优惠类型',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == 0) {
                        return "单价优惠";
                    }
                    return "折扣率";
                }
            }, {
                field: 'discountRate',
                title: '折扣率',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (row.discountType == 0) {
                        return "-";
                    }
                    return value;
                }
            }, {
                field: 'discountPrice',
                title: '优惠价',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (row.discountType == 0) {
                        if (value != null && value != undefined && value != "") {
                            return value.toFixed(2);
                        }
                    }
                    return "-";
                }

            }, {
                field: 'deleteFlag',
                title: '启用状态',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == 0) {
                        return "启用";
                    }
                    return "停用";
                }
            }
        ],
        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   //数据
            };
        },
    });
}


/**
 * 构建列表查询参数
 * @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 = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        deleteFlag: $("#delFlag").val(),
        deptType: $("#deptType").val(),
        deptNo: $("#deptNo").val(),
        chargeItemCodes: $("#chargeItem").val(),
        beginTime: rePortRangeArr[0] == "1970-01-01 00:00:00" ? null : rePortRangeArr[0],
        endTime: rePortRangeArr[1] == "1970-01-01 23:59:59" ? null : rePortRangeArr[1],
        pageSize: params.limit,   //页面大小
        pageIndex: params.offset / params.limit,  //页码
    };
    return temp;
}


/**
 * 初始化下拉选
 */
function initSelect() {
//启动Bootsrap-Select
    $(".selectpicker").selectpicker({
        dropuAuto: false
    });
    var yesNo = '<option value="1">停用</option><option value="0">启用</option>';
    $('#delFlag').html(yesNo);
    $('#delFlag').selectpicker('refresh');

    $('#deleteFlagParams').html(yesNo);
    $('#deleteFlagParams').selectpicker('refresh');
    $('#deleteFlagParams').selectpicker('val', 0);
    $('#deleteFlagParams').selectpicker('refresh');


    var deptType = '<option value="1">执行科室</option><option value="0">申请科室</option>';
    $('#deptType').html(deptType);
    $('#deptType').selectpicker('refresh');
    $('#deptTypeParams').html(deptType);
    $('#deptTypeParams').selectpicker('refresh');
    $('#deptTypeParams').selectpicker('val', 0);
    $('#deptTypeParams').selectpicker('refresh');

    var discountType = '<option value="1">折扣率</option><option value="0">单价优惠</option>';
    $('#discountTypeParams').html(discountType);
    $('#discountTypeParams').selectpicker('refresh');

    initDeptSelect();
    initZdChargeSelect();
}


/**
 * 停用或者启用惠民活动
 * @param code
 */
function updateDiscountDelFlag(id, name, delFlag) {
    if (delFlag == 1 && !confirm("确认要停用惠民活动【" + name + "】信息吗？")) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/updateDiscountDelFlag?id=' + id + "&delFlag=" + delFlag,
        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);
                $('#tb_table').bootstrapTable("refresh");
            } else {
                errorMesage(res);
            }
        }
    });
}

/**
 * 优惠类型变化事件
 */
function discountTypeChange() {
    var discountTypeParams = $("#discountTypeParams").val();
    if (discountTypeParams == 0) {
        $("#discountRateDiv").addClass("hide");
        $("#discountPriceDiv").removeClass("hide");
    } else {
        $("#discountPriceDiv").addClass("hide");
        $("#discountRateDiv").removeClass("hide");
    }
}

/**
 * 删除惠民活动
 * @param code
 */
function deleteDiscountDelFlag(id, name) {
    if (!confirm("确认要删除惠民活动【" + name + "】信息吗？")) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/removeById?id=' + id,
        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);
                $('#tb_table').bootstrapTable("refresh");
            } else {
                errorMesage(res);
            }
        }
    });
}

/**
 * 修改惠民活动
 * @param code
 */
function updateDiscount(id) {
    $.ajax({
        type: "GET",
        url: '/thmz/getDiscountById?id=' + id,
        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) {
                $("#nameParams").val(res.data.name);
                $("#discountRate").val(res.data.discountRate);
                $("#id").val(res.data.id);
                $('#deptTypeParams').selectpicker('val', res.data.deptType);
                $('#deptTypeParams').selectpicker('refresh');
                $('#deptNoParmas').selectpicker('val', res.data.deptNo);
                $('#deptNoParmas').selectpicker('refresh');
                $("#discountBeginTime").find("input").val(res.data.discountBeginTime);
                $("#discountEndTime").find("input").val(res.data.discountEndTime);
                if (res.data.chargeItemCodes != null && res.data.chargeItemCodes != '') {
                    var arr = res.data.chargeItemCodes.split(",");
                    $("#chargeItemCodesParams").selectpicker('val', arr);
                    $("#chargeItemCodesParams").selectpicker('refresh');
                }
                $('#deleteFlagParams').selectpicker('val', res.data.deleteFlag);
                $('#deleteFlagParams').selectpicker('refresh');
                $('#discountTypeParams').selectpicker('val', res.data.discountType);
                $('#discountTypeParams').selectpicker('refresh');
                $("#discountPrice").val(res.data.discountPrice);
                if (res.data.discountType == 0) {
                    $("#discountRateDiv").addClass("hide");
                    $("#discountPriceDiv").removeClass("hide");
                } else {
                    $("#discountPriceDiv").addClass("hide");
                    $("#discountRateDiv").removeClass("hide");
                }
                $("div.bs-example-modal-lg").modal();
            } else {
                errorMesage(res);
            }
        }
    });
}


/**
 * 挂号列表中的科室列表
 */
function initDeptSelect() {
    //科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/allUnitCode',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        //async: false,
        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>';
                if (deptNoMap == null) {
                    deptNoMap = new Map()
                }
                deptNoMap.put(comment.code, comment.name);
            });
            $('#deptNo').empty();
            $('#deptNo').html(html);
            $('#deptNo').selectpicker('refresh');

            $('#deptNoParmas').html(html);
            $('#deptNoParmas').selectpicker('refresh');
        }
    });
}


/**
 * 使用中的收费项目列表
 */
function initZdChargeSelect() {
    //科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/getAllInUsedZdCharge',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        // async: false,
        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.code + ')</option>';
                if (chargeItemMap == null) {
                    chargeItemMap = new Map()
                }
                chargeItemMap.put(comment.code, comment.name);
            });
            $('#chargeItem').empty();
            $('#chargeItem').html(html);
            $('#chargeItem').selectpicker('refresh');

            $('#chargeItemCodesParams').html(html);
            $('#chargeItemCodesParams').selectpicker('refresh');

        }
    });
}


//保存惠民活动
$('#save').click(function () {
    var chargeItemCodesStr = null;
    var chargeItemCodesParams = $("#chargeItemCodesParams").val();
    if (chargeItemCodesParams != null && chargeItemCodesParams.length > 0) {
        for (var i = 0; i < chargeItemCodesParams.length; i++) {
            if (chargeItemCodesStr == null) {
                chargeItemCodesStr = chargeItemCodesParams[i];
            } else {
                chargeItemCodesStr += "," + chargeItemCodesParams[i];
            }

        }
    }
    $.ajax({
        type: "POST",
        url: '/thmz/saveDiscount',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify({
            "id": $("#id").val(),
            "name": $("#nameParams").val(),
            "deptType": $("#deptTypeParams").val(),
            "deptNo": $("#deptNoParmas").val(),
            "discountBeginTime": $("#discountBeginTime").find("input").val(),
            "discountEndTime": $("#discountEndTime").find("input").val(),
            "chargeItemCodes": chargeItemCodesStr,
            "discountType": $("#discountTypeParams").val(),
            "discountPrice": $("#discountPrice").val(),
            "discountRate": $("#discountRate").val(),
            "deleteFlag": $("#deleteFlagParams").val()
        }),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                $("div.bs-example-modal-lg").modal("hide");
                clearInput();
                successMesage(res);
                $('#tb_table').bootstrapTable("refresh");
            } else {
                errorMesage(res);
            }
        }
    });
});


/**
 * 清空输入框
 */
function clearInput() {
    $("#deptTypeParams").selectpicker('val', 0);//默认选中
    $("#deptTypeParams").selectpicker('refresh');
    $("#deptNoParmas").selectpicker('val', null);//默认选中
    $("#deptNoParmas").selectpicker('refresh');
    $("#discountBeginTime").find("input").val(null);
    $("#discountEndTime").find("input").val(null);
    $("#chargeItemCodesParams").selectpicker('val', null);//默认选中
    $("#chargeItemCodesParams").selectpicker('refresh');
    $("#deleteFlagParams").selectpicker('val', 0);//默认选中
    $("#deleteFlagParams").selectpicker('refresh');
    $("#id").val(null);
    $("#discountRate").val(null);
    $("#nameParams").val(null);

    $("#discountTypeParams").selectpicker('val', 0);//默认选中
    $("#discountTypeParams").selectpicker('refresh');
    $("#discountPrice").val(null);
    $("#discountRateDiv").addClass("hide");
    $("#discountPriceDiv").removeClass("hide");
}