var table;
var laydate;
var form;
var residueNum =-1;
var keyNum=0;
var valueNum =0;
layui.use(['table', 'layer', 'laydate', 'jquery', 'form'], function () {
    table = layui.table;
    laydate = layui.laydate;
    form = layui.form;
    laydate.render({
        elem: '#reservationTime' //指定元素  元素选择器
        , type: 'date'  //选择时间类型 可选值:year(年) month(年月)  date(年月日)  time(时分秒)  datetime(年月日时分秒)
        , trigger: 'click'
        , format: 'yyyy-MM-dd'  //时间格式  常用时间格式:yyyy-MM-dd HH:mm:ss
        , btns: ['clear', 'now', 'confirm'] //选择框右下角显示的按钮 清除-现在-确定
        , done: function (value, date) {//时间回调
            console.log(value);
            console.log(date);
            let hospitalValue = $("#hospital").val();
            if(hospitalValue == "0"){
                $("#reservationTime").val("");
                layer.msg("请先选择医院，再选择时间");
            }else{
                let tf =  getRetirementNum();
                if(tf == "0" || residueNum<0){
                    $("#reservationTime").val("");
                    layer.msg("今日当前医院体检名额所剩不足，所选人数超出"+Math.abs(residueNum)+"个，请选择其他时间体检！");
                }
            }
        }
    });
    // laydate.render({
    //     elem: "#reservationTime",
    //     min: minDate(),
    //     max: maxDate(),
    //     ready: function (value) {
    //         disabled_date(value);
    //     },
    //     change: function (value, date) {
    //         disabled_date(date);
    //     },
    // });
    getHospitalSelect();
    $('input[name=checkType][value="1"]').prop('checked',true);
    form.render()
    form.on('radio(checkType)', function (data) {
        var values = data.value;
        getTcManSelect(values);
        getTcWomanSelect(values);
    });
    getTcManSelect("1");
    getTcWomanSelect("1");

    form.on('submit(formDemo)', function (data) {
        if(residueNum<0){
            layer.msg("今日当前医院体检名额所剩不足，只有"+residueNum+"个，请选择其他时间体检！");
            return false;
        }
        var hospitalId = $("#hospital").val();
        var keyWord = $("#reservationTime").val();
        $.ajax({
            type: 'post',
            url: ctxPath + '/retirement/getRetirementNum',
            dataType: 'json', // 服务器返回数据类型
            async: false,
            data: {
                hospitalId:hospitalId,
                keyWord:keyWord
            },
            success: function (data) {
                var data = data.data;
                var thiskeyNum = data.key;
                var thisvalueNum = data.value;
                var nums = thiskeyNum-thisvalueNum -$("#manNum").val()-$("#womenNum").val();
                if(nums>=0){
                    addReservationData()
                }else{
                    layer.msg("后台数据变动，今日当前医院体检名额已经所剩不足，只有"+residueNum+"个，请选择其他时间体检！");
                }

            },
            error: function (err) {
                console.log("获取工程下拉列表出错：", err);
            }
        });

        return false;
    });
});

function getRetirementNum() {
    var hospitalId = $("#hospital").val();
    var keyWord = $("#reservationTime").val();
    if(hospitalId == 0){
        layer.msg("请选择体检医院！");
        return "0";
    }
    if(keyWord == ""){
        layer.msg("请选择体检是时间！");
        return "0";
    }
    $.ajax({
        type: 'post',
        url: ctxPath + '/retirement/getRetirementNum',
        dataType: 'json', // 服务器返回数据类型
        async: false,
        data: {
            hospitalId:hospitalId,
            keyWord:keyWord
        },
        success: function (data) {
            var data = data.data;
            residueNum = data.key - data.value;
            keyNum = data.key;
            valueNum = data.value;
            residueNum = residueNum - $("#manNum").val()-$("#womenNum").val()
            console.log(JSON.stringify(data)+" ,residueNum="+residueNum)
            return "1";
        },
        error: function (err) {
            console.log("获取工程下拉列表出错：", err);
        }
    });
    return "1";
}

/**
 * 批量添加人员预约
 */
