/**
 * 预约到货供应商配置表
 */


let el = {
    tb: '#tb',
    searchForm: '#searchForm',
    bodyHeight: document.documentElement.clientHeight,
    status: "#status",
    week: '#week',
    dockerCode:"#dockerCode",
    factoryCode:"#factoryCode"
};

$(function () {
    // $(el.status).combobox({
    //     valueField: 'value',
    //     textField: 'label',
    //     value: 1,
    //     data: [
    //         {label: '禁用', value: 0},
    //         {label: '启用', value: 1}
    //     ],
    //     editable: false,
    //     panelHeight: 'auto',
    // });

    //获取下拉框数据
    initNecessaryDatas("pc/sys/factory/rest/listAll");
    //获取字典数据
    initDict("week");

    $(el.factoryCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        data: getNecessaryDataList("pc/sys/factory/rest/listAll"),
        panelHeight: 'auto',
    });

    $(el.dockerCode).combogrid({
        panelWidth: 450,
        idField: 'dockerCode',
        textField: 'dockerName',
        prompt: '-- 请选择 --',
        editable: false,
        url: g.ctx+'pc/order/appointmentDocker/rest/listAll',
        columns: [[
            {field: 'dockerCode', title: '卸货点编码', width: 60},
            {field: 'dockerName', title: '卸货点名称', width: 100},
            {field: 'factoryCode', title: '工厂编码', width: 100},
            {field: 'factoryName', title: '工厂名称', width: 200}
        ]],
    });

    $(el.week).combobox({
        valueField: 'code',
        textField: 'name',
        data: getDictList("week"),
        editable: false,
        panelHeight: 'auto',
    });

    loadGrid();
});

function loadGrid() {
    let searchHeight = $(el.searchForm).outerHeight();
    let pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);

    $(el.tb).datagrid({
        height: el.bodyHeight - searchHeight,
        width: gridwidth,
        url: g.ctx+'pc/order/appointmentTime/rest/list',
        singleSelect: true,
        pagination: true,
        idField: '',
        autoHeight: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        fitColumns: false,
        striped: true,
        page: 1,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {
            page: 1,
            rows: 20
        },
        columns: [[
            {
                field: 'ck',
                checkbox: 'true'
            },
            {
                field: 'week',
                title: '星期',
                width: '100',
                align: 'left',
                formatter: function (data) {
                    switch (data) {
                        case "1":
                            return "周日";
                        case "2":
                            return "周一";
                        case "3":
                            return "周二";
                        case "4":
                            return "周三";
                        case "5":
                            return "周四";
                        case "6":
                            return "周五";
                        case "7":
                            return "周六";
                    }
                }
            },
            {
                field: 'factoryCode',
                title: '工厂编码',
                width: '100',
                align: 'left',
            },
            {
                field: 'factoryName',
                title: '工厂名称',
                width: '160',
                align: 'left',
            },
            {
                field: 'dockerCode',
                title: '卸货点编码',
                width: '100',
                align: 'left',
            },
            {
                field: 'dockerName',
                title: '卸货点名称',
                width: '100',
                align: 'left',
            },
            {
                field: 'startTime',
                title: '预约时段',
                width: '100',
                align: 'left',
                formatter: function (value, row, index) {
                    return value + ' - ' + row.endTime;
                }
            },
            {
                field: 'maxNum',
                title: '最大预约量',
                width: '100',
                align: 'left',
            },
            {
                field: 'maxThreshold',
                title: '绿色放行阈值',
                width: '100',
                align: 'left',
                hidden: true
            },
            {
                field: 'status',
                title: '启用状态',
                width: '100',
                align: 'left',
                formatter: function (data) {
                    if (Number(data) === 1)
                        return "启动";
                    else
                        return "<span style='color: red' >禁用</span>"
                }
            },


        ]],
        toolbar: [
            {
                text: '新增',
                id:'btn-add',
                iconCls: 'icon-add',
                handler: function () {
                    addOrEdit(1);
                }
            },
            "-", {
                text: '编辑',
                id:'btn-edit',
                iconCls: 'icon-edit',
                handler: function () {
                    addOrEdit(2);
                }
            },
            "-", {
                text: '删除',
                id:'btn-delete',
                iconCls: 'icon-delete',
                handler: function () {
                    delData();
                }
            }
        ],
        onLoadSuccess: function () {
            autoMergeCells();
            $(el.tb).datagrid('clearSelections');
        }
    });
}


