/**
 * 物料管理首页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',
    factoryCode: '#factoryCode',
    tb: '#tb',
    frmExcel: '#frmExcel',
    syncSapDialog: null,
    bodyHeight: document.documentElement.clientHeight
};

$(function () {

    $(el.factoryCode).combobox({
        url: g.ctx + 'pc/sys/factory/rest/listAll',
        editable: false,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        onLoadSuccess: function () { //加载完成后,设置选中第一项
            var val = $(this).combobox("getData");
            for (var item in val[0]) {
                if (item === "code") {
                    $(this).combobox("select", val[0][item]);
                    loadGrid();
                }
            }
        }
    });

    // 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/product/rest/list',
        singleSelect: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        height: el.bodyHeight - searchHeight - 20,
        rownumbers: true,
        queryParams: {
            factoryCode:$(el.factoryCode).combobox('getValue')
        },
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'materialCode',
                title: '物料编码',
                width: 100
            },
            {
                field: 'freeze',
                title: '冻结状态',
                width: 100,
                formatter: function (value) {
                    if(value==1){
                        return '<span style="color: red">已冻结</span>';
                    }else {
                        return '<span  style="color: green" >未冻结</span>';
                    }
                }
            },
            {
                field: 'materialName',
                title: '物料名称',
                width: 340,
                formatter: function (value) {
                    return '<span title="'+value+'">'+value+'</span>';

                }
            },
            {
                field: 'materialGroupCode',
                title: '物料组编码',
                width: 100
            },
            {
                field: 'materialGroupName',
                title: '物料组名称',
                width: 300
            },
            // {
            //     field: 'materialSpec',
            //     title: '规格',
            //     width: 100
            // },
            // {
            //     field: 'productName',
            //     title: '品名',
            //     width: 100
            // },
            // {
            //     field: 'brand',
            //     title: '品牌',
            //     width: '100'
            // },
            // {
            //     field: 'manufacturer',
            //     title: '生产厂家',
            //     width: 100
            // },
            {
                field: 'basisUnit',
                title: '物料基本单位',
                width: 100
            },
            {
                field: 'orderUnit',
                title: '采购单位',
                width: 100
            },
            {
                field: 'unitChange',
                title: '转换比例',
                width: 100
            },
            // {
            //     field: 'is_gmp',
            //     title: '质量控制物料',
            //     width: 100,
            //     formatter: function (value, row, index) {
            //         if (value =="X")
            //             return "<sapn style='color: red;'>是</sapn>";
            //         else
            //             return "否"
            //     }
            // },
            {
                field: 'factoryCode',
                title: '工厂编码',
                width: 80
            },

            {
                field: 'materialPurchaseGroup',
                title: '物料采购组',
                width: 100
            },
            {
                field: 'estimatedPrice',
                title: '采购预估价',
                width: 100
            },
            // {
            //     field: 'mrp_control_user',
            //     title: '采购计划员',
            //     width: 100
            // },
            // {
            //     field: 'storage_conditions',
            //     title: '存储条件',
            //     width: 100
            // },
            // {
            //     field: 'storage_conditions_name',
            //     title: '存储条件名称',
            //     width: 100
            // },
            // {
            //     field: 'stand_code',
            //     title: '批准文号/注册证号',
            //     width: 150
            // },
            // {
            //     field: 'division',
            //     title: '级别',
            //     width: 100
            // },{
            //     field: 'casitem_no',
            //     title: 'CAS/货号',
            //     width: 100
            // },
            {
                field: 'deliveryPlanDays',
                title: '采购提前期（天）',
                width: 100
            },
            // {
            //     field: 'safety_stock',
            //     title: '安全库存',
            //     width: 100
            // },{
            //     field: 'quantity_range',
            //     title: '容差',
            //     width: 100
            // },{
            //     field: 'risk_level',
            //     title: '风险级别',
            //     width: 100
            // },{
            //     field: 'arrival_time',
            //     title: '到货处理时间',
            //     width: 100
            // },
            {
                field: 'deleteFlag',
                title: '删除标识',
                width: 100,
                formatter: function (value) {
                    switch (value) {
                        case 1:
                            return "<sapn style='color: red;'>已删除</sapn>";
                        default:
                            return "未删除"

                    }
                }
            },
            {
                field: 'createTime',
                title: '同步日期',
                width: 140,
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm:SS');
                    }
                    return '';
                }
            },
            {
                field: 'lastUpdateTime',
                title: '同步修改日期',
                width: 140,
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm:SS');
                    }
                    return '';
                }
            }
        ]],
        onLoadSuccess: function () {
            displayButtonByUserRole('materail_data');
        },
        toolbar: [
            {
                text: '冻结',
                iconCls: 'icon-lock',
                id: 'lock',
                handler: function () {
                    lockState(1);
                }
            }, "-",{
                text: '解冻',
                iconCls: 'icon-undo',
                id: 'undo',
                handler: function () {
                    lockState(0);
                }
            }, "-",{
                text: '同步',
                iconCls: 'icon-reload',
                id: 'sync_sap',
                handler: function () {
                    syncSap();
                }
            },"-",{
                text: '同步单位转换',
                iconCls: 'icon-reload',
                id: 'sync_unit_convert',
                handler: function () {
                    syncUnitConvert();
                }
            }, "-",
            {
                text: '物料导出',
                iconCls: 'icon-download',
                id: 'export',
                handler: function () {
                    commonExportExcel2("#tb", "/product/exportExcel");
                }
            }, "-",
            {
                text: '同步至单据',
                iconCls: 'icon-reload',
                id: 'sync_invoices',
                handler: function () {
                    syncInvoices();
                }
            }
        ]
    });
}

function syncInvoices() {
    let row = $('#tb').datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    layer.confirm('是否确认同步？', function (index) {
        $.ajax({
            url: '/product/sync/invoices',
            method: "post",
            data: {id: row.id},
            beforeSend: function () {
                topWin.layer.load(0);
            },
            complete: function () {
                topWin.layer.closeAll('loading');
            },
            success: function (data) {
                if (data == "ok") {
                    $('#tb').datagrid('load');
                    layer.msg("同步成功!");
                    layer.close(index);
                } else {
                    layer.msg("同步成功!");
                }
            },
            error: function (data) {
                layer.close(index);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}
/**
 * 导入
 */
