var defaultColumns = []
$(function () {
    initDict("po_item_type")
    defaultColumns = [{
        field: 'rowTypeCode',
        title: '项目类别',
        width: 100,
        sortable: true,
        exportEnum: getDictList('po_item_type'),
        formatter: function (value) {
            return getDicName("po_item_type", value);
        }
    },
        {
            field: 'companyCode',
            title: '公司编码',
            sortable: true,
            width: 70
        },
        {
            field: 'factoryCode',
            title: '工厂编码',
            width: 100
        },
        {
            field: 'purchaseOrgName',
            title: '采购组织', sortable: true,
            width: 150
        },
        {
            field: 'purchaseGroupCode',
            title: '采购组编码', sortable: true,
            width: 80
        },
        {
            field: 'purchaseGroupName', title: '采购组', width: 60
        },
        {
            field: 'orderTypeCode',
            title: '订单类型', sortable: true,
            width: 70
        },
        {
            field: 'supplierErpCode',
            title: '供应商编码',
            width: 80,
            sortable: true
        },
        {
            field: 'supplierName',
            title: '供应商名称',
            sortable: true,
            width: 200
        },
        {
            field: 'createTime',
            title: '创建时间',
            width: 80,
            sortable: true,
            formatter: function (value) {
                return DateFormatMs(value);
            }
        },
        {
            field: 'webre',
            title: '基于收货的发票校验',
            width: 150
        },

        {
            field: 'orderCode',
            title: 'SAP订单号',
            width: 80,
            sortable: true
        },
        {
            field: 'orderRow',
            title: '订单行号',
            width: 80,
            sortable: true
        },
        {
            field: 'middleClass', title: '物料中类',
            width: '90', align: 'left'
        },
        {
            field: 'materialGroupCode',
            title: '物料组编码',
            width: 100
        },
        {
            field: 'materialGroupName',
            title: '物料组',
            width: 200
        },
        {
            field: 'materialCode',
            title: '物料编码',
            width: 100,
            sortable: true
        },
        {
            field: 'materialName',
            title: '物料描述',
            width: 150
        },
        {
            field: 'companyName',
            title: '公司',
            width: 200
        },
        {
            field: 'unitName',
            title: '采购单位',
            width: 80
        },
        {
            field: 'num',
            title: '下单数量',
            width: 80
        },
        {
            field: 'receivedNum', title: '接收数量',
            width: '100', align: 'left',
        },
        {
            field: 'noClearNum',
            title: '未清数量',
            width: 80
        },
        {
            field: 'onlineNum',
            title: '在途送货单',
            width: 80
        },
        {
            field: 'delFlag',
            title: '删除标识',
            width: 80,
            exportEnum: [
                {code: 0, codeWithDesc: '未删除'},
                {code: 1, codeWithDesc: '已删除'}
            ],
            formatter: function (value) {
                if (value == 0) {
                    return "未删除"
                }
                if (value == 1) {
                    return "<span style=\"color: red;\">已删除</span>"
                }
            }
        },
        {
            field: 'requireDate',
            title: '需求日期',
            width: 100,
            sortable: true
        },
        {
            field: 'replayRequireDate',
            title: '回复交期',
            width: 80,
            sortable: true,
            formatter: function (value) {
                if (!value) {
                    return "";
                }
                return DateFormatMs(value);
            }
        },
        // {
        //     field: 'replayNum',
        //     title: '回复数量',
        //     width: 80
        // },
        {
            field: 'differenceDays',
            title: '差异天数',
            width: 80,
            formatter: function (value, row) {
                if (row.requireDate !== '' && row.replayRequireDate !== '') {
                    let diff = moment(row.requireDate).diff(moment(row.replayRequireDate), 'days');
                    return diff + "天"
                }
                return ''
            }
        },
        {
            field: 'requirementStatus',
            title: '需求满足状态',
            width: 100,
            formatter: function (value, row) {
                if (row.scheduleDeliveryDate !== '' && row.lastRequireDate !== '') {
                    let diff = moment(row.requireDate).diff(moment(row.replayRequireDate), 'days');
                    if (diff >= 0) {
                        return '<span style="color: olivedrab;">OK</span>'
                    } else {
                        return '<span style="color: orangered;">NG</span>'
                    }
                }
                return '';
            }
        },
        {
            field: 'currencyCode',
            title: '币种',
            width: 80
        },
        {
            field: 'price',
            title: '单价',
            width: 80
        },
        {
            field: 'netPrice',
            title: '净价',
            width: 80
        },
        {
            field: 'taxCode',
            title: '税码',
            width: 100
        },
        {
            field: 'taxName',
            title: '税率',
            width: 150
        },
        {
            field: 'taxAmount',
            title: '行总金额',
            width: 100
        },
        {
            field: 'paymentMethod',
            title: '付款条款编码',
            width: 150
        },
        {
            field: 'paymentMethodName',
            title: '付款条款名称',
            width: 150
        },
        {
            field: 'supplierName1',
            title: '物流商',
            width: 120
        },
        {
            field: 'supplierName2',
            title: '关税报关公司',
            width: 120
        },
        {
            field: 'tariff',
            title: '关税率(%)',
            width: 70
        },
        {
            field: 'createName',
            title: '创建人',
            width: 80
        },
        {
            field: 'state',
            title: '订单状态',
            width: 100,
            exportEnum: [
                {code: 2, codeWithDesc: '订单不可用'},
                {code: 6, codeWithDesc: '待供应商确认'},
                {code: 7, codeWithDesc: '确认完成'},
                {code: 8, codeWithDesc: '收货完成'},
                {code: 9, codeWithDesc: '删除'},
                {code: 11, codeWithDesc: '供应商拒收'},
            ],
            formatter: function (value) {
                if (!value) {
                    return ""
                }
                if (value === 2) {
                    return "<span style='color:red;' > 订单不可用 </span>"
                }
                if (value === 6) {
                    return "<span style='color:saddlebrown;' > 待供应商确认 </span>"
                }
                if (value === 7) {
                    return "<span style='color:royalblue;' > 确认完成 </span>"
                }
                if (value === 8) {
                    return "<span style='color:green;' > 收货完成 </span>"
                }
                if (value === 9) {
                    return "删除"
                }
                if (value === 11) {
                    return "<span style='color:orangered;' >供应商拒收</span>"
                }
            }
        },
        {
            field: 'originalRequireDate',
            title: '原始需求日期',
            width: 100
        },
        {
            field: 'orderHeadRemark',
            title: '单头备注',
            width: 145,
            formatter: function (value) {
                if (!value) {
                    return '';
                }
                return '<span title="' + value + '">' + value + '</span>';
            }
        },
        {
            field: 'remark',
            title: '明细备注',
            width: 145,
            formatter: function (value) {
                if (!value) {
                    return '';
                }
                return '<span title="' + value + '">' + value + '</span>';
            }
        },
        {
            field: 'warningFlag',
            title: '告警',
            width: 80,
            formatter: function (value) {
                if (value == '1') {
                    return "<span style='color: red'>是</span>"
                } else {
                    return "<span>否</span>"
                }
            }
        },
        {
            field: 'companyName',
            title: '公司',
            width: 70
        },
        {
            field: 'factoryName',
            title: '工厂名称',
            width: 100
        },
        {
            field: 'stockCode',
            title: '库存地点',
            width: 80
        },
        {
            field: 'defaultStock',
            title: '默认储位',
            width: 80
        },
        {
            field: 'returnFlag',
            title: '是否退货',
            width: 100,
            formatter: function (value) {
                if (value === 'X') {
                    return "是"
                } else {
                    return "否"
                }
            }
        },
        {
            field: 'finishFlag',
            title: '是否交货完成',
            width: 100,
            formatter: function (value) {
                if (value === 'N') {
                    return "否"
                }
                if (value === 'Y') {
                    return "是"
                }
            }
        },
        {
            field: 'isFirst',
            title: '是否期初订单',
            width: 110,
            formatter: function (value) {
                if (value == '1') {
                    return "是"
                } else {
                    return "否"
                }
            }
        },
        {
            field: 'assetNo',
            title: '资产卡片号',
            width: 200
        }]
    let column = getRemoteColumnSort(columnSortCodeEnum.PURCHASE_ORDER_DETAIL, defaultColumns);
    // 加载表格
    loadGrid(column);
});
var submitFlag = 0;
let el = {
    tb: '#tb',
    searchForm: '#searchForm',
    finishJaoHuo01: '#finishJaoHuo01',
    finishJaoHuo: '#finishJaoHuo',
    bodyHeight: document.documentElement.clientHeight
}

