/**
 * 物料组管理首页JS
 *
 * Modify by likui on 2019/11/11.
 */
'use strict';
var el = {
    searchForm: '#searchForm',
    materialCode: '#materialCode',
    materialName: '#materialName',
    materialGroupCode: '#materialGroupCode',
    materialGroupName: '#materialGroupName',
    startCreateDate: '#startCreateDate',
    endCreateDate: '#endCreateDate',
    factory: '#factory',
    tb: '#tb',
    id: '#id',
    frmExcel: '#frmExcel',
    syncSapDialog: null,
    bodyHeight: document.documentElement.clientHeight

};

$(function () {

    $(el.factory).combobox({
        url: g.ctx + 'factory/provide/page/select',
        editable: false,
        valueField: 'factoryCode',
        textField: 'factoryCodeName',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 360
    });

    loadGrid();
    // importExcel();
});


/**
 * 加载数据表格
 */
function loadGrid() {
    var searchHeight = $(el.searchForm).outerHeight() - 10;
    var pager = initGridPager(el.bodyHeight - searchHeight * 2 - 120, 40);

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/sys/productGroup/rest/list',
        singleSelect: false,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        height: el.bodyHeight - searchHeight - 20,
        rownumbers: true,
        queryParams: {
            inquiryId:$(el.id).val(),
        },
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'disable',
                title: '数据状态',
                width: 80,
                exportEnum:[
                    {code:1,codeWithDesc:'正常'},
                    {code:2,codeWithDesc:'禁用'},
                ],
                formatter:function (value) {
                    if (value == 1) {

                        return '<a style="color:green;">'+"正常"+'</a>'

                    }else {
                        return '<a style="color:red;">'+"禁用"+'</a>'
                    }
                }
            },
            {
                field: 'erpStatus',
                title: '同步ERP状态',
                width: 100,
                exportEnum:[
                    {code:0,codeWithDesc:'待同步'},
                    {code:1,codeWithDesc:'同步成功'},
                    {code:2,codeWithDesc:'同步失败'},
                ],
                formatter:function (value) {
                    if (value === 0) {
                        return '<a style="color:grey;">待同步</a>'
                    }else if (value === 1){
                        return '<a style="color:green;">同步成功</a>'
                    }else if (value === 2){
                        return '<a style="color:red;">同步失败</a>'
                    }
                }
            },
            {
                field: 'materialGroup',
                title: '物料组编码',
                width: 100
            },
            {
                field: 'materialDesc',
                title: '物料组名称',
                width: 350
            },
            {
                field: 'categoryCode',
                title: '品类编码',
                width: 100
            },
            {
                field: 'categoryName',
                title: '品类名称',
                width: 350
            },
            {
                field: 'reqNum',
                title: '样品数量',
                width: 80
            },
            {
                field: 'createTime',
                title: '创建日期',
                width: 150,
               // exportDateFormatter:'dateTime',
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm:SS');
                    }
                    return '';
                }
            },
            {
                field: 'erpResult',
                title: '同步ERP反馈',
                width: 200
            },
            {
                field: 'erpTime',
                title: '同步ERP时间',
                width: 150,
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm:SS');
                    }
                    return '';
                }
            },
        ]],
        onLoadSuccess: function () {
            //displayButtonByUserRole('product.group');
        },
        toolbar: [
            {
                text: '导入',
                iconCls: 'icon-import',
                id: 'import',
                handler: function () {
                    dataImport();
                }
                // handler: function () {
                //     $("#detailUpload .filebox-label").click();
                // }
            },'-',
            {
                text: '导出',
                iconCls: 'icon-import',
                handler: function () {
                    openExportDialog('pc/sys/productGroup/rest/export','tb',{inquiryId:$(el.id).val()});
                }
            },'-',
            {
                text: '新增',
                id: 'add',
                iconCls: 'icon-add',
                hidden: true,
                handler: function () {
                    addOrEdit(0);
                }
            },'-',
            {
                text: '编辑',
                id: 'edit',
                iconCls: 'icon-edit',
                handler: function () {
                    addOrEdit(1);
                }
            },"-",
            {
                text: "禁用",
                id: 'btn_delete',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteData(2);

                }
            },'-',
            {
                text: "启用",
                id: 'btn_delete',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteData(1);

                }
            },'-',
            {
                text: '同步到ERP',
                iconCls: 'icon-reload',
                handler: function () {
                    syncSap();
                }
            }
        ]
    });
}
/**
 *新增编辑
 */
function addOrEdit(flag) {
    var id= '';
    if(flag===1){
        var cbox = $('#tb').datagrid('getSelected');
        if (cbox === null || cbox === undefined) {
            layer.msg("请选中一条记录");
            return;
        }
        id = cbox.id;
    }

    var moldFormDialog = openDialog('moldForm', g.ctx + 'pc/sys/productGroup/detail?id=' + id, {
        title: flag===0?'新增':'编辑',
        width: '50%',
        height: '40%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            moldFormDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.save,
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['moldForm'].saveOrUpdate(function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        moldFormDialog.dialog('close');
                        $(el.tb).datagrid('reload');
                    });
                }
            },
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    moldFormDialog.dialog('close');
                }
            }
        ]
    });
}
/**
 * 数据导入
 */
function dataImport() {
    var a = openImportExcelDialog("static/excel/product_group_list.xlsx", '物料组导入', function (file) {
        let formData = new FormData();
        formData.append("file", file);
        //取到fileId然后进行数据导入操作
        $.ajax({
            url: g.ctx + 'pc/sys/productGroup/rest/productGroupImportData',
            method: "POST",
            contentType: false,
            processData: false,
            data: formData,
            success: function (data) {
                topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    a.dialog('close');
                    $('#tb').datagrid('reload');
                });
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}


/**
 * 禁用/启用
 */
function deleteData(disable) {

    var rows = $(el.tb).datagrid("getSelections");
    if (rows.length == 0) {
        topWin.layer.msg("请选择数据",{icon:0});
        return;
    }
    layer.confirm('是否确认更改数据状态?', function (index) {
    var loading = topWin.layer.msg('数据处理中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: '/pc/sys/productGroup/rest/disable',
        method: "post",
        data: {
            id: rows[0].id,
            disable:disable
        },
        success: function () {
            topWin.layer.close(loading);
            topWin.layer.msg("操作成功",{icon:1});
            $(el.tb).datagrid('reload');
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
        layer.close(index)
    })

}

/**
 * 同步到sap
 */
function syncSap() {

    var rows = $(el.tb).datagrid("getSelections");
    if (rows.length === 0) {
        topWin.layer.msg("请选择数据",{icon:0});
        return;
    }
    let ids = [];
    for (let i = 0; i < rows.length; i++) {
        ids.push(rows[i].id);
    }
    topWin.layer.confirm('是否确认同步到ERP?', function (index) {
        var loading = topWin.layer.msg('数据处理中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: '/pc/sys/productGroup/rest/syncSap',
            method: "post",
            data: {
                ids: JSON.stringify(ids)
            },
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg("操作成功",{icon:1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loading);
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
        layer.close(index)
    })

}


/**
 * 选择物料
 * @param callback  选择物料数据的回调
 */
function chooseRow(callback) {
    var row = $(el.tb).datagrid('getSelected');
    callback(row);
}

/**
 * 导出excel
 */
function exportExcel() {
    layer.confirm('确定导出?', function (index) {
        document.getElementById("searchForm").action = g.ctx + '/product/export';
        document.getElementById("searchForm").submit();
        layer.close(index)
    });
}