let el = {
    combobox: {
        factory: []
    },
    factoryCode: "",
    factoryCode: '#factoryCode',
    selectedMaterials: [],
    tableData: {},
    tbMaterial : '#tb_material',
};


// (function initComBoBoxFactory() {
//     $.ajax({
//         url: g.ctx + 'xj/common/rest/find/factory',
//         type: 'post',
//         async: false,
//         success: function (data) {
//             el.combobox.factory = data;
//         },
//         error: function (data) {
//             layer.msg("获取工厂列表失败", {time: 2000});
//         }
//     });
//
// })();

$(function () {
    // $("#factoryCode").combobox({
    //     valueField: 'factory',
    //     textField: 'factoryName',
    //     panelHeight: 100,
    //     panelWidth: 250,
    //     data: el.combobox.factory || [],
    //     editable: false,
    //     onChange: function (value) {
    //         el.factoryCode = value;
    //         loadGrid(value);
    //     }
    // });

    $("#factoryCode").combobox({
        url: g.ctx + 'pc/sys/factory/rest/listAll',
        editable: false,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        panelHeight: 100,
        panelWidth: 250,
        onChange: function (value) {
            el.factoryCode = value;
            loadGrid(value);
        }
    });
    loadGrid();
    // // 设置第一个值为默认值
    let valueField = $("#factoryCode").combobox("options").valueField;
    let allData = $("#factoryCode").combobox("getData");
    if (!allData || allData.length < 1) {
        layer.msg("当前用户未配置工厂数据");
        return false;
    }
    let firstValue = allData[0][valueField];
    let factoryCode = sessionStorage.getItem("factoryCode");
    if (!factoryCode) {
        $("#factoryCode").combobox("setValue", firstValue);
    } else {
        $("#factoryCode").combobox("setValue", factoryCode);
        $("#factoryCode").combobox("disable");
    }

    // 如果session中存在 materialCodes ，说明是从'无配额物料查询'发起的配额新增
    let materialCodes = sessionStorage.getItem("materialCodes");
    if (materialCodes) {
        returnSelectProduct(materialCodes.split(","));
    }

});

