$(function () {
    initDict("po_item_type")
    loadGrid();
});
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() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 30, 40);


    $(el.tb).edatagrid({
        height: el.bodyHeight - searchHeight,
        method: "GET",
        url: g.ctx + 'pc/order/purchaseOrderPlan/rest/list',
        singleSelect: false,
        queryParams: {
            finishFlag: 'N',
            del_flag:0
        },
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        loadMsg: '数据加载中......',
        rownumbers: true,
        frozenColumns: [
            [
                {
                    field: 'ck', checkbox: true
                },
                {
                    field: 'rowTypeCode',
                    title: '项目类别',
                    width: 100,sortable: true,
                    exportEnum: getDictList('po_item_type'),
                    formatter: function (value) {
                        return getDicName("po_item_type", value);
                    }
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'companyCode',
                    title: '公司编码',
                    sortable: true,
                    width: 70
                },
                {
                    field: 'factoryCode',sortable: true,
                    title: '工厂编码',
                    width: 100
                },
                {
                    field: 'purchaseOrgName',
                    title: '采购组织',sortable: true,
                    width: 150
                },
                {
                    field: 'purchaseGroupCode',
                    title: '采购组编码',sortable: true,
                    width: 80
                },
                {
                    field: 'purchaseGroupName', title: '采购组',sortable: true, 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: 125,
                },
                {
                    field: 'orderCode',
                    title: 'SAP订单号',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'orderRow',
                    title: '订单行号',
                    width: 80,
                    sortable: true
                },
                {
                    field: 'materialGroupCode',
                    title: '物料组编码',
                    width: 100
                },
                {
                    field: 'materialGroupName',
                    title: '物料组',
                    width: 200
                },
                {
                    field: 'materialCode',
                    title: '物料编码',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'materialName',
                    title: '物料描述',
                    width: 150
                },
                {
                    field: 'unitName',
                    title: '采购单位',
                    width: 80
                },
                {
                    field: 'num',
                    title: '采购量',
                    width: 80
                },
                {
                    field: 'receivedNum',
                    title: 'PO接收数量',
                    width: 80
                },
                {
                    field: 'receivedQuantity',
                    title: '计划行接收数量',
                    width: 120
                },
                {
                    field: 'onlineNum',
                    title: '在途送货单',
                    width: 120
                },
                {
                    field: 'noClearNum',
                    title: '未交量',
                    width: 80
                },
                {
                    field: 'lastRequireDate',
                    title: '需求日期',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'scheduleLine',
                    title: '计划行号',
                    width: 100
                },
                {
                    field: 'scheduleDeliveryDate',
                    title: '<span style="color: lightskyblue;">计划交货日期</span>',
                    width: 120,
                    exportDateFormatter: 'date',
                    sortable: true,
                    editor: {
                        type: 'datebox',
                        options: {showSeconds: false, editable: true}
                    }
                },
                {
                    field: 'scheduleDeliveryQuantity', title: '计划交货数量',
                    width: '90', align: 'left',
                    formatter: function (value, row) {
                        if (value) {
                            return value;
                        }
                        return "";
                    }
                },
                {
                    field: 'diffDays', title: '差异天数',
                    width: '90', align: 'left',
                    formatter: function (value, row) {
                        if (row.scheduleDeliveryDate !== '' && row.lastRequireDate !== '') {
                            let diff = moment(row.lastRequireDate).diff(moment(row.scheduleDeliveryDate), 'days');
                            return diff + "天"
                        }
                        return ''
                    }
                },
                {
                    field: 'okStatus', title: '需求满足状态',
                    width: '90', align: 'left',
                    sortable: true,
                    formatter: function (value, row) {
                        if (row.scheduleDeliveryDate !== '' && row.lastRequireDate !== '') {
                            let diff = moment(row.lastRequireDate).diff(moment(row.scheduleDeliveryDate), 'days');
                            if (diff >= 0) {
                                return '<span style="color: olivedrab;">OK</span>'
                            } else {
                                return '<span style="color: orangered;">NG</span>'
                            }
                        }
                        return ''
                    }
                },


                {
                    field: 'delFlag',
                    title: '计划删除标识',
                    width: 100,
                    formatter: function (value) {
                        switch (value) {
                            case "是":
                                return '<span style="color: red;">是</span>';
                            case "否":
                                return '否';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'factoryName',
                    title: '工厂名称',
                    width: 200
                },
                {
                    field: 'state', title: '状态', align: 'left', width: 100,
                    exportEnum: [
                        {code: 2, codeWithDesc: '订单不可用'},
                        {code: 6, codeWithDesc: '待供应商确认'},
                        {code: 7, codeWithDesc: '确认完成'},
                        {code: 8, codeWithDesc: '收货完成'},
                        {code: 9, codeWithDesc: '删除'},
                        {code: 11, codeWithDesc: '供应商拒收'},
                    ],
                    formatter: function (value, row) {
                        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: 'day1',
                    title: 'day1',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'day2',
                    title: 'day2',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'day3',
                    title: 'day3',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'day4',
                    title: 'day4',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'day5',
                    title: 'day5',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },

                {
                    field: 'day6',
                    title: 'day6',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'day7',
                    title: 'day7',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'week1',
                    title: 'week1',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'week2',
                    title: 'week2',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'week3',
                    title: 'week3',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'week4',
                    title: 'week4',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'week5',
                    title: 'week5',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'week6',
                    title: 'week6',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'week7',
                    title: 'week7',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'week8',
                    title: 'week8',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'month1',
                    title: 'month1',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'month2',
                    title: 'month2',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'month3',
                    title: 'month3',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'month4',
                    title: 'month4',
                    width: 120,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }else {
                            //如果noClearNum为0，返回0
                            if (Number(row.noClearNum)===0) {
                                return 0;
                            }else {
                                return value;
                            }
                        }

                    }
                },
                {
                    field: 'look', title: '组件查看',
                    width: '90', align: 'left',
                    exportHidden: true,
                    formatter: function (index, row) {
                        if (row.componentCount > 0) {
                            return '<a href="javascript:void(0)" onclick="openComponentDialog(\'' + row.orderCode + '\',\'' + row.orderRow + '\',\'' + row.scheduleLine + '\')">组件查看</a>';
                        } else {
                            return ''
                        }

                    }
                },
                {
                    field: 'purchApplyNo',
                    title: '采购申请编号',
                    width: 100
                },
                {
                    field: 'purchApplyRow',
                    title: '采购申请行',
                    width: 100
                },
                {
                    field: 'originalRequireDate',
                    title: '原始需求日期',
                    width: 100
                },
                {
                    field: 'orderRemark',
                    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>';
                    }
                },
            ]
        ],
        toolbar: [
            {
                text: '导出',
                iconCls: 'icon-undo',
                id: 'icon_print',
                handler: function () {
                    exportExcel();
                }
            },
            {
                text: '导入',
                iconCls: 'icon-import',
                id: 'icon_import',
                handler: function () {
                    $("#fileUpload .filebox-label").click();
                }
            },
            {
                text: '提交', id: 'btn_submit', iconCls: 'icon-save', handler: function () {
                    $(el.tb).edatagrid('saveRow');
                    let rows = $(el.tb).datagrid('getChecked');
                    if (rows.length <= 0) {
                        topWin.layer.msg("请选中至少一条数据");
                        return;
                    }
                    setOperationLog("提交按钮", "交货计划行明细");
                    let a = rows.filter(a => a.scheduleDeliveryDate === '')
                    if (a.length > 0) {
                        topWin.layer.msg("请填写计划交货日期");
                        return;
                    }
                    let postRows = []
                    $.each(rows, function (i, it) {
                        postRows.push({
                            id: it.id,
                            purchaseOrder: it.orderCode,
                            lineItem: it.orderRow,
                            scheduleDeliveryDate: it.scheduleDeliveryDate,
                            noClearNum: it.noClearNum
                        })
                    })
                    let loadIndex = topWin.layer.msg('保存中...', {
                        icon: 16,
                        shade: [0.1, '#000'],
                        time: false
                    });
                    $.ajax({
                        url: g.ctx + 'pc/order/purchaseOrderPlan/rest/saveOrUpdate',
                        method: "post",
                        contentType: 'application/json',
                        data: JSON.stringify(postRows),
                        complete: function () {
                            topWin.layer.close(loadIndex);
                        },
                        success: function () {
                            topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                                $(el.tb).datagrid("reload")
                                topWin.layer.close(idx);
                                $(el.tb).datagrid('reload');
                            });
                        },
                        error: function (data) {
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                            $(el.tb).datagrid('reload');
                        }
                    });
                }
            },
            {
                text: '拆行答交', id: 'btn_replay_plan', iconCls: 'icon-back', handler: function () {
                    let rows = $(el.tb).datagrid('getSelections');
                    if (!rows || rows.length != 1) {
                        topWin.layer.msg("请选中一条订单");
                        return;
                    }
                    let row = rows[0];
                    if (row.state !== 7) {
                        topWin.layer.msg("请选择“确认完成”状态订单");
                        return;
                    }
                    setOperationLog("拆行答交按钮", "交货计划行明细");
                    openConfiDialog(2, row.orderId);
                }
            }
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole('Purchase Order Plan');//页面按钮显示‘菜单标识’
            $(el.tb).datagrid('clearSelections');
        },
        onLoadError: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}