function searchInfo() {
    var params = {};
    $.each($("#searchForm").serializeArray(), function (index, item) {
        if (params[item.name] != undefined && params[item.name] != '') {
            params[item.name] = params[item.name] + ',' + item.value;
        } else {
            params[item.name] = item.value;
        }
    });
    $('#tb').datagrid('options').queryParams = params;
    $('#tb').datagrid('load');
}

/**
 * 加载表格
 */
function loadGrid(colums) {
    debugger;
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    $("#statusStr").combobox("setValues", ['6', '7']);
    $(el.tb).edatagrid({
        height: el.bodyHeight - searchHeight,
        method: "GET",
        url: g.ctx + 'pc/order/purchaseOrderDetail/rest/order/details',
        singleSelect: false,
        queryParams: {
            statusStr: '6,7',
            finishJaoHuo: 'N',
            delFlag: '0'
        },
        pagination: true,
        autoSave: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        loadMsg: '数据加载中......',
        rownumbers: true,
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                }
            ]
        ],
        columns: [
            colums
        ],
        toolbar: [
            {
                text: '导出',
                iconCls: 'icon-print',
                id: 'icon_print',
                handler: function () {
                    exportExcel();
                }
            },
            {
                text: '导入',
                iconCls: 'icon-import',
                id: 'icon_import1',
                handler: function () {
                    $("#fileUpload1 .filebox-label").click();
                }
            },
            {
                text: ' 计划导入',
                iconCls: 'icon-import',
                id: 'icon_import',
                handler: function () {
                    $("#fileUpload .filebox-label").click();
                }
            },
            {
                text: ' 计划修改',
                iconCls: 'icon-import',
                id: 'icon_mark_update',
                handler: function () {
                    $(el.tb).edatagrid('saveRow');
                    var rows = $(el.tb).datagrid('getChecked');
                    if (rows.length <= 0) {
                        topWin.layer.msg("请选择需要修改的数据");
                        return;
                    }
                    var tipMsg = [];
                    $.each(rows, function (idx, itm) {
                        // if (!itm.markType) {
                        //     tipMsg.push("第" + (idx + 1) + "条数据，不是计划提货/备货");
                        // }
                        if (!itm.markType) {
                            tipMsg.push("请确保修改的订单明细已经导入计划,再修改!");
                        }
                        if (itm.state != 6 && itm.state != 7) {
                            tipMsg.push("第" + (idx + 1) + "条数据，订单状态不是待供应商确认/确认完成");
                        }
                    })
                    if (tipMsg.length > 0) {
                        topWin.layer.alert(tipMsg.join("<br/>"));
                        return;
                    }
                    if (submitFlag == 1) {
                        return;
                    }
                    var formArray = [];
                    $.each(rows, function (idx, itm) {
                        formArray.push({
                            id: itm.id,
                            markDate: itm.markDate,
                            markType: itm.markType,
                            markCount: itm.markCount
                        })
                    });
                    submitFlag = 1;
                    $.ajax({
                        type: "POST", //请求方式
                        contentType: "application/json",
                        data: JSON.stringify(formArray),
                        url: g.ctx + "pc/order/purchaseOrderMark/rest/updateBatch", //请求路径
                        success: function (data) {
                            submitFlag = 0;
                            topWin.layer.alert("修改成功", function (index) {
                                topWin.layer.close(index);
                                $(el.tb).datagrid('reload');
                            })
                        },
                        error: function (data) {
                            submitFlag = 0;
                            topWin.layer.alert(data.responseJSON.message);
                            $(el.tb).datagrid('reload');
                        }
                    });
                }
            },
            {
                text: ' 计划批量修改',
                iconCls: 'icon-import',
                id: 'icon_mark_batch_update',
                handler: function () {
                    var rows = $(el.tb).datagrid('getChecked');
                    if (rows.length <= 0) {
                        topWin.layer.msg("请选择需要修改的数据");
                        return;
                    }
                    var tipMsg = [];
                    var ids = [];
                    $.each(rows, function (idx, itm) {
                        // if (!itm.markType) {
                        //     tipMsg.push("第" + (idx + 1) + "条数据，不是计划提货/备货");
                        // } else {
                        //     ids.push(itm.id);
                        // }

                        ids.push(itm.id);
                    })
                    if (tipMsg.length > 0) {
                        topWin.layer.alert(tipMsg.join("<br/>"));
                        return;
                    }
                    var upateMarkDialog = openDialog("upateMarkDialog", g.ctx + "pc/order/purchaseOrderMark/page/update?ids=" + ids.join(","), {
                        title: '计划批量修改',
                        width: 400,
                        height: '500',
                        cache: false,
                        modal: true,
                        border: false,
                        draggable: false,
                        shadow: false,
                        onClose: function () {
                            upateMarkDialog.dialog('destroy');
                        },
                        buttons: [{
                            text: '确定',
                            handler: function () {
                                topWin.frames['upateMarkDialog'].page.save(() => {
                                    upateMarkDialog.dialog('close');
                                    $(el.tb).datagrid('reload');
                                });

                            }
                        }, {
                            text: '关闭',
                            handler: function () {
                                upateMarkDialog.dialog('close');
                            }
                        }]
                    });
                }
            },
            {
                text: '列设置',
                iconCls: 'icon-anchor',
                id: 'btn_column_sort',
                handler: function () {
                    console.log(el.defaultColumns)
                    openSortDialog({
                        //唯一编码
                        code: columnSortCodeEnum.PURCHASE_ORDER_DETAIL,
                        //初始列（每次新增或删除列需要手动删除sys_column_sort表中对应code数据）
                        columns: el.defaultColumns,
                        callBack: function (newColumns) {
                            //需要隐藏
                            loadGrid(newColumns)
                        },
                    });
                }
            }
        ], onBeforeLoad: function () {
            displayButtonByUserRole('order_detail_report');//页面按钮显示‘菜单标识’
        },
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');
        }
    });
}

