var el = {
    form : '#form',
    useState: '#useState',
    attachment: '#attachment',
    factoryCode: '#factoryCode',

    combobox: {
        factory: []
    },
    factoryCode: "",
    selectedMaterials: [],
    tableData: {}
}
$(function () {
    //loadGrid();
    // 初始化工厂下拉框
    $(el.factoryCode).combobox({
        url: g.ctx + 'pc/sys/factory/rest/listAll',
        editable: false,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        onChange: function (value) {
            el.factoryCode = value;
            loadGrid(value);
        }
    });
});
/**
 * 加载页面表格
 */
function loadGrid() {
    $('#tb_material').datagrid({
        iconCls: 'icon-list',
        title: '配额物料列表',
        height: gridheight - 43,
        width: gridwidth,
        //singleSelect: true,
        pagination: true,
        idField: 'addUniqueFlag',
        autoHeight: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        fitColumns: false,
        remoteSort: true,
        view: detailview,
        columns: columns1,
        page: 1,
        pageSize: 10,
        queryParams: {
            page: 1,
            rows: 10
        },
        detailFormatter: function (index, row) {
            return '<div id="ddv-' + index + '" style="padding:5px"></div>';
        },
        // 展开行
        onExpandRow: function (index, row) {
            $('#ddv-' + index).datagrid({
                rownumbers: true,
                loadMsg: '数据加载中......',
                onClickCell: onClickCell,
                onAfterEdit: onAfterEdit,
                data: el.tableData[index].supplierQuotaDetail,
                columns: columns2,
                onResize: function () {
                    $('#tb_material').datagrid('fixDetailRowHeight', index);
                },
                onLoadSuccess: function (data) {
                    setTimeout(function () {
                        $('#tb_material').datagrid('fixDetailRowHeight', index);
                    }, 0);
                    $(".datagrid-row-detail .datagrid-header-check").html("");
                },
            });
            $('#tb_material').datagrid('fixDetailRowHeight', index);
        },
        onLoadSuccess: function (data) {
            el.tableData = data.rows;

            // 设置index
            if (data && data.rows.length > 0) {
                $.each(data.rows, function (index, row) {
                    row.index = index;
                });
            }

            // 加载easyUI样式
            //$.parser.parse($(".easyui-datebox").parent());

            // 默认展开行内table行
            let tb = $('#tb_material');
            let rows = tb.datagrid("getRows");
            for (let i = 0; i < rows.length; i++) {
                tb.datagrid("expandRow", i);
            }

            sessionStorage.clear();
        },
        toolbar: [
            {
                text: '选择物料',
                iconCls: 'icon-add',
                handler: function () {
                    selectMaterial();
                }
            }, "-",{
                text: '导出模板',
                iconCls: 'icon-download',
                handler: function () {
                    window.open(g.ctx + 'open/bid/rest/export/tmp3?templateId=347&templateTitle=' + encodeURI("物料导入模板"));
                }
            }, "-",
            {
                text: '导入物料信息',
                iconCls: 'icon-import',
                handler: function () {
                    $("#materialUpload .filebox-label").click();
                }
            }, "-", {
                text: '删除',
                id: 'delete',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteData();
                }
            }
        ],
        onCheck: function (rowIndex,rowData) {
            $('#ddv-' + rowIndex).datagrid("checkAll");
        },
        onUncheck: function (rowIndex,rowData) {
            $('#ddv-' + rowIndex).datagrid("uncheckAll");
        },
        onCheckAll: function (rows) {
            // 同时checkAll子表行
            for (let i = 0, len = rows.length; i < len; i++) {
                $('#ddv-' + i).datagrid("checkAll");
            }
        },
        onUncheckAll: function (rows) {
            // 同时checkAll子表行
            for (let i = 0, len = rows.length; i < len; i++) {
                $('#ddv-' + i).datagrid("uncheckAll");
            }
        }
    });
}
/**
 * 物料导入
 */
function materialImport () {
    var filebox = $("#materialFileInput").filebox("files");
    if (filebox.length == 1) {
        var formData = new FormData();
        formData.append("file", filebox[0]);
        var index = layer.load(1, {
            shade: [0.1, '#eee'] //0.1透明度的白色背景
        });
        $.ajax({
            url: g.ctx + 'evl/person/rest/material/import',
            data: formData,
            type: 'post',
            contentType: false,
            processData: false,
            success: function (d) {
                if (d.result == 1){
                    let materialCodes = [];
                    $.each(d.msg, function (index, item) {
                        materialCodes[materialCodes.length] = item.material_code;
                    });
                    layer.close(index);

                    let options = $('#tb_material').datagrid("options");
                    options.queryParams.factoryCode = el.factoryCode;
                    options.queryParams.materialCodes = JSON.stringify(materialCodes);
                    options.url = '/quotaManagement/maintain/generateSupplierQuotaDetail';
                    $('#tb_material').datagrid("load");

                } else {
                    var materialCodes = d.msg;
                    var msg = "";
                    var index2 = "";
                    for (var i = 0;i<materialCodes.length;i++){
                        if (i == materialCodes.length -1){
                            index2 = index2 + (i+1);
                            msg = msg + materialCodes[i];
                        }else{
                            index2 = index2 + (i+1) + ",";
                            msg = msg + materialCodes[i]+",";
                        }

                    }
                    layer.confirm("第"+index2+"行物料编码为："+msg+"没有相关物料信息");

                    layer.close(index);
                }

            },
            error :function (data) {
                layer.close(index);;
                parent.layer.alert(data.responseJSON.message)
            }
        })
    }
}
 function saveOrUpdate(call) {
    if (!$(el.form).form('validate')) {
        layer.msg("必填项未填写!");
        return
    }
    var array = $(el.form).serializeArray();
    var person = {};
    person.id = id;
    var dcArray = [];
    var category=[];
    person.userId = 0;
    $.each(array, function (index, item) {
        switch (item.name) {
            case 'dc':
                dcArray.push(item.value);
                break;
            default:
                person[item.name] = item.value;
                break;
        }
    });
    person['dimensionCodes'] = dcArray;
    person['categoryId'] = category;
    $.ajax({
        url: g.ctx + 'pc/tender/expertManage/rest/saveOrUpdate',
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(person),
        success: function (data) {
            layer.msg("操作成功!");
            call();
        },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                layer.alert(JSON.parse(data.responseText).message);
            }
        });

}
// function saveOrUpdate(call) {
//     if($(el.form).form('validate')){
//         var formData = $(el.form).serializeJson();
//         var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
//         $.ajax({
//             url: g.ctx + 'pc/tender/expertManage/rest/saveOrUpdate',
//             method: 'post',
//             data: formData,
//             success: function (data) {
//                 call();
//             },
//             complete: function(data) {
//                 top.layer.close(loading);
//             },
//             error: function (data) {
//                 layer.alert(JSON.parse(data.responseText).message);
//             }
//         });
//     }else{
//         layer.msg("红色框为必输项，请填写！");
//     }
// }
function searchSupplier(){
    var userOrgyDialog = openDialog('userOrgyDialog', g.ctx + 'pc/supplier/supplierSelect?single=1', {
        title: "选择供应商",
        width: '650px',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userOrgyDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.confirm,
                handler: function () {
                    topWin.frames['userOrgyDialog'].chooseRow(function (cbox) {console.log(cbox)
                        $("#supplierId").val(cbox.id);
                        $("#supplierCode").val(cbox.supplierCode);
                        $('#supplierName').textbox('setValue', cbox.supplierName)
                        userOrgyDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                handler: function () {
                    userOrgyDialog.dialog('close');
                }
            }
        ]
    });
}