/**
 * 系统管理-数据字典管理首页JS
 */
'use strict';
var el = {
    searchForm: '#searchForm',
    thirdOrder: '#thirdOrder',
    orderCode: '#orderCode',
    createUserName: '#createUserName',
    afOrderCode: '#afOrderCode',
    skuName: '#skuName',
    tb: '#tb',
    id: '#id',
    noteForm: '#noteForm',
    lookDetailDialog: null,
    noteDialog: null,
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    initPageComBoBox();
    initDict("after_sale_type,after_sale_ways");
    initDictTypeDataGrid();
});

/**
 * 初始化页面下拉框
 */
function initPageComBoBox() {
    // 初始化售后类型下拉框
    $('#afterSaleType').combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=after_sale_type',
        panelHeight: 'auto',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
    // 初始化售后方式下拉框
    $('#afterSaleWays').combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=after_sale_ways',
        panelHeight: 'auto',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
}
/**
 * 初始化订单表格
 */
function initDictTypeDataGrid() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        url: '/pc/mall/myAfterSale/rest/findMyAfterSalesPage',
        height: el.bodyHeight - searchHeight,
        singleSelect: true,
        rownumbers: true,
        pagination: true,
        remoteSort:true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {quotaManageId:$(el.id).val()},
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'afOrderCode',
                    title: '售后单号',
                    width:100,
                    sortable:true
                },
                {
                    field: 'status',
                    title: '状态',
                    width: 150,
                    sortable:true,
                    exportEnum:[
                        {code:1,codeWithDesc:'售后单取消失败'},
                        {code:2,codeWithDesc:'售后申请发起成功'},
                        {code:3,codeWithDesc:'售后申请发起失败'},
                        {code:4,codeWithDesc:'售后单取消成功'},

                    ],
                    formatter: function (value) {
                        switch (Number(value)) {
                            case 1:
                                return '<span style="color: orangered;">售后单取消失败</span>';
                            case 2:
                                return '<span style="color: green;">售后申请发起成功</span>';
                            case 3:
                                return '<span style="color: #750523;">售后申请发起失败</span>';
                            case 4:
                                return '<span style="color: grey;">售后单取消成功</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'orderCode',
                    title: '订单号',
                    width: 160,
                    sortable:true
                    // formatter: function (value, row) {
                    //     return '<span onclick="lookupDicItem(' + row.id + ')" style="color: blue;cursor: pointer;" title="点击查看详情">' + value + '</span>';
                    // }
                },
                {
                    field: 'afterSalesType',
                    title: '售后类型',
                    width: 100,
                    sortable:true,
                    exportEnum:getDictList('after_sale_type'),
                    formatter: function (value) {
                        return getDicName('after_sale_type',value);
                    }

                },
                {
                    field: 'afterSalesWay',
                    title: '售后方式',
                    width: 130,
                    sortable:true,
                    exportEnum:getDictList('after_sale_ways'),
                    formatter: function (value) {
                        return getDicName('after_sale_ways',value);
                    }
                },
                {
                    field: 'createUserName',
                    title: '申请人',
                    sortable:true,
                    width: 100
                },
                {
                    field: 'applyTel',
                    title: '申请人电话',
                    sortable:true,
                    width: 120
                },
                {
                    field: 'skuName',
                    title: '商品名称',
                    sortable:true,
                    width: 120
                },
                {
                    field: 'returnQuatity',
                    title: '退货数量',
                    sortable:true,
                    width: 80
                },
                {
                    field: 'refundAmount',
                    title: '退款金额',
                    sortable:true,
                    width: 120
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    width: 120,
                    sortable:true
                },
                {
                    field: 'note',
                    title: '备注',
                    width: 200,
                    sortable:true,
                    formatter: function(value, row, index) {
                        return '<a href="#" style="color: black" title="' + value + '" class="note">' + value + '</a>';
                    }
                    // formatter: function (value, row) {
                    //     return openNoteDialog(value)
                    // }
                    // formatter: function (value, row) {
                    //
                    //     return "<a href='javascript:void(0)' onclick=\"editNote('" + row.id + "')\">" + value + "</a>";
                    // }
                },
            ]
        ],
        toolbar: [
            {
                text: '取消',
                id: 'cancel',
                iconCls: 'icon-delete',
                handler: function () {
                    cancel('');
                }
            },
            {
                text: '删除',
                hide: true,
                id: 'btn_remove',
                iconCls: 'icon-remove',
                handler: function () {
                    del();
                }
            },
            {
                text: '查看',
                hide: true,
                id: 'btn_chakan',
                iconCls: 'icon-search',
                handler: function () {
                    look('');
                }
            },
            {
                text: '导出',
                id: 'btn_export',
                iconCls: 'icon-undo',
                handler: function () {
                    var params = searchParams();
                    openExportDialog('pc/mall/myAfterSale/rest/AsExport','tb',params);
                }
            },
            {
                text: '添加/编辑备注',
                hide: true,
                id: 'btn_chakan',
                iconCls: 'icon-search',
                handler: function () {
                    editNote();
                }
            },
            // {
            //     text: '导出',
            //     hide: true,
            //     id: 'btn_export',
            //     iconCls: 'icon-import',
            //     handler: function () {
            //         openExportDialog('pc/mall/cart/rest/export','tb',{quotaManageId:$(el.id).val()});
            //     }
            // }
        ],
        onLoadSuccess: function () {
             displayButtonByUserRole('MyAfterSalesMark');
            $(el.tb).datagrid('clearSelections');
        }
    });
}