function importExcel() {
    $("#fileInput").filebox({
        buttonText: 'Choose',
        buttonAlign: 'left',
        onChange: function () {
            let filebox = $("#fileInput").filebox("files");
            if (filebox.length == 1) {
                let formData = new FormData();
                formData.append("file", filebox[0]);
                let index = layer.load(1, {
                    shade: [0.1, '#eee'] //0.1透明度的白色背景
                });
                $.ajax({
                    url: g.ctx + 'product/import',
                    data: formData,
                    type: 'post',
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        layer.close(index);
                        layer.msg("导入成功",{
                            time : 1000
                        });
                        $(el.tb).datagrid('reload');
                    },
                    error:function(xhr,state,errorThrown){
                        layer.close(index);
                        layer.alert(xhr.responseJSON.message);
                    }
                });
                $("#fileInput").filebox("clear");
            }
        }
    })
}

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


/**
 * 同步ERP物料
 */
function syncSap() {
    var url = g.ctx + 'product/syncUI';
    el.syncSapDialog = openDialog('syncSap', url, {
        title: '同步ERP物料主数据信息',
        width: "55%",
        height: "75%",
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.syncSapDialog.dialog('destroy');
        },
        buttons: [{
            text: '同步',
            handler: function () {
                topWin.frames['syncSap'].syncSapResult(function () {
                    $(el.tb).datagrid('load');
                    el.syncSapDialog.dialog('close');
                });
            }
        }, {
            text: '关闭',
            handler: function () {
                el.syncSapDialog.dialog('close');
            }
        }]
    });
}

/**
 * 同步物料单位转换
 */
