/**
 * 送货单预约送货单
 * view/delivery/appointment_record/appointment.ftl
 */
var el = {
        clander: "#clander",
        tb: '#tb',
        appointmentDate: "#appointmentDate",
        ids: "#ids",
        factoryCode: "#factoryCode",
        id: "#id",
        dockerCode: "#dockerCode",
        urgencyFlag: "#urgencyFlag",
        bodyHeight: document.documentElement.clientHeight
    },
    maxRange = $(el.appointmentDate).val(),
    defaultDate = moment(new Date()).format('YYYY-MM-DD'),
    urgencyFlag = $(el.urgencyFlag).val(),
    dockerCode = $(el.dockerCode).val(),
    factoryCode = $(el.factoryCode).val();
    id = $(el.id).val();


$(function () {
    initClander();
    loadGrid();
});

/**
 * 校验日期是否可以选择
 * @param arr 失效日期数组
 */
function checkDate(arr) {
    var elem = $(".layui-laydate-content");//获取table对象
    layui.each(elem.find('tr'), function (trIndex, trElem) {//遍历tr
        layui.each($(trElem).find('td'), function (tdIndex, tdElem) {
            //遍历td
            var tdTemp = $(tdElem);
            if (tdTemp.hasClass('laydate-day-next') || tdTemp.hasClass('laydate-day-prev')) {
                return;
            }
            // if (tdIndex == 1) { //此时周一不可选
            //     //此处判断，是1的加上laydate-disabled，0代表星期日
            //     tdTemp.addClass('laydate-disabled');
            // }
            if (arr.indexOf(tdTemp.attr("lay-ymd")) > -1) {//指定数组中的日期不可选
                tdTemp.addClass('laydate-disabled');
            }
        });
    });
}

/**
 * 初始化日历
 */
function initClander() {
    var mark = {};
    for (let i = 0; i < dayOffArr.length; i++) {
        let dayOffArrElement = dayOffArr[i];
        mark[dayOffArrElement] = "休息";
    }
    laydate.render({
        elem: el.clander,
        position: 'static',
        min: 0,
        max: Number(maxRange),
        value: defaultDate,
        calendar: true,
        mark: mark,
        showBottom: false,
        format: "yyyy-MM-dd",
        ready: function () {
            checkDate(dayOffArr);
        },
        change: function () {
            checkDate(dayOffArr);
        },
        done: function (value, date, endDate) {
            defaultDate = value;
            $(el.tb).datagrid('options').queryParams = {
                selectDay: defaultDate, factoryCode: factoryCode,
                dockerCode: dockerCode
            };
            $(el.tb).datagrid('load');
            $(el.tb).datagrid('clearSelections');
            console.log(value); //得到日期生成的值，如：2017-08-18
            console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
        }
    });
}


/**
 * 初始化表格数据
 *
 */
function loadGrid() {
    let pager = initGridPagerNew(el.bodyHeight, 37, 40);
    $(el.tb).datagrid({
        height: el.bodyHeight - $(el.clander).outerHeight(),
        width: gridwidth,
        url: g.ctx + 'pc/order/appointmentTime/rest/appointmentList',
        singleSelect: true,
        pagination: false,
        idField: '',
        autoHeight: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        fitColumns: false,
        striped: true,
        page: 1,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {
            factoryCode: factoryCode,
            selectDay: defaultDate,
            dockerCode: dockerCode
        },
        columns: [[
            {
                field: 'ck',
                checkbox: 'true'
            },
            {
                field: 'rang',
                title: '时间范围',
                width: '120',
                align: 'left',
            },
            {
                field: 'startTime',
                title: '开始时间',
                width: '160',
                align: 'left',
            },
            {
                field: 'endTime',
                title: '结束时间',
                width: '160',
                align: 'left',
            },
            {
                field: 'hasAppointNum',
                title: '已预约数量',
                width: '120',
                align: 'left',
            },
            {
                field: 'surplusNum',
                title: '剩余可预约数量',
                width: '120',
                align: 'left',
            },
        ]],
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');
        }
    });
}

/**
 * 预约提交 送货单类型
 * @param urgencyFlag
 * @param callback
 */
function submit(urgencyFlag, callback) {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg('选择要预约的时间段', {icon: 2});
        return;
    }
    if (urgencyFlag === 0 && row.surplusNum <= 0) {
        topWin.layer.msg('当前可预约数为0', {icon: 2});
        return;
    }
    if (urgencyFlag === 1 && row.surplusNum > 0) {
        topWin.layer.msg('当前有可预约数量，无需插队', {icon: 2});
        return;
    }
    var load = topWin.layer.load(2);
    $.ajax({
        url: g.ctx + 'pc/order/appointmentRecord/rest/devOrder/save',
        method: "post",
        data: {
            selectDay: defaultDate,
            appointmentId: row.id,
            id: id,
            deliveryIds: $(el.ids).val(),
            urgencyFlag: urgencyFlag,
            factoryCode: factoryCode,
            dockerCode: dockerCode,
            supplierCode: $("#supplierCode").val(),
            supplierName: $("#supplierName").val(),
        },
        complete: function () {
            topWin.layer.close(load);
        },
        success: function (data) {
            callback(data);
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}


/**
 * 变更提交
 * @param callback
 */
function changeDate(callback) {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        parent.layer.msg('选择要预约的时间段', {icon: 2});
        return;
    }
    if (urgencyFlag === '0' && row.surplusNum <= 0) {
        parent.layer.msg('当前可预约数为0', {icon: 2});
        return;
    }
    var load = parent.layer.load(2);
    $.ajax({
        url: g.ctx + 'pc/order/appointmentRecord/rest/devOrder/change',
        method: "post",
        data: {
            selectDay: defaultDate,
            appointmentId: row.id,
            ids: $(el.ids).val(),
            dockerCode: dockerCode,
            factoryCode: factoryCode,
            supplierCode: $("#supplierCode").val(),
            supplierName: $("#supplierName").val(),
        },
        success: function (data) {
            parent.layer.close(load);
            callback(data);
        },
        error: function (data) {
            parent.layer.close(load);
            callback(data);
        }
    });
}