/**
 * 备注编辑
 */
function openNoteDialog(value) {

    return '<a style="color: #108ee9" onclick="editNote()">' + value + '</a>';
}

/**
 * 售后备注提交
 * @param afId 字典类型ID
 */
function editNote() {
    var cbox = $('#tb').datagrid('getSelected');

    if (cbox === null || cbox === undefined) {
        layer.msg("请选中一条记录");
        return;
    }
        // var row = $(el.tb).datagrid('getSelected');
        // var id = row.id;
        // var afId = row.orderCode;
        // var skuName = cbox.skuName;
        // var afId = cbox.afId;
        var sasiId = cbox.sasiId;
    console.log("id " + sasiId)
    var url = '/pc/mall/cart/page/note?sasiId=' + sasiId;
    el.noteDialog = openDialog('note', url, {
        title: '备注',
        width: '50%',
        height: '50%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.noteDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'提交',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['note'].submitNote(function (data) {
                        el.noteDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.noteDialog.dialog('close');
                }
            }
        ]
    });
}


// function submitNote(call) {
//     if($(el.noteForm).form('validate')){
//         // if (Number.isInteger(el.useTimes)) {
//
//         var formData = $(el.noteForm).serializeJson();
//         console.log("77777"+JSON.stringify(formData))
//
//
//         var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
//         $.ajax({
//             url: g.ctx + 'pc/mall/myAfterSale/rest/noteSave',
//             method: 'post',
//             data: formData,
//             success: function (data) {
//                 call();
//             },
//             complete: function(data) {
//                 top.layer.close(loading);
//             },
//             error: function (data) {
//                 layer.alert(JSON.parse(data.responseText).message);
//             }
//         });
//     }else{
//         layer.msg("红色框为必输项，请填写！");
//     }
// }


function del() {
    var cbox = $('#tb').datagrid('getSelected');
    if (cbox.status != "4"){
        layer.msg("只有售后取消成功的单据才可以删除");
        return;
    }
    if (cbox === null || cbox === undefined) {
        layer.msg("请选中一条记录");
        return;
    }

    var qmAuditManage = cbox.id;

    parent.layer.confirm('是否删除？', function (index) {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        var url = g.ctx + 'pc/mall/cart/rest/remove';
        $.ajax({
            url: url,
            method: "post",
            data: {id: qmAuditManage},
            success: function (data) {
                parent.layer.close(index);
                $(el.tb).datagrid('reload');
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                layer.close(index);
                layer.alert(JSON.parse(data.responseText).message);
            }
        });
    });
}
/**
 * 售后申请
 * @param afId 字典类型ID
 */