function loadGrid() {
    // 在页面上申明一个新的表格DOM
    //el.tbMaterial = $('<table id="tb_material" width="100%"></table>').appendTo($('.tb-material'));
    $('#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({
                url: '/quotaManagement/maintain/getSupplierQuotaDetail',
                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 selectMaterial() {
    // let url = g.ctx + 'pc/sys/product/select/dialog?factoryCode=' + el.factoryCode;
    // let title = common_layer_title.select_material_title;
    // openLayerWin(title, url, '1000px', '560px');

    let factoryCode = $("#factoryCode").combobox('getValue');
    if(!factoryCode){
        layer.alert('请先选择工厂', {icon: 0});
        return false;
    }
    var selectMaterialElement = openDialog("selectMaterialDialog", g.ctx + 'pc/sys/product/select/dialog', {
        title: '选择物料',
        width: '80%',
        height: '75%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            selectMaterialElement.dialog('destroy');
        },
        buttons: [{
            text: '确定',
            iconCls: 'icon-save',
            handler: function () {
                console.log(12312312312312)
                topWin.frames['selectMaterialDialog'].chooseRows(function (data) {
                    console.log(data)
                    let ps = $('#tb_material').datagrid('getRows');
                    for (let i = 0; i < data.length; i++) {
                        let product = data[i];
                        let sameFlag = false;
                        for (let j = 0; j < ps.length; j++) {
                            if (product.id === ps[j].productId) {
                                sameFlag = true;
                                break;
                            }
                        }
                        if (sameFlag){
                            continue;
                        }
                        console.log(product)
                        $('#tb_material').datagrid('appendRow', {
                            productId: product.id,
                            materialName: product.materialName,
                            materialCode: product.materialCode,
                            orderUnit: product.orderUnit,
                            lastQuarterInMoney: '0',
                            mpq: product.mpq,
                            effectDate: product.effectDate,
                            invalidDate: product.invalidDate,
                            // productName: product.productName,
                            // materialSpec: product.materialSpec,
                            // materialModel: product.materialModel,
                            // brand: product.brand,
                            // costFlag:0,
                            // stagePriceFlag:0,
                            // number:0,
                            // materialGroupCode: product.materialGroupCode,
                            // materialGroupName: product.materialGroupName,
                            // materialUnit: product.basisUnit,
                            // purchaseUnit:product.orderUnit,
                            // factoryCode: product.factoryCode,
                            // currencyCode:'CNY'
                        });
                    }
                    selectMaterialElement.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                selectMaterialElement.dialog('close');
            }
        }]
    });
}

// 保存配额
function saveQuota() {
    let $tg = $('#tb_material');
    let rows = $tg.datagrid("getRows");
    let result = [];
    for (const line of rows) {
        let index = line.index;
        let detailTgSelected = $('#ddv-' + index).datagrid("getRows");
        if (detailTgSelected && detailTgSelected.length > 0) {
            for (const detailLine of detailTgSelected) {
                detailLine.factoryCode = $("#factoryCode").combobox("getValue");
                detailLine.factoryName = $("#factoryCode").combobox("getText");
                detailLine.materialCode = line.materialCode;
                detailLine.materialName = line.materialName;
                detailLine.reason = $.trim($("#reason").val());
                result[result.length] = detailLine;
            }
        }
    }

    if (result.length < 1) {
        layer.msg("保存的记录为空");
        return false;
    }

    let loadIndex = layer.load(2);
    let quotaListJson = JSON.stringify(result);
    $.ajax({
        url: g.ctx + 'quotaManagement/maintain/saveOrUpdate',
        type: "POST",
        data: {"quotaListJson": quotaListJson},
        success: function (data) {
            layer.close(loadIndex);
            if (data.state) {
                parent.layer.msg('保存成功', {icon: 1, time: 2000});
                parent.frames['/quotaManagement/maintain/index'].$('#tb').datagrid('load');
                closeLayer();
                // 上传附件
                let list = data.data;
                let quotaCode = list[0].quotaCode;
                autoUploadExcel(quotaListJson, quotaCode);
            } else {
                parent.layer.msg('保存失败：' + data.msg, {icon: 2, time: 2000});
            }
        },
        error: function (data) {
            layer.close(loadIndex);
            parent.layer.alert(data.responseJSON.message)
        }
    });

}

function autoUploadExcel(quotaListJson, quotaCode) {
    // 自动上传附件
    $.ajax({
        url: g.ctx + 'quotaManagement/maintain/autoUploadExcel',
        type: "POST",
        data: {"quotaListJson": quotaListJson, "quotaCode": quotaCode},
        success: function (data) {
            if (data.state) {
                // parent.layer.msg('保存成功', {icon: 1, time: 2000});
            } else {
                parent.layer.msg('附件保存失败：' + data.msg, {icon: 2, time: 2000});
            }
        },
        error: function (data) {
            parent.layer.msg('附件保存失败：' + data.msg, {icon: 2, time: 2000});
        }
    });
}

let editIndex = undefined;
let lastEditTg = undefined;
let cantEndEdit = false;

//该方法用于关闭上一个焦点的editing状态
function endEditing(tg) {
    if (cantEndEdit) {
        return false;
    }
    if (editIndex == undefined) {
        return true
    }
    // 当前表格
    if (lastEditTg && !tg.is(lastEditTg)) {
        if (lastEditTg.datagrid('validateRow', editIndex)) {
            lastEditTg.datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        }
    } else {
        if (tg.datagrid('validateRow', editIndex)) {
            tg.datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        }
    }
    return false;
}

//点击单元格事件：
function onClickCell(index, field, value) {
    debugger
    let _thisDg = $(this);
    if (endEditing(_thisDg)) {
        if (field == "quota") {
            _thisDg.datagrid('beginEdit', index);
            let ed = _thisDg.datagrid('getEditor', {index: index, field: field});
            $(ed.target).focus();
            $(ed.target).on("blur", function (e) {
                let val = e.target.value;
                if (!/^[\d.]*$/.test(val)) {
                    _thisDg.datagrid('beginEdit', index);
                    parent.layer.msg("只能输入正数");
                    $(ed.target).focus();
                    cantEndEdit = true;
                    return false;
                } else {
                    cantEndEdit = false;
                    _thisDg.datagrid('endEdit', index);
                }
            });
            lastEditTg = _thisDg;
        }
        editIndex = index;
    }
}

//单元格失去焦点执行的方法
function onAfterEdit(index, row, changes) {
    let properties = Object.getOwnPropertyNames(changes);
    let field;
    if (properties.length > 0) {
        field = properties[0];
    }
    if (!field) {
        return false;
    }
    let _thisDg = $(this);
    if (!/^[\d.]*$/.test(changes[field])) {
        _thisDg.datagrid('beginEdit', index);
        let ed = _thisDg.datagrid('getEditor', {index: index, field: field});
        $(ed.target).focus();
        parent.layer.msg("只能输入正数");
        return false;
    }

    let updated = _thisDg.datagrid('getChanges', 'updated');
    if (updated) {
        // 同表其他行的同一个供应商的配额值要保持一致
        let rows = _thisDg.datagrid("getRows");
        for (let i = 0; i < rows.length; i++) {
            if (i != index && rows[i].supplierCode == row.supplierCode) {
                rows[i].quota = changes[field];
                _thisDg.datagrid("refreshRow", i);
            }
        }
    }
}

function look() {
    let cbox = $('#ddv-' + index).datagrid('getSelected');

    if (!cbox) {
        layer.msg("请选中一条记录");
        return;
    }

    openMainLayerWin("详情", '/quotaManagement/maintain/lookUI?id=' + cbox.id, "1000px", "80%");
}

let columns2 = [[
    /*{
      field: 'ck',
      checkbox: true
    },*/
    {
        field: 'id',
        title: 'id',
        hidden: true
    },
    {
        field: 'supplierCode',
        title: '供应商编码',
        width: '4.8%',
        align: 'left'
    }, {
        field: 'supplierName',
        title: '供应商名称',
        width: '14.8%',
        align: 'left'
    },
    {
        field: 'purchaseGroupName',
        title: '采购组',
        width: '6.8%',
        align: 'left'
    },
    {
        field: 'lastPrice',
        title: '未税单价',
        width: '5.8%',
        align: 'left'
    },
    {
        field: 'lastPriceTax',
        title: '含税单价',
        width: '5.8%',
        align: 'left'
    },
    {
        field: 'taxCode',
        title: '税码',
        width: '2.8%',
        align: 'left'
    },
    {
        field: 'taxRate',
        title: '税率',
        width: '2.8%',
        align: 'left'
    },
    {
        field: 'quota',
        title: '配额（%）',
        width: '5.8%',
        align: 'left',
        editor: 'text',
        formatter: function (data) {
            let val = (data * 100).toFixed(3) + "%";
            return "<span style='cursor: pointer; color:#1a84e9;'>"+ val +"</span>";
        }
    },
    {
        field: 'infnr',
        title: '价格信息记录编码',
        width: '5.8%',
        align: 'left'
    }
    , {
        field: 'priceEffectDate',
        title: '生效时间',
        width: '5.8%',
        align: 'left',
        formatter: function (data) {
            if (!data) {
                return '';
            }
            return DateFormatMs(data)
        }
    }, {
        field: 'priceInvalidDate',
        title: '失效时间',
        width: '7%',
        align: 'left',
        formatter: function (data) {
            if (!data)
                return '';
            return DateFormatMs(data)
        }
    }
    , {
        field: 'lastQuarterInMoney',
        title: '上季度入库金额',
        width: '7%',
        align: 'left'
    }, {
        field: 'lastQuarterOutMoney',
        title: '上季度退货金额',
        width: '5.8%',
        align: 'left'
    }, {
        field: 'moq',
        title: '最小订货量',
        width: '5.8%',
        align: 'left'
    }, {
        field: 'mpq',
        title: '最小包装量',
        width: '5.8%',
        align: 'left'
    },
    /* {
       field: 'lastQuota',
       title: '上次配额',
       width: '5.8%',
       align: 'left'
     }, */
    {
        field: 'settlementModes',
        title: '结算方式',
        width: '8%',
        align: 'left'
    }
]];

let columns1 = [[
    {
        field: 'ck',
        checkbox: true
    },
    {
        field: 'addUniqueFlag',
        hidden: true
    },
    {
        field: 'materialCode',
        title: '物料编码',
        width: '10%',
        align: 'left'
    },
    {
        field: 'materialName',
        title: '物料名称',
        width: '35%',
        align: 'left'
    },
    {
        field: 'orderUnit',
        title: '订单单位',
        width: '10%',
        align: 'left'
    },
    /*{
      field: 'historyQuota',
      title: '历史配额',
      width: '10%',
      align: 'left',
      formatter: function () {
        return '<span style = "color:#1a84e9">查看</span>';
      }
    },*/
    {
        field: 'lastQuarterInMoney',
        title: '上季度入库金额',
        width: '10%',
        align: 'left'
    },
    {
        field: 'mpq',
        title: '最小拆分数量',
        width: '6%',
        align: 'left',
        // editor: {
        //     type: 'textbox'
        // },
        formatter: function (data) {
             //return '<input type="text" onchange="queryByMaterial()" style="width: 100%;"/>';
        }
    },
    {
        field: 'effectDate',
        title: '有效期起始日',
        width: '12%',
        align: 'left',
        // editor:{
        //     type: 'datebox'
        // },
        formatter: function (data) {
            if (!data) {
                return '';
            }
             return DateFormatMs(data)
            // return `
            //           <div class="ui-input">
            //             <input class="easyui-datebox" name="effectDate" id="effectDate" editable="false"
            //               data-options="required:false,onSelect:reloadLineTable" style="width:100%; height: 22px;">
            //           </div>
            //        `;

        }
    },
    {
        field: 'invalidDate',
        title: '有效期截至日',
        width: '12%',
        align: 'left',
        // editor:{
        //     type: 'datebox'
        // },
        formatter: function (data) {
            if (!data) {
                return '';
            }
            return DateFormatMs(data)
            /*return `
                      <div class="ui-input">
                        <input class="easyui-datebox" name="invalidDate" id="invalidDate" editable="false"
                          data-options="required:false, onSelect:reloadLineTable" style="width:100%; height: 22px;">
                      </div>
                   `;*/
        }
    }
]];

// 重新加载行展开表格
function reloadLineTable(value,o) {
    console.log($(value).parent());
}

function queryByMaterial() {

}

function detail(type) {

    let cbox = $('#tb_material').datagrid('getSelected');

    if (!cbox) {
        layer.msg("请选中一条记录");
        return;
    }

    let url = '/quotaManagement/maintain/detailUI?materialCode=' + cbox.materialCode
        + '&effectiveStartTime=' + DateTimeFormatMs(cbox.effectiveStartTime)
        + '&effectiveEndTime=' + DateTimeFormatMs(cbox.effectiveEndTime)
        + '&type=' + type;

    openMainLayerWin("详情", url, "1000px", "80%");
}

/**
 * 导出excel
 */
function exportExcel() {
    layer.confirm('确定导出?', function (index) {

        window.location.href = "/quotaManagement/maintain/export?materialCode=" + $("#materialCode").val()
            + "&materialName=" + $("#materialName").val()
            + "&effectiveStartTime=" + $("#effectiveStartTime").datebox("getValue")
            + "&effectiveEndTime=" + $("#effectiveEndTime").datebox("getValue");
        layer.close(index);

    });
}

/**
 * 导入
 */
function importExcel() {
    openMainLayerWin("导入", '/quotaManagement/maintain/importUI', "1000px", "80%");
}

function scheduling() {
    let rows = $('#tb_material').datagrid("getSelections");
    if (rows.length < 1) {
        layer.msg("请选择数据");
        return;
    }
    let ids = [];

    for (let i = 0; i < rows.length; i++) {
        ids.push(rows[i].materialCode);
    }
    layer.confirm('是否确认同步？', function (index) {
        let loadIndex = layer.load(2);
        $.ajax({
            url: '/quotaManagement/maintain/schedulingData',
            method: "post",
            data: JSON.stringify(ids),
            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {
                layer.close(loadIndex);
                $('#ddv-' + index).datagrid('load');
                layer.msg("同步成功!");
                layer.close(index);
            },
            error: function (data) {
                layer.close(loadIndex);
                layer.close(index);
                layer.msg(data.responseJSON);
            }
        });
    });
}

//删除
function deleteData() {
    let $tb = $('#tb_material');
    let cbox = $tb.datagrid('getChecked');
    if (!cbox || cbox.length < 1) {
        layer.msg("请选中一条记录");
        return;
    }

    // let trSize = $tb.datagrid('getRows').length;
    // if (cbox.length == trSize) {
    //     layer.msg("不建议删除全部记录");
    //     return;
    // }

    layer.confirm('是否确认删除？', function (index) {
        for (let i = cbox.length - 1; i >= 0; i--) {
            let index = $tb.datagrid("getRowIndex", cbox[i]);
            $tb.datagrid("deleteRow", index);
        }
        layer.close(index);
    });
}

/**
 * 选择物料回调
 *
 * @param productJson 选择的物料结果
 */
function returnSelectProduct(productJson) {
    let options = $('#tb_material').datagrid("options");
    options.queryParams.factoryCode = el.factoryCode;
    options.queryParams.materialCodes = JSON.stringify(productJson);
    options.url = '/quotaManagement/maintain/generateSupplierQuotaDetail';
    $('#tb_material').datagrid("load");
}

/**
 * 物料导入
 */
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)
            }
        })
    }
}