function addReservationData() {
    //医院select选择
    var hospitalVal = $("#hospital").val();

    //男套餐select选择
    var tcMan = $("#tcMan").val();
    //女套餐select选择
    var tcWoman = $("#tcWoman").val();

    //父页面传人员id字符串
    var personId = $("#personId").val();
    //男人数
    var manNum = $("#manNum").val();
    //女人数
    var womenNum = $("#womenNum").val();

    if(manNum >0 && tcMan==0){
        layer.msg("请选择男性套餐！");
        return false;
    }
    if(womenNum >0 && tcWoman==0){
        layer.msg("请选择女性套餐");
        return false;
    }
    if(hospitalVal == 0){
        layer.msg("请选择体检医院");
        return false;
    }
    console.log("hospitalVal="+hospitalVal+" ,tcMan="+tcMan+" ,tcWoman="+tcWoman);
    console.log("personId="+personId+" ,manNum="+manNum+" ,womenNum="+womenNum);
    console.log("tcManName="+$("#tcMan").text().replace("请选择套餐","")+" ,tcWomanName="+$("#tcWoman").text().replace("请选择套餐",""));

    $.ajax({
        type: 'post',
        url: ctxPath + '/retirement/addReservationData',
        dataType: 'json', // 服务器返回数据类型
        data: {
            id:hospitalVal,
            tcManId:tcMan,
            tcWomanId:tcWoman,
            personStr:personId,
            reservationTime:$("#reservationTime").val(),
            tcManName:$("#tcMan").text().replace("请选择套餐",""),
            tcWomanName:$("#tcWoman").text().replace("请选择套餐","")

        },
        async: false,
        success: function (data) {
            debugger;
            var count = data.count ;
            if(count ==1){
                layer.msg("预约成功！", {icon: 1});
                setTimeout(function () {
                    parent.layer.closeAll();
                },1500)
            }else{
                layer.msg("预约失败！", {icon: 2});
            }
        },
        error: function (err) {
            console.log("获取工程下拉列表出错：", err);
        }
    });


}

function getHospitalSelect() {
    $.ajax({
        type: 'post',
        url: ctxPath + '/utilConnection/getHospitalSelect',
        dataType: 'json', // 服务器返回数据类型
        data: {
        },
        async: false,
        success: function (data) {
            $("#hospital").empty();
            var data = data.data;
            var html = '<option value="0">请选择医院</option>';
            for (var i = 0; i < data.length; i++) {
                html += '<option value=\'' + data[i].key + '\'>' + data[i].value + '</option>';
            }
            $("#hospital").html(html);
            layui.form.render('select');  //这里就是我们要渲染的地方了
        },
        error: function (err) {
            console.log("获取工程下拉列表出错：", err);
        }
    });
}


function getTcManSelect(values) {
    $.ajax({
        type: 'post',
        url: ctxPath + '/utilConnection/getSetMeal',
        dataType: 'json', // 服务器返回数据类型
        data: {
            'type':'0',
            'keyWord':'2',
            'checkId':values,
            'higherJob':$("#higherJob").val()
        },
        async: false,
        success: function (data) {
            $("#tcMan").empty();
            var data = data.data;
            var html = '<option value="0">请选择套餐</option>';
            for (var i = 0; i < data.length; i++) {
                html += '<option value=\'' + data[i].key + '\'>' + data[i].value + '</option>';
            }
            $("#tcMan").html(html);
            layui.form.render('select');  //这里就是我们要渲染的地方了
        },
        error: function (err) {
            console.log("获取工程下拉列表出错：", err);
        }
    });

};

function getTcWomanSelect(values) {
    $.ajax({
        type: 'post',
        url: ctxPath + '/utilConnection/getSetMeal',
        dataType: 'json', // 服务器返回数据类型
        data: {
            'type':'1',
            'keyWord':'2',
            'checkId':values,
            'higherJob':$("#higherJob").val()
        },
        async: false,
        success: function (data) {
            $("#tcWoman").empty();
            var data = data.data;
            var html = '<option value="0">请选择套餐</option>';
            for (var i = 0; i < data.length; i++) {
                html += '<option value=\'' + data[i].key + '\'>' + data[i].value + '</option>';
            }
            $("#tcWoman").html(html);
            layui.form.render('select');  //这里就是我们要渲染的地方了
        },
        error: function (err) {
            console.log("获取工程下拉列表出错：", err);
        }
    });


}


// 设置可选日期
function maxDate() {
    var now = new Date();
    return now.getFullYear() + "-" + "10-31";
}
// 设置可选日期
function minDate() {
    var now = new Date();
    return now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
}
//周六周日不可选
function disabled_date(value) {
    var mm = value.year + '-' + value.month + '-' + value.date;
    $('.laydate-theme-grid table tbody').find('[lay-ymd="' + mm + '"]').removeClass('layui-this');
    var dates = [6,7];
    for (var i = 0; i < dates.length; i++) {
        if (dates[i] == "7") {
            dates[i] = 0;
        }
        $("table>tbody>tr").find("td:eq(" + dates[i] + ")").addClass('laydate-disabled');
    }
}