/**
 * 导出excel
 */
function exportExcel() {
    setOperationLog("导出按钮", "订单明细查看");
    openExportDialog('pc/order/purchaseOrderDetail/rest/export', "tb", searchParams())
}

function importFileUpload() {
    var filebox = $("#fileInput1").filebox("files");
    if (filebox.length == 1) {
        var formData = new FormData();
        formData.append("file", filebox[0]);
        var index = topWin.layer.msg('0%', {icon: 16, time: 0, shade: [0.8, '#393D49']});
        $.ajax({
            url: g.ctx + "pc/order/purchaseOrderMark/rest/import/mark1",
            data: formData,
            type: 'post',
            contentType: false,
            processData: false,
            xhr: function () {
                var xhr = new XMLHttpRequest();
                xhr.upload.addEventListener('progress', function (e) {
                    var progressRate = ((e.loaded / e.total) * 100).toFixed(0) + '%';
                    topWin.layer.close(index);
                    index = topWin.layer.msg(progressRate, {
                        icon: 16,
                        time: 0,
                        shade: [0.8, '#393D49']
                    });
                });
                return xhr;
            },
            success: function (d) {
                $("#fileInput1").filebox("clear");
                topWin.layer.close(index);
                topWin.layer.msg("操作成功!");
                $(el.tb).edatagrid("reload");

            }, error: function (data) {
                topWin.layer.close(index);
                $("#fileInput1").filebox("clear");
                var idx = topWin.layer.alert(data.responseJSON.message.replace("com.sc.toa.sys.exception.DaoException:", ""), {
                    icon: 2,
                    closeBtn: 0,
                    yes: function () {
                        topWin.layer.close(idx);
                    }
                });
            }
        })
    }
}