function syncUnitConvert() {
    // var url = g.ctx + 'product/syncUnitConvertUI';
    // el.syncUnitConvert = openDialog('syncUnitConvert', url, {
    //     title: '同步ERP物料单位转换信息',
    //     width: "55%",
    //     height: "75%",
    //     cache: false,
    //     modal: true,
    //     border: 'thin',
    //     onClose: function () {
    //         el.syncUnitConvert.dialog('destroy');
    //     },
    //     buttons: [{
    //         text: '同步',
    //         handler: function () {
    //             topWin.frames['syncUnitConvert'].syncSapResult(function () {
    //                 $(el.tb).datagrid('load');
    //                 el.syncUnitConvert.dialog('close');
    //             });
    //         }
    //     }, {
    //         text: '关闭',
    //         handler: function () {
    //             el.syncUnitConvert.dialog('close');
    //         }
    //     }]
    // });
    layer.confirm('是否同步物料单位转换主数据？', function (index) {
        let url = g.ctx + 'product/info/rest/synUomConversions';
        layer.load(1);
        $.ajax({
            url: url,
            method: "post",
            // data: {materialIds: JSON.stringify(materialIds), status: state},
            success: function (data) {
                layer.closeAll('loading');

                if (data == "true" || data == true) {
                    $(el.tb).datagrid('reload');
                    $(el.tb).datagrid('clearSelections');
                    layer.closeAll('dialog');
                } else {
                    layer.alert("提交失败!");
                }
            },
            error: function (data) {
                layer.closeAll('loading');
                layer.alert(common_opt_msg.opt_fail_msg);
            }
        });
    });

}

/**
 * 冻结、解冻
 * @param state 1.冻结 0.正常
 */
function lockState(state) {
    let title;
    switch (state) {
        case 0:
            title = '解冻';
            break;
        case 1:
            title = '冻结';
            break;
        default:
    }

    let rows = $(el.tb).datagrid('getSelections');
    if (rows.length < 1) {
        layer.msg("请选中一条记录");
        return;
    }

    let materialIds = [];

    $.each(rows, function (index, item) {
        if (item.state !== String(state)) {
            materialIds.push(item.id);
        }
    });

    if (materialIds.length < 1) {
        layer.msg('请选择可' + title + '数据');
        return;
    }

    layer.confirm('是否' + title + '该物料？', function (index) {
        let url = '/product/lockState';
        layer.load(1);
        $.ajax({
            url: url,
            method: "post",
            data: {materialIds: JSON.stringify(materialIds), status: state},
            success: function (data) {
                layer.closeAll('loading');
                if (data === "success") {
                    $(el.tb).datagrid('reload');
                    $(el.tb).datagrid('clearSelections');
                    layer.closeAll('dialog');
                } else {
                    layer.alert("提交失败!");
                }
            },
            error: function (data) {
                layer.closeAll('loading');
                layer.alert(common_opt_msg.opt_fail_msg);
            }
        });
    });
}
/**
 * 数据查询
 */
function materialSearch() {
    var queryParams = {};
    queryParams.materialCode =  $.trim($(el.materialCode).val()).split(' ').join('|');
    queryParams.materialName = $.trim($(el.materialName).val());
    queryParams.materialGroupCode = $.trim($(el.materialGroupCode).val());

    queryParams.materialGroupName = $.trim($(el.materialGroupName).val());
    queryParams.factoryCode = $(el.factoryCode).combobox('getValue');
    $(el.tb).datagrid('options').queryParams = queryParams;
    $(el.tb).datagrid('reload');
}


/**
 * 数据查询重置
 */
function materialSearchReset() {
    $(el.materialCode).val('');
    $(el.materialName).val('');
    $(el.materialGroupCode).val('');
    $(el.materialGroupName).val('');
    // $(el.factoryCode).combobox('setValue', '');

    materialSearch();
}

$(function () {
    document.addEventListener("keydown", function (event) {
        if (event.key === 'Enter') {
            materialSearch();
        }
    })
})

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