$(function () {
    initNecessaryData("pc/sys/factory/rest/allList")
    initPageQuery();
    loadGrid();
});

let el = {
    tb: '#tb',
    searchForm: '#searchForm',
    state: '#state',
    delFlag: '#delFlag',
    closeCaseFlag: '#closeCaseFlag',
    factoryCode: '#factoryCode',
    notEq: '#notEq',
    orderCode: '#orderCode',
    createName: '#createName',
    supplier: '#supplier',
    mrp: '#mrp',
    material: '#material',
    changQu: '#changQu',
    deliveryDateStart: '#deliveryDateStart',
    deliveryDateEnd: '#deliveryDateEnd',
    createDateStart: '#createDateStart',
    createDateEnd: '#createDateEnd',
    bodyHeight: document.documentElement.clientHeight
}

function padZero(num) {
    return num < 10 ? '0' + num : num;
}

function formatDate(date) {
    var year = date.getFullYear();
    var month = padZero(date.getMonth() + 1); // 月份从0开始，所以要加1
    var day = padZero(date.getDate());
    return year + '-' + month + '-' + day;
}

function initPageQuery() {
    var currentDate = new Date();
    var oneMonthsAgo = new Date(currentDate);
    oneMonthsAgo.setMonth(currentDate.getMonth() - 1);
    currentDate.setDate(currentDate.getDate() + 1); // 在原始日期基础上加一天

    $(el.createDateStart).datebox('setValue', formatDate(oneMonthsAgo));
    $(el.createDateEnd).datebox('setValue', formatDate(currentDate));

    $("#state").combobox({
         onLoadSuccess: function () {
            $("#state").combobox('select', "2");
        }
    })

}

/**
 * 加载表格
 */