/**
 * 导出excel
 */
function exportExcel() {
    setOperationLog("导出按钮", "交货计划行明细");
    openExportDialog('pc/order/purchaseOrderPlan/rest/export', "tb", searchParams())
}

/**
 * 答交
 */
function openConfiDialog(type, id) {
    var btn = [{
        text: '关闭', iconCls: 'icon-cancel', handler: function () {
            confirmDialog.dialog('close');
        }
    }]
    if (type === 1) {
        //供方确认
        btn.unshift({
            text: '确定', iconCls: 'icon-ok', handler: function () {
                topWin.frames['confirmDialog'].save(function () {
                    confirmDialog.dialog('close');
                    $(el.tb).datagrid("reload")
                })
            }
        })
        //供方确认
        btn.unshift({
            text: '拒收', iconCls: 'icon-undo', handler: function () {
                topWin.frames['confirmDialog'].refusal(function () {
                    confirmDialog.dialog('close');
                    $(el.tb).datagrid("reload")
                })
            }
        })
    } else {
        //答交
        btn.unshift({
            text: '提交', iconCls: 'icon-ok', handler: function () {
                topWin.frames['confirmDialog'].savePlan(function () {
                    confirmDialog.dialog('close');
                })
            }
        })
    }
    var confirmDialog = openDialog('confirmDialog', g.ctx + 'pc/order/purchaseOrder/page/supplierConfirm?id=' + id + "&type=" + type, {
        title: (type === 1 ? '供方确认' : '订单答交'),
        width: "90%",
        height: "100%",
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            confirmDialog.dialog('destroy');
        },
        buttons: btn
    });
}

function importFileUpload() {
    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/purchaseOrderPlan/rest/importPlan",
            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) {
                $("#fileInput").filebox("clear");
                topWin.layer.close(index);
                topWin.layer.alert("操作成功!", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    $(el.tb).edatagrid("reload");
                });
            }, error: function (data) {
                topWin.layer.close(index);
                $("#fileInput").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 openComponentDialog(purchaseOrder, row, scheduleLine) {
    let url = g.ctx + 'pc/order/purchaseOrderDetail/page/componentList?orderCode=' + purchaseOrder + "&row=" + row + "&planLine=" + scheduleLine;
    var componentDialog = openDialog('componentDialog', url, {
            title: "查看组件数据",
            width: '800px',
            height: '600px',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                componentDialog.dialog('destroy');
            },
            buttons: [
                {
                    text: itablei8n.close,
                    handler: function () {
                        componentDialog.dialog('close');
                    }
                }
            ]
        }
    );
}