/**
 * 新增、编辑、查看
 * @param type 1.新增 2.编辑 3.查看
 */
function addOrEdit(type) {
    let title, url, btn, btn1Fc, row;
    switch (type) {
        case 1:
            title = "新增"
            url = g.ctx+'pc/order/appointmentTime/detail?type=' + type;
            btn = ['保存', '关闭'];
            btn1Fc = function (index, layero) {
                let iframe = parent.window[layero.find('iframe')[0]['name']];
                iframe.submitForm(function () {
                    parent.layer.close(index);
                    $(el.tb).datagrid('reload');
                });
            }
            break;
        case 2:
            title = '编辑';
            row = $(el.tb).datagrid('getSelected');
            if (!row) {
                layer.msg('请选择编辑的数据!');
                return;
            }
            url = g.ctx+'pc/order/appointmentTime/detail?id=' + row['id'] + '&type=' + type;
            btn = ['保存', '关闭'];
            btn1Fc = function (index, layero) {
                let iframe = parent.window[layero.find('iframe')[0]['name']];
                iframe.submitForm(function () {
                    parent.layer.close(index);
                    $(el.tb).datagrid('reload');
                });
            }
            break;
        case 3:
            title = '查看';
            row = $(el.tb).datagrid('getSelected');
            if (!row) {
                layer.msg('请选择查看的数据!');
                return;
            }
            url = g.ctx+'pc/order/appointmentTime/detail?id=' + row['id'];
            btn = ['关闭'];
            btn1Fc = function (index) {
                parent.layer.close(index)
            };
            break;
    }

    parent.layer.open({
        title: title,
        skin: 'layui-layer-molv',
        type: 2,
        area: ['50%', '80%'],
        content: url,
        btn: btn,
        yes: btn1Fc
    })
}

/**
 * 删除
 */
function delData() {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        layer.msg('请选择编辑的数据!');
        return;
    }

    parent.layer.load(1);
    $.post(g.ctx+'pc/order/appointmentTime/rest/remove', {id: row.id}, function () {
        parent.layer.msg('操作成功');
        $(el.tb).datagrid('load');
    }).error(function (data) {
        let msg = JSON.parse(data['responseText'])['message'];
        layer.msg('保存失败！ ' + msg);
    }).complete(function () {
        parent.layer.closeAll('loading');
    })

}




/**
 * 自动合并单元格
 */
function autoMergeCells() {
    // tableDom 表格HTML中DOM; judge 判断条件
    var judge = 'week';
    // field_arr 需要合并的列
    var field_arr = ['week', 'factoryCode', 'factoryName', 'dockerCode', 'dockerName'];
    var rows = $(el.tb).datagrid('getRows');
    if (NULL(field_arr) || NULL(rows)) {
        return;
    }
    for (var i = 1; i < rows.length; i++) {
        for (var k = 0; k < field_arr.length; k++) {
            // 要排序的字段
            var field = field_arr[k];
            // 相邻的上下两行
            if (rows[i][field] === rows[i - 1][field]) {
                if (NOTNULL(judge)) {
                    if (rows[i][judge] !== rows[i - 1][judge]) {
                        continue;
                    }
                }
                var rowSpan = 2;
                // 判断上下多行内容一样
                for (var j = 2; i - j >= 0; j++) {
                    if (rows[i][field] !== rows[i - j][field]) {
                        break;
                    } else {
                        if (NOTNULL(judge)) {
                            if (rows[i][judge] !== rows[i - j][judge]) {
                                break;
                            }
                        }
                        rowSpan = j + 1;
                    }
                }
                // 合并
                $(el.tb).datagrid('mergeCells', {
                    index: i - rowSpan + 1,
                    field: field,
                    rowspan: rowSpan
                });
            }
        }
    }
}


/**
 * 判断字符串不为空
 *
 * @return {boolean}
 */
function NOTNULL(obj) {
    return !(typeof (obj) === 'undefined' || obj === '' || obj == null || obj === 'null');

}


/**
 * 判断字符串为空
 *
 * @return {boolean}
 */
function NULL(obj) {
    return typeof (obj) === 'undefined' || obj === '' || obj == null || obj === 'null';

}
