//@ sourceURL=request-holidays-config.js
var switchery;
$(function () {
    $(".selectpicker").selectpicker({
        dropuAuto: false
    });


    //告警阈值
    $.ajax({
        type: "GET",
        url: '/thmz/getConfigByKey?key=alarm_num',
        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;
            }
            $("#alarmNum").val(res.data.configValue);
        }
    });

    $('#send').click(function () {
        //修改告警设置
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=UTF-8",
            url: '/thmz/setConfig',
            dataType: "json",
            data: JSON.stringify({"configKey": "alarm_num","configValue": $("#alarmNum").val()}),
            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) {
                    //修改告警人员
                    var doctor=$("#doctor").val();
                    var doctorStr=null;
                    if(doctor!=null && doctor.length>0){
                        for (var i=0;i<doctor.length;i++){
                            if(doctorStr==null){
                                doctorStr=doctor[i];
                            }else {
                                doctorStr+=","+doctor[i];
                            }

                        }
                    }
                    $.ajax({
                        type: "POST",
                        contentType: "application/json;charset=UTF-8",
                        url: '/thmz/setConfig',
                        dataType: "json",
                        data: JSON.stringify({"configKey": "alarm_user","configValue": doctorStr}),
                        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);
                            }
                        }
                    });
                } else {
                    errorMesage(res);
                }
            }
        });
    });






    $("#beginDate").change(function (e) {
        var beginDate = $("#beginDate").val();
        if (beginDate.length == 8 && beginDate.indexOf("-") <= 0) {
            beginDate = beginDate.substring(0, 4) + "-" + beginDate.substring(4, 6) + "-" + beginDate.substring(6);
            $("#beginDate").val(beginDate);
        }
        var dateFormat = /^(\d{4})-(\d{2})-(\d{2})$/;
        if (!dateFormat.test(beginDate)) {
            new PNotify({
                title: '错误提示',
                text: '开始日期错误',
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
        var arr = beginDate.split("-");
        if (!checkDate(arr[0], arr[1], arr[2])) {
            new PNotify({
                title: '错误提示',
                text: '开始日期错误',
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
    });


    $("#endDate").change(function (e) {
        var endDate = $("#endDate").val();
        if (endDate.length == 8 && endDate.indexOf("-") <= 0) {
            endDate = endDate.substring(0, 4) + "-" + endDate.substring(4, 6) + "-" + endDate.substring(6);
            $("#endDate").val(endDate);
        }
        var dateFormat = /^(\d{4})-(\d{2})-(\d{2})$/;
        if (!dateFormat.test(endDate)) {
            new PNotify({
                title: '错误提示',
                text: '结束日期错误',
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
        var arr = endDate.split("-");
        if (!checkDate(arr[0], arr[1], arr[2])) {
            new PNotify({
                title: '错误提示',
                text: '结束日期错误',
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
    });



    initMzWorkTime();
    initList();
    $("#btn_add").click(function (t) {
        $("#editModal").modal();
        clearInput();
    });
    //周末是否免费设置
    $("#btn_weekend").click(function (t) {
        $("#weekendModal").modal();

        //查询已经设置好的结果，回显
        $.ajax({
            type: "GET",
            url: '/thmz/getConfigByKey?key=weekend_fee',
            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.data.configValue=='0'){
                    setSwitchery(false);
                }else {
                    setSwitchery(true);
                }
            }
        });



    });

    $("#saveEdit").click(function (t) {
        saveHolidays();
    });

    var elem = document.querySelector('.js-switch');
    //size 设置禁用可用按钮的大小、secondaryColor：设置右边的颜色为红色
    switchery = new Switchery(elem,{
        color: "#26B99A"
    });



    $('#saveWeekend').click(function () {
        var weekendFee=$("input:checkbox:checked").val();
        if(weekendFee=='on'){
            weekendFee='1';
        }else {
            weekendFee='0';
        }
        //修改周末是否免费设置
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=UTF-8",
            url: '/thmz/setConfig',
            dataType: "json",
            data: JSON.stringify({"configKey": "weekend_fee","configValue": weekendFee}),
            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) {
                    $("#weekendModal").modal('hide');
                    successMesage(res);
                } else {
                    errorMesage(res);
                }
            }
        });
    });

});


/**
 * 切换Switchery开关函数  switchElement Switchery对象,checkedBool 选中的状态
 */
function setSwitchery(checkedBool) {
    if((checkedBool && !switchery.isChecked()) || (!checkedBool && switchery.isChecked())) {
        switchery.setPosition(true);
        switchery.handleOnchange(true);
    }
}


/**
 * 保存
 */
function saveHolidays() {
    $.ajax({
        type: "POST",
        url: '/thmz/saveHolidays',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify({"beginDate":$("#beginDate").val(),"beginAmpm":$("#beginAmpm").val(),"endDate":$("#endDate").val(),"endAmpm":$("#endAmpm").val()}),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                $("#editModal").modal("hide");
                clearInput();
                $('#tb_table').bootstrapTable('refresh');
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}




/**
 * 清空输入框
 */
function clearInput() {
    $("#beginDate").val(null);
    $('#beginAmpm').selectpicker('val', null);
    $('#beginAmpm').selectpicker('refresh');
    $("#endDate").val(null);
    $('#endAmpm').selectpicker('val', null);
    $('#endAmpm').selectpicker('refresh');
}

/**
 * 查询节假日信息
 */
function initList() {
    $('#tb_table').bootstrapTable("destroy");
    $('#tb_table').bootstrapTable({
        url: '/thmz/getHolidays',         //请求后台的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: 15,                       //每页的记录行数（*）
        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='<button type="button" class="btn btn-danger  btn-sm" onclick="removeRequest(' + row.id + ')">删除</button>';
                    return [str].join('');
                }
            },
            {
                field: 'beginDate',
                title: '开始日期',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return format(value, "yyyy-MM-dd");
                }

            },
            {
                field: 'beginAmpm',
                title: '开始时间段',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if(value=='a'){
                        return '<span>上午</span>';
                    }
                    if(value=='p'){
                        return '<span>下午</span>';
                    }
                    if(value=='d'){
                        return '<span>全天</span>';
                    }
                }
            }, {
                field: 'endDate',
                title: '结束日期',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return format(value, "yyyy-MM-dd");
                }
            }, {
                field: 'endAmpm',
                title: '结束时间段',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if(value=='a'){
                        return '<span>上午</span>';
                    }
                    if(value=='p'){
                        return '<span>下午</span>';
                    }
                    if(value=='d'){
                        return '<span>全天</span>';
                    }
                }
            }
        ],
        onLoadSuccess: function () {

        },
        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.count,//总页数
                "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 temp = {
        pageSize: params.limit,
        offset:params.offset,
    };
    return temp;
};


/**
 * 初始门诊时间区间下拉选
 */
function initMzWorkTime() {
    $.ajax({
        type: "GET",
        url: '/thmz/getMzWorkTime',
        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 = '';
            var ampm = null;
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#beginAmpm').empty();   //清空resText里面的所有内容
            $('#beginAmpm').html(html);
            $('#beginAmpm').selectpicker('refresh');
            $('#endAmpm').empty();   //清空resText里面的所有内容
            $('#endAmpm').html(html);
            $('#endAmpm').selectpicker('refresh');
        }
    });
}






/**
 * 删除信息
 * @param id
 */
function removeRequest(id) {
    if (!confirm("确认要删除当前操作的节假日信息吗？")) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/removeHolidaysById?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) {
                $('#tb_table').bootstrapTable('refresh');
                successMesage(res);
            }else {
                errorMesage(res);
            }
        }
    });
}