function cancel(afId) {
    if ('' === afId) {
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert('请选中一条记录进行操作', {icon: 0});
            return false;
        }

        afId = row.id;
    }
    var status = row.status;
    if (Number(status) !== 2) {
        topWin.layer.alert('只有“售后申请发起成功”状态的单据才能执行该操作, 您选择的订单(' + row.thirdOrder + ')当前状态不正确, 请检查', {icon: 0});
        return false;
    }
    topWin.layer.confirm('您确定要将选中的记录推送商城进行取消操作吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据推送中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            type: 'POST',
            url: '/pc/mall/cart/rest/cancel/mall/order',
            data: {id: row.id},
            success: function (data) {
                topWin.layer.close(loading);
                $(el.tb).datagrid('reload');
                // 6:商城订单确认成功 7:商城订单确认失败 9:商城订单确认成功但生成SRM订单失败
                switch (Number(data)) {
                    case 6:
                        topWin.layer.alert('售后取消成功', {icon: 1});
                        break;
                    case 7:
                        topWin.layer.alert('售后取消失败', {icon: 1});
                        break;
                    default:
                        topWin.layer.alert('售后取消成功', {icon: 1});
                        break;
                }
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON, {icon: 2});
            }
        });
    });
}
/**
 * 售后申请
 * @param afId 字典类型ID
 */
function look(afId) {
    if('' === afId){
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert('请选中一条记录进行操作', {icon: 0});
            return false;
        }
        var id = row.id;
        afId = row.orderCode;
    }

    var url = '/pc/mall/cart/page/applyUILook?cartId=' + afId + "&id=" + id;
    el.lookDetailDialog = openDialog('afterSaleApply', url, {
        title: '售后申请查看',
        width: '80%',
        height: '80%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.lookDetailDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.lookDetailDialog.dialog('close');
                }
            }
        ]
    });
}
/**
 * 售后申请
 * @param afId 字典类型ID
 */
function afterApply(afId) {
    if('' === afId){
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert('请选中一条记录进行操作', {icon: 0});
            return false;
        }

        afId = row.id;
    }

    var url = '/pc/mall/cart/page/applyUI?cartId=' + afId;
    el.lookDetailDialog = openDialog('afterSaleApply', url, {
        title: '售后申请',
        width: '80%',
        height: '80%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.lookDetailDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.submit,
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['afterSaleApply'].submit(function () {
                        topWin.layer.msg('数据提交成功', {icon: 1});
                        el.lookDetailDialog.dialog('close');
                        $(el.tb).datagrid('reload');
                    });
                }
            },
            {
                text: itablei8n.save,
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['afterSaleApply'].saveOrUpdate(function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        el.lookDetailDialog.dialog('close');
                        $(el.tb).datagrid('reload');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.lookDetailDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 维护字典类型条目
 *
 * @param dtId 字典类型ID
 */
function lookupDicItem(dtId) {
    if('' === dtId){
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert('请选中一条记录进行操作', {icon: 0});
            return false;
        }

        dtId = row.id;
    }

    var url = '/pc/mall/cart/page/detailListUI?cartId=' + dtId;
    el.lookDetailDialog = openDialog('lookDetail', url, {
        title: '查看订单详情',
        width: '80%',
        height: '99%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.lookDetailDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.lookDetailDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 查询
 */
function searchDictTypeData() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.orderCode = $.trim($(el.orderCode).val());
    queryParams.skuName = $.trim($(el.skuName).val());
    queryParams.afOrderCode = $.trim($(el.afOrderCode).val());
    queryParams.createUserName = $.trim($(el.createUserName).val());
    $(el.tb).datagrid('load');
}


/**
 * 重置查询
 */
function resetDictTypeSearch() {
    $(el.orderCode).val('');
    $(el.afOrderCode).val('');
    $(el.createUserName).val('');
    $(el.skuName).val('');
    searchDictTypeData();
}


/**
 * 推送商城购物车
 */
function pushCartExamine() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条记录进行操作', {icon: 0});
        return false;
    }

    //1:待推送商城购物车  2：待oa审批  3：oa审批失败 4：待生成确认订单 5：生成订单成功 6：生成订单失败
    var status = row.srmStatus;
    if (Number(status) !== 1) {
        topWin.layer.alert('您选择的订单(' + row.thirdOrder + ')不是待推送商城购物车状态, 不可推送商城购物车', {icon: 0});
        return false;
    }

    topWin.layer.confirm('您确定要将选中的记录推送商城购物车吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据推送中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            type: 'POST',
            url: '/pc/mall/shopping/rest/push/cart',
            data: {id: row.id},
            success: function (data) {
                topWin.layer.close(loading);
                if(Number(data.code) === 0){
                    topWin.layer.msg('推送成功', {icon: 1});
                    $(el.tb).datagrid('load');
                }else{
                    topWin.layer.close(loading);
                    parent.layer.alert(data.errorMsg, {icon: 2});
                    $(el.tb).datagrid('load');
                }
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON, {icon: 2});
            }
        });
    });
}