function markFileUpload() {
    var filebox = $("#fileInput").filebox("files");
    if (filebox.length == 1) {
        var formData = new FormData();
        formData.append("file", filebox[0]);
        var index = topWin.layer.msg('0%', {icon: 16, time: 0, shade: [0.8, '#393D49']});
        $.ajax({

            url: g.ctx + "pc/order//purchaseOrderMark/rest/import/mark/0",
            data: formData,
            type: 'post',
            contentType: false,
            processData: false,
            xhr: function () {
                var xhr = new XMLHttpRequest();
                xhr.upload.addEventListener('progress', function (e) {
                    var progressRate = ((e.loaded / e.total) * 100).toFixed(0) + '%';
                    topWin.layer.close(index);
                    index = topWin.layer.msg(progressRate, {
                        icon: 16,
                        time: 0,
                        shade: [0.8, '#393D49']
                    });
                });
                return xhr;
            },
            success: function (d) {
                if (d.length > 0) {
                    topWin.layer.close(index);
                    //有数量不满足，需要提示是否继续
                    let msg = d.join("<br/>")
                    topWin.layer.confirm("发料料号:" + msg + '<br/>是否继续？', function (index1) {
                        $.ajax({
                            url: g.ctx + "pc/order//purchaseOrderMark/rest/import/mark/1",
                            data: formData,
                            type: 'post',
                            contentType: false,
                            processData: false,
                            success: function () {
                                $("#fileInput").filebox("clear");
                                topWin.layer.close(index1);
                                topWin.layer.msg("操作成功!");
                                $(el.tb).edatagrid("reload");
                            }
                        });
                    }, function (index1) {
                        topWin.layer.close(index1);
                        $("#fileInput").filebox("clear");
                    });
                } else {
                    //
                    topWin.layer.close(index);
                    $.ajax({
                        url: g.ctx + "purchase/order/mark/rest/import/mark/1",
                        data: formData,
                        type: 'post',
                        contentType: false,
                        processData: false,
                        success: function () {
                            $("#fileInput").filebox("clear");
                            topWin.layer.msg("操作成功!");
                            $(el.tb).edatagrid("reload");
                        }, error: function () {
                            $("#fileInput").filebox("clear");
                        }
                    });
                }
            },
            error: function (data) {
                topWin.layer.close(index);
                $("#fileInput").filebox("clear");
                var idx = topWin.layer.alert(data.responseJSON.message, {
                    icon: 2,
                    closeBtn: 0,
                    yes: function () {
                        topWin.layer.close(idx);
                    }
                });
            }
        })
    }
}