function loadGrid() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    var queryParams = {};
    queryParams.createDateStart = moment($(el.createDateStart).datebox('getValue')).format('YYYY-MM-DD');
    queryParams.createDateEnd = moment($(el.createDateEnd).datebox('getValue')).format('YYYY-MM-DD');
    queryParams.state = $('#state').val();


    $(el.tb).datagrid({
        height: el.bodyHeight - searchHeight,
        method: "GET",
        url: g.ctx + 'pc/order/deliveryOrderDetail/rest/list',
        singleSelect: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        loadMsg: '数据加载中......',
        rownumbers: true,
        queryParams:queryParams,
        frozenColumns: [[{
            field: 'ck', checkbox: true
        }]],
        onBeforeLoad: function () {
            displayButtonByUserRole('delivery_detail_view');
        },
        columns: [[{
            field: 'headerState', title: '送货单头状态', width: 90,
            formatter: function (value, row) {
                if (!value) {
                    return ""
                }
                // 1-新建 2-发布 3-完成
                if (value == 1) {
                    return "新建"
                }
                if (value == 2) {
                    return "已发货"
                }
                if (value == 3) {
                    return "已完成"
                }
            }

        }, {
            field: 'delFlag', title: '送货单行删除标识', width: 90, formatter: function (value) {
                if (value == 0) {
                    return "未删除"
                }
                if (value == 1) {
                    return "<span style=\"color: red;\">已删除</span>"
                }
            }
        },{
            field: 'isPrint', title: '打印状态', width: 65, formatter: function (value) {
                if (value) {
                    return '<span style="color: black;">是</span>';
                }
                return '<span style="color: orange;">否</span>';
            }
        }, {
            field: 'orderCode', title: '送货单号', width: 100,sortable: true
        }, {
            field: 'orderRow', title: '行号', width: 60
        }, {
            field: 'createName', title: '采购员', width: 100,sortable: true
        }, {
            field: 'deliveryDate', title: '送货日期', width: 80, formatter: function (value) {
                return DateFormatMs(value);
            },sortable: true
        }, {
            field: 'purchaseOrderCode', title: 'SAP订单号', width: 80,sortable: true
        }, {
            field: 'purchaseOrderRow', title: '订单行号', width: 80
        }, {
            field: 'materialCode', title: '物料编码', width: 80,sortable: true
        }, {
            field: 'materialName', title: '物料名称', width: 80
        }, {
            field: 'materialSpec', title: '规格', width: 160
        }, {
            field: 'noClearNum', title: '订单未清数量', width: 80
        }, {
            field: 'num', title: '送货数量', width: 80
        },
        //     {
        //     field: 'newReceiveNum', title: '收货数量', width: 80
        // }, {
        //     field: 'receiveNum', title: '入库数量', width: 80
        // }, {
        //     field: 'rejectionsNum', title: '验退数量', width: 80
        // },
            {
            field: 'supplierErpCode', title: '供应商编码', width: 70
        }, {
            field: 'supplierName', title: '供应商名称', width: 200,sortable: true
        }, {
            field: 'remark', title: '送货备注', width: 100
        },
        //     {
        //     field: 'contractNum', title: '合同号', width: 80
        // },
            {
            field: 'unitName', title: '订单单位', width: 100
        }, {
            field: 'requireDate', title: '需求交期', width: 150, formatter: function (value) {

                return DateFormatMs(value);
            }
        }, {
            field: 'planDeliveryDate', title: '预计到货日期', width: 150, formatter: function (value) {

                return DateFormatMs(value);
            }
        }, {
            field: 'consigner', title: '发货人', width: 100
        }, {
            field: 'phone', title: '发货人联系电话', width: 100
        }, {
            field: 'expressCode', title: '物流公司', width: 80
        }, {
            field: 'expressNo', title: '物流单号', width: 100
        }, {
            field: 'batchNum', title: '供应商批号', width: 100
        }, {
            field: 'createDate', title: '创建日期', width: 80, formatter: function (value) {
                return DateFormatMs(value);
            },sortable: true
        },


            {
                field: 'mrp', title: 'MRP控制者', width: 150
            }, {
                field: 'stockCode', title: '库存地点', width: '60', align: 'left',

            }, {
                field: 'defaultStock', title: '默认储位', width: '80', align: 'left',

            },

            {
                field: 'gmpPackingSpecification', title: '包装规格数', width: 100, formatter: function (value) {
                    return value.toString().replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
                }
            }, {
                field: 'packNum', title: '件数', width: 100
            }, {
                field: 'partialNum', title: '尾数', width: 100, formatter: function (value) {
                    return value.toString().replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');
                }
            }, {
                field: 'buyer', title: '使用者', width: 70
            }, {
                field: 'companyName', title: '公司', width: 100,sortable: true
            }, {
                field: 'factoryCode', title: '工厂', width: 150,
                formatter: function (value) {
                    return getNecessaryDataName("pc/sys/factory/rest/allList", value);
                }
            }]],
        toolbar: [{
            text: '导出', iconCls: 'icon-print', id: 'btn_export', handler: function () {
                exportExcel();
            }
        }, "-", {
            text: "打印", id: 'btn_print', iconCls: 'icon-print', handler: function () {
                printBarcode();
            }
        },'-',{
            text: '查看', id: 'btn_detail', iconCls: 'icon-search', handler: function () {
                let rows = $(el.tb).datagrid('getChecked');
                if (rows.length != 1) {
                    topWin.layer.msg("请选中一条记录");
                    return;
                }
                setOperationLog("查看按钮", "送货单明细查看");
                let row = rows[0];
                var url = g.ctx + "pc/order/deliveryOrder/page/createOrUpdate?type=2&id=" + row.deliveryOrderId;
                var deliveryCreateDialog = openDialog("deliveryCreateDialog", url, {
                    title: '送货单查看',
                    width: '100%',
                    height: '100%',
                    cache: false,
                    modal: true,
                    border: false,
                    draggable: true,
                    shadow: false,
                    onClose: function () {
                        deliveryCreateDialog.dialog('destroy');
                    },
                    buttons: [{
                        text: '关闭', iconCls: 'icon-cancel', handler: function () {
                            deliveryCreateDialog.dialog('close');
                        }
                    }]
                })
            }
        }, "-", {
            text: "补打", id: 'btn_reprint', iconCls: 'icon-print', handler: function () {
                rePrintBarcode();
            }
        },"-", {
            text: "删除", id: 'btn_remove', iconCls: 'icon-remove', handler: function () {
                doRemove();
            }
        },]
    });
}
function printById(ids) {
    var iframe = document.getElementById('printOrder');
    iframe.src = g.ctx + 'pc/order/deliveryOrder/page/print?ids=' + ids.join(",");
}