/**
 * 确认商城订单
 */
function confirmMallOrder() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条记录进行操作', {icon: 0});
        return false;
    }

    var status = row.srmStatus;
    if (Number(status) !== 5) {
        topWin.layer.alert('只有“待确认商城订单”状态的单据才能执行该操作, 您选择的订单(' + row.thirdOrder + ')当前状态不正确, 请检查', {icon: 0});
        return false;
    }

    topWin.layer.confirm('您确定要将选中的记录推送商城进行确认操作吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据推送中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            type: 'POST',
            url: '/pc/mall/cart/rest/confirm/mall/order',
            data: {id: row.id},
            success: function (data) {
                topWin.layer.close(loading);
                $(el.tb).datagrid('reload');
                // 6:商城订单确认成功 7:商城订单确认失败 9:商城订单确认成功但生成SRM订单失败
                switch (Number(data)) {
                    case 6:
                        topWin.layer.alert('商城订单确认成功', {icon: 1});
                        break;
                    case 7:
                        topWin.layer.alert('商城订单确认失败', {icon: 1});
                        break;
                    default:
                        topWin.layer.alert('确认成功', {icon: 1});
                        break;
                }
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON, {icon: 2});
            }
        });
    });
}


/**
 * 收货
 */
function confirmReceipt(){

    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条记录进行操作', {icon: 0});
        return false;
    }

    var status = row.srmStatus;
    if (Number(status) !== 6) {
        topWin.layer.alert('只有“生成订单成功”状态的单据才能执行该操作, 您选择的订单(' + row.thirdOrder + ')当前状态不正确, 请检查', {icon: 0});
        return false;
    }

    var url = '/pc/mall/cart/page/confirmReceipt?cartId=' + row.id;
    el.lookDetailDialog = openDialog('confirmReceipt', url, {
        title: '收货',
        width: '80%',
        height: '99%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.lookDetailDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'保存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['confirmReceipt'].submitReceiptNum(function (data) {
                        el.lookDetailDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.lookDetailDialog.dialog('close');
                }
            }
        ]
    });


}


function confirmExcel(){
    var accessToken = $(el.accessToken).val();
    var url = '/pc/mall/cart/page/excel/buy/confirm/page';
    el.cbcDialog = openDialog('choseBuyConfirm', url, {
        title: '添加商品',
        width: '80%',
        height: '99%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.cbcDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确认提交',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseBuyConfirm'].dataSave(function () {
                        el.cbcDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.cbcDialog.dialog('close');
                }
            }
        ]
    });

}


/**
 * 删除商城订单调用取消接口
 */
function delOrder() {
    var row = $('#tb').datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    if (row.srmStatus !='5') {
        layer.msg("只有状态为\"待确认商城订单\"的记录才能删除");
        return;
    }
    var id = row.id;
    var orderId=row.orderId;

    topWin.layer.confirm('您确定要删除选中的记录吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);
        $.ajax({
            type: 'POST',
            url: '/pc/mall/cart/rest/delOrder',
            data: {id: id,orderId:orderId},
            success: function () {
                topWin.layer.msg('删除成功', {icon: 1});
                $(el.tb).datagrid('load');
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON, {icon: 2});
            }
        });
    });
}