let quotaCode = $("#quotaCode").val();
let materialCode = $("#materialCode").val();

let el = {
    factoryCode:'#factoryCode',
    id:'#id',
    dateViewTotal: [],
    combobox: {
        factory: []
    }
};



$(function () {
    initNecessaryDatas('pc/sys/tax/rest/listAll');
    $("#factoryCode").combobox({
        url: g.ctx + 'pc/sys/factory/rest/listAll',
        editable: false,
        valueField: 'factory',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        // panelHeight: 100,
        // panelWidth: 250,
        onLoadSuccess:function (value) {
            el.factoryCode = value;
            loadGrid(value);
        }
    });
});

function loadGrid(factoryCode) {
    $('#tb_material').datagrid({
        url: '/pc/tender/quotaManage/quotaManagement/rest/edit/list',
        iconCls: 'icon-list',
        title: '配额物料列表',
        height: gridheight - 43,
        width: gridwidth,
        //singleSelect: true,
        pagination: true,
        idField: 'materialCode',
        autoHeight: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        fitColumns: false,
        remoteSort: true,
        onClickCell: onClickCell,
        view: detailview,
        columns: columns1,
        page: 1,
        pageSize: 10,
        queryParams: {
            page: 1,
            rows: 10,
            quotaCode: quotaCode,
            materialCode: materialCode||''
        },
        detailFormatter: function (index, row) {
            return '<div id="ddv-' + index + '" style="padding:5px"></div>';
        },
        // 展开行
        onExpandRow: function (index, row) {
            el.dateViewTotal.push(index);
            //console.log(row)
            $('#ddv-' + index).datagrid({
                url: '/pc/tender/quotaManage/quotaManagement/rest/supplier/list',
                //singleSelect: true,
                rownumbers: true,
                loadMsg: '数据加载中......',
                onClickCell: onClickCell,
                onAfterEdit: onAfterEdit,
                page: 1,
                pageSize: 30,
                queryParams: {
                    page: 1,
                    rows: 30,
                    quotaCode: quotaCode,
                    materialCode: row.materialCode,
                    effectDate: DateFormatMs(row.effectDate),
                    quotaManageId:$(el.id).val(),
                    // invalidDate: row.invalidDate
                },
                columns: columns2,
                onResize: function () {
                    $('#tb_material').datagrid('fixDetailRowHeight', index);
                },
                onLoadSuccess: function () {
                    setTimeout(function () {
                        $('#tb_material').datagrid('fixDetailRowHeight', index);
                    }, 0);
                    $(".datagrid-row-detail .datagrid-header-check").html("");
                }
            });
            $('#tb_material').datagrid('fixDetailRowHeight', index);
        },
        onCollapseRow: function (indexDetail, row) {
            let index = el.dateViewTotal.indexOf(indexDetail);
            el.dateViewTotal.splice(index, 1);
        },
        onLoadSuccess: function (data) {
            // 设置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);
            }

        },
        toolbar: [
            // {
            //     text: '导出',
            //     id: 'export',
            //     iconCls: 'icon-undo',
            // },
            // {
            //     text: '导出',
            //     iconCls: 'icon-import',
            //     handler: function () {
            //         openExportDialog('pc/tender/quotaManage/quotaManagement/rest/export','tb_material',{quotaManageId:$(el.id).val()});
            //     }
            //
            // }
            // , "-", {
            //     text: '删除',
            //     id: 'add',
            //     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 saveQuota(call) {
    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.quotaCode = line.quotaCode;
                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 + 'pc/tender/quotaManage/quotaManagement/rest/saveOrUpdate',
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(result),
        success: function (data) {
            layer.close(loadIndex);
            $('#tb').datagrid('load')
            call();
        },
        error: function (data) {
            layer.close(loadIndex);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });

}

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) {
    console.log(field)
    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: '10%',
        align: 'left'
    }, {
        field: 'supplierName',
        title: '供应商名称',
        width: '14.8%',
        align: 'left'
    },
    {
        field: 'purchaseGroupCode',
        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: '5%',
        align: 'left',
        formatter: function (value) {
            return getNecessaryDataName('pc/sys/tax/rest/listAll',value);
        }
    },
    {
        field: 'quota',
        title: '配额（%）',
        width: '5.8%',
        align: 'left',
        editor: 'text',
        formatter: function (data) {
            return "<span style='cursor: pointer; color:#1a84e9;'>"+ data +"</span>";
        }
    },
    {
        field: 'priceInfoCode',
        title: '价格信息记录编码',
        width: '10%',
        align: 'left'
    }
    , {
        field: 'priceEffectDate',
        title: '生效时间',
        width: '5.8%',
        align: 'left',
        formatter: function (value, row, index) {
            if (value) {
                return moment(value).format("YYYY-MM-DD");
            }
            return '';
        }
    }, {
        field: 'priceInvalidDate',
        title: '失效时间',
        width: '7%',
        align: 'left',
        formatter: function (value, row, index) {
            if (value) {
                return moment(value).format("YYYY-MM-DD");
            }
            return '';
        }
    }
    // , {
    //     field: 'lastQuarterInMoney',
    //     title: '上季度入库金额',
    //     width: '7%',
    //     align: 'left'
    // }, {
    //     field: 'lastQuarterOutMoney',
    //     title: '上季度退货金额',
    //     width: '5.8%',
    //     align: 'left'
    // }
    , {
        field: 'moq',
        title: '最小订货量',
        width: '7%',
        align: 'left'
    }, {
        field: 'mpq',
        title: '最小包装量',
        width: '7%',
        align: 'left'
    },
    /*  {
        field: 'lastQuota',
        title: '上次配额',
        width: '5.8%',
        align: 'left'
      },*/
    {
        field: 'paymentMethod',
        title: '付款条件',
        width: '8%',
        align: 'left'
    },
    {
        field: 'leadTime',
        title: '货期',
        width: '8%',
        align: 'left'
    }
]];

let columns1 = [[

    {
        field: 'materialCode',
        title: '物料编码',
        width: '20%',
        align: 'left'
    },
    {
        field: 'materialName',
        title: '物料名称',
        width: '40%',
        align: 'left'
    },
    // {
    //     field: 'unitCode',
    //     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',
    //     formatter: function () {
    //         //return '<input type="text" onchange="queryByMaterial()" style="width: 100%;"/>';
    //     }
    // },
    {
        field: 'effectDate',
        title: '有效期起始日',
        width: '18%',
        align: 'left',
        formatter: function (value, row, index) {
            if (value) {
                return moment(value).format("YYYY-MM-DD");
            }
            return '';
        }
    },
    {
        field: 'invalidDate',
        title: '有效期截至日',
        width: '19%',
        align: 'left',
        formatter: function (value, row, index) {
            if (value) {
                return moment(value).format("YYYY-MM-DD");
            }
            return '';
        }
    }
]];

// 重新加载行展开表格
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 = "/pc/tender/quotaManage/quotaManagement/rest/maintain/export?quotaCode=" + quotaCode;
        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);
    });


    // var rows = [];
    // for (let i = 0; i < el.dateViewTotal.length; i++) {
    //     let tbDom = '#ddv-' + el.dateViewTotal[i];
    //     let selectRows = $(tbDom).datagrid('getSelections');
    //     if (selectRows.length > 0) {
    //         rows.push.apply(rows, selectRows);
    //     }
    // }
    // if (rows.length === 0) {
    //     topWin.layer.msg('请选取一条记录进行操作', {icon: 0});
    //     return false;
    // }
    // 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);
    // });
}
/**
 * 关闭弹框
 */
function closeLayer() {
    parent.layer.closeAll();
}