async function printBarcode() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length <= 0) {
        topWin.layer.alert("至少选择一条数据进行打印", {icon: 0});
        return false;
    }
    let tipMsg = [];
    let ids = [];
    for (const itm of rows) {
        ids.push(itm.deliveryOrderId);
        if (itm.delFlag === 1) {
            tipMsg.push("送货单" + itm.orderCode + "已删除");
            return true;
        }
        if (itm.headerState !== 2) {
            tipMsg.push("送货单" + itm.orderCode + "不是发货状态");
        }
        // 出货检验报告是否必填判断
        if ((itm.fileIds === "" || itm.fileIds === null)) {
            await $.ajax({
                url: g.ctx + 'pc/sys/supplierOrderFileSetting/rest/getBySupplierCode',
                method: "GET",
                data: {
                    supplierCode: itm.supplierErpCode
                },
                success: function(data) {
                    if (data && data.requiredFlag === "1") {
                        tipMsg.push("请上传出货检验报告" + "(送货单:" + itm.orderCode + ")");
                    }
                }
            });
        }
    }
    if (tipMsg.length > 0) {
        topWin.layer.msg(tipMsg.join("</br>"));
        return;
    }
    printById(ids);
}

async function rePrintBarcode() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length <= 0) {
        topWin.layer.alert("至少选择一条数据进行打印", {icon: 0});
        return false;
    }
    let tipMsg = [];
    let ids = [];
    for (const itm of rows) {
        ids.push(itm.deliveryOrderId);
        if (itm.delFlag === 1) {
            tipMsg.push("送货单" + itm.orderCode + "已删除");
            return true;
        }
        if (itm.headerState !== 2) {
            //tipMsg.push("送货单" + itm.orderCode + "不是发货状态");
        }
        // 出货检验报告是否必填判断
        if ((itm.fileIds === "" || itm.fileIds === null)) {
            await $.ajax({
                url: g.ctx + 'pc/sys/supplierOrderFileSetting/rest/getBySupplierCode',
                method: "GET",
                data: {
                    supplierCode: itm.supplierErpCode
                },
                success: function(data) {
                    if (data && data.requiredFlag === "1") {
                        tipMsg.push("请上传出货检验报告" + "(送货单:" + itm.orderCode + ")");
                    }
                }
            });
        }
    }
    if (tipMsg.length > 0) {
        topWin.layer.msg(tipMsg.join("</br>"));
        return;
    }
    printById(ids);
}
/**
 * 导出excel
 */
function exportExcel() {
    setOperationLog("导出按钮", "送货单明细查看");
    openExportDialog( "pc/order/deliveryOrderDetail/rest/export","tb", searchParams())
}

var delSubmitFlag = 0

function doRemove() {
    // var rows = $(el.tb).datagrid('getSelections');
    // if (rows.length <= 0) {
    //     topWin.layer.alert("至少选择一条数据进行打印", {icon: 0});
    //     return false;
    // }
    // let tipMsg = [];
    // let ids = [];
    // $.each(rows, function (idx, itm) {
    //     ids.push(itm.deliveryOrderId);
    //     if (itm.delFlag === 1) {
    //         tipMsg.push("送货单" + itm.orderCode + "已删除");
    //         return true;
    //     }
    //     if (itm.headerState !== 2) {
    //         //tipMsg.push("送货单" + itm.orderCode + "不是发货状态");
    //     }
    // });
    // if (tipMsg.length > 0) {
    //     topWin.layer.msg(tipMsg.join("</br>"));
    //     return;
    // }

    let rows = $('#tb').datagrid('getChecked');
    if (rows.length <= 0) {
        topWin.layer.msg("请选中一条记录");
        return;
    }
    let delRowNo = [];
    let ids = [];
    $.each(rows, function (idx, row) {
        if (row.delFlag === 1) {
            delRowNo.push(row.orderRow)
        } else {
            ids.push(row.id)
        }
    });
    if (delRowNo.length > 0) {
        topWin.layer.msg("行号:" + delRowNo.join(",") + "已经删除，无法重复删除");
        return;
    }
    if (delSubmitFlag == 1) {
        return;
    }
    topWin.layer.confirm('是否删除？', {icon: 0}, function (index) {
        $.ajax({
            url: g.ctx + "pc/order/deliveryOrderDetail/rest/remove",
            type: "POST",
            data: {ids: ids.join(",")},
            beforeSend: function () {
                delSubmitFlag = 1;
                topWin.layer.load(0);
            },
            complete: function () {
                delSubmitFlag = 0;
                topWin.layer.closeAll('loading');
            },
            success: function (data) {
                $('#tb').datagrid('options').url = g.ctx + 'pc/order/deliveryOrderDetail/rest/listForDeliverOrder?id=' + $("#id").val();
                $('#tb').datagrid('load');
                topWin.layer.msg("删除成功");
                topWin.layer.close(index);
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message)
            }
        })
    })

}