let el = {
    tb: '#tb',
    itemName: '#itemName',
    searchForm: '#searchForm',
    bodyHeight: document.documentElement.clientHeight,
    supplierQuery: "#supplierQuery",
    purchaserCode: "#purchaserCode",
    formDialog: null,
    returnOrderNo: "#returnOrderNo",
    documentType:"#documentType",
    deliveryStatus:"#deliveryStatus"
};

function initDataGrid() {
    let searchHeight = $(el.searchForm).outerHeight();
    let pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    $(el.tb).edatagrid({
        url: g.ctx + 'pc/contract/returnOrder/rest/list',
        method: "GET",
        queryParams: {page: 1, rows: 10, deleteFlag: '0'},
        singleSelect: true,
        loadMsg: '数据远程载入中,请等待...',
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        checkbox: true,
        height: el.bodyHeight - searchHeight,
        frozenColumns: [
            [
                {
                    field: 'ck', checkbox: true
                }, {
                field: 'deliveryStatus', title: '单据状态', align: 'left', width: 100, formatter: function (value, row) {
                    if (!value) {
                        return ""
                    }
                    if (row.deleteFlag === 1) {
                        return "<span style='color: red;' >已删除</span>"
                    }
                    if (value === 4) {
                        return "<span style='color: yellowgreen;' >创建退货单</span>"
                    }
                    if (value === 5) {
                        return "<span style='color: seagreen;' >确认退货</span>"
                    }
                }
            }
            ]
        ],
        columns: [[ {
            field: 'returnOrderNo', title: '退货单号', width: 130,
            sortable: true
        }, {
            field: 'documentType', title: '单据类型', width: 120,
            sortable: true, formatter: function (value, row) {
        if (!value) {
            return ""
        }
        if (value === "01") {
            return "<span style='color: yellowgreen;' >送货</span>"
        }
        if (value === "02") {
            return "退货"
        }
    }
        },
            {field: 'purchaser', title: '购货方', width: 230,
                sortable: true},
            {
                 field: 'supplier', title: '供应商', width: 200,
                sortable: true
            }, {
                field: 'receiver', title: '退货人', width: 100, sortable: true
            }, {
                field: 'returnOrderDate', title: '退货日期', width: 150,
                sortable: true
            },  {
                field: 'purchaseGroup', title: '采购组', width: 120, formatter: function (value) {
                    return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll',value);
                },
                sortable: true
            },
            {
                field: 'createTime', title: '创建时间', width: 150,
                sortable: true
            },
            {
                field: 'attachmentFiles', title: '退货单附件', width: 150, align: 'left', formatter: function (value, row) {
                    if (value !== "") {
                        return "<a href='javascript:void(0)' onclick=\"viewAttachmentFileDetail('" + row.id + "', '" + row.returnOrderNo +"')\">" + "点击查看(已上传)" + "</a>";
                    } else {
                        return "<a style='color:red;' href='javascript:void(0)' onclick=\"viewAttachmentFileDetail('" + row.id + "', '" + row.returnOrderNo +"')\">" + "点击上传(未上传)" + "</a>";
                    }
                }
            }
        ]],
         toolbar: [
             {
             text: '查看', id: 'btn_return_order_detail', iconCls: 'icon-search', handler: function () {
               debugger;
                 let rows = $('#tb').datagrid('getChecked');
                 if (rows.length != 1) {
                     topWin.layer.msg("请选中一条记录");
                     return;
                 }
                 let row = rows[0];
                 var url = g.ctx + "pc/contract/returnOrder/page/createOrUpdate?type=2&id=" + row.id;
                 var contractReturnOrderCreateDialog = openDialog("contractReturnOrderCreateDialog", url, {
                     title: '退货单查看',
                     width: '100%',
                     height: '100%',
                     cache: false,
                     modal: true,
                     border: false,
                     draggable: true,
                     shadow: false,
                     onClose: function () {
                         contractReturnOrderCreateDialog.dialog('destroy');
                     },
                     buttons: [{
                         text: '关闭', iconCls: 'icon-cancel', handler: function () {
                             contractReturnOrderCreateDialog.dialog('close');
                         }
                     }]
                 })
             }
         }, "-",
             {
            text: '编辑', id: 'btn_return_order_edit', iconCls: 'icon-edit', handler: function () {
                let rows = $('#tb').datagrid('getChecked');
                if (rows.length != 1) {
                    topWin.layer.msg("请选中一条记录");
                    return;
                }
                let row = rows[0];
                if (row.deleteFlag === 1) {
                    topWin.layer.msg("此单已删除");
                    return;
                }
                if (row.deliveryStatus !== 4) {
                    topWin.layer.msg("只有创建退货单状态可以修改");
                    return;
                }
                var url = g.ctx + "pc/contract/returnOrder/page/edit?id=" + row.id;
                var returnOrderEditDialog = openDialog("returnOrderEditDialog", url, {
                    title: '退货单修改',
                    width: '100%',
                    height: '100%',
                    cache: false,
                    modal: true,
                    border: false,
                    draggable: true,
                    shadow: false,
                    onClose: function () {
                        returnOrderEditDialog.dialog('destroy');
                    },
                    buttons: [{
                        text: '提交', iconCls: 'icon-save', handler: function () {
                            topWin.frames['returnOrderEditDialog'].submit(function () {
                                topWin.layer.msg('修改成功', {icon: 1});
                                returnOrderEditDialog.dialog('close');
                                $(el.tb).datagrid('reload');
                                $(el.tb).datagrid('clearChecked');
                            }, 1);
                        }
                    }, {
                        text: '关闭', iconCls: 'icon-cancel', handler: function () {
                            returnOrderEditDialog.dialog('close');
                        }
                    }]
                })
            }
        }, "-", {
            text: "确认退货", id: 'btn_return_order_booking', iconCls: 'icon-book-add', handler: function () {
                let rows = $('#tb').datagrid('getChecked');
                if (rows.length <= 0) {
                    topWin.layer.msg("请选中至少一条记录");
                    return;
                }
                     //获取id
                     var item = rows[0];
                     if (item.deleteFlag === 1) {
                         topWin.layer.msg("此单已删除");
                         return;
                     }
                     if (item.deliveryStatus !== 4) {
                         topWin.layer.msg("只有创建退货单状态可以确认退货");
                         return;
                     }
                     let msg = '您确定要将选中的记录进行确认退货吗';
                     topWin.layer.confirm(msg, {icon: 3}, function (index) {
                         topWin.layer.close(index);
                         var loading = topWin.layer.msg('数据推送中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
                         $.ajax({
                             type: 'POST',
                             url: g.ctx + 'pc/contract/returnOrder/rest/confirmReceipt',
                             data: {
                                 id: item.id,
                             },
                             success: function () {
                                 topWin.layer.close(loading);
                                 topWin.layer.msg('数据退货成功', {icon: 1});
                                 $(el.tb).datagrid('reload');
                             },
                             error: function (data) {
                                 parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                             }
                         });
                     });
            }
        }, "-", {
            text: "删除", id: 'btn_return_order_delete', iconCls: 'icon-print', handler: function () {
                     deleteContractDelivery();
            }}
        ],
        onBeforeLoad: function () {
            displayButtonByUserRole('return.order.list');
        },
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');
        }
    });
}
function deleteContractDelivery() {
    let rows = $('#tb').datagrid('getChecked');
    if (rows.length <= 0) {
        topWin.layer.msg("请选中至少一条记录");
        return;
    }

    var item = rows[0];
    if(item.deliveryStatus != 4){
        topWin.layer.msg("只有创建退货单状态才允许删除");
        return;
    }
    if (item.deleteFlag === 1) {
        topWin.layer.msg("此单已删除");
        return;
    }
    let msg = '您确定要将选中的记录删除吗';
    topWin.layer.confirm(msg, {icon: 3}, function (index) {
        topWin.layer.close(index);
        var loading = topWin.layer.msg('数据推送中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            type: 'POST',
            url: g.ctx + 'pc/contract/returnOrder/rest/retuenOrderRemove',
            data: {
                id: item.id,
            },
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg('退货单删除成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}

function viewAttachmentFileDetail(businessId, businessCode) {
    const businessTypeCode = "contract_order_return";
    let url = g.ctx + "pc/sys/businessAttachment/businessAttachmentDetail?businessId="
        + businessId + "&businessCode=" + businessCode + "&businessTypeCode=" + businessTypeCode;
    const buttons = [{
        text: itablei8n.close, handler: function () {
            returnAttachmentFileDetailDialog.dialog('close');
        }
    }]
    returnAttachmentFileDetailDialog = openDialog("returnAttachmentFileDetailDialog", url, {
        title: '退货单附件',
        width: '800px',
        height: '500px',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        buttons: buttons,
        onClose: function () {
            returnAttachmentFileDetailDialog.dialog('destroy');
        }, buttons: [{
            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                returnAttachmentFileDetailDialog.dialog('close');
            }
        }]

    })
}

$(function () {
    initDict("delivery_type")
    initNecessaryData("pc/sys/factory/rest/allList")
    initNecessaryData("pc/sys/purchaseGroup/rest/listAll");
    // 加载表格
    initDataGrid();
});