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


/**
 * 文档就绪
 */
$(function () {
    initCombo()
    initDictTypeDataGrid();
});

function initCombo() {
    $("#srmStatus").combobox({
        editable: false,
        panelHeight: 'auto',
        valueField: 'value',
        textField: 'label',
        value:'',
        data: [
            {value: '', label: '全部'},
            {value: 1, label: '报价完成'},
            {value: 2, label: '订单-7天无理由取消'},
            {value: 3, label: '订单-无法发货取消'},
            {value: 5, label: '待确认商城订单'},
            {value: 6, label: '生成订单成功'},
            {value: 7, label: '生成订单失败'},
            {value: 8, label: '7天未确认自动取消'},
            {value: 9, label: '电商因为自身原因无法发货而取消'},
        ],
        // multiple: true,
    });
    $("#receiptStatus").combobox({
        editable: false,
        panelHeight: 'auto',
        valueField: 'value',
        textField: 'label',
        value:'',
        data: [
            {value: '', label: '全部'},
            {value: 1, label: '已收货'},
            {value: 2, label: '部分收货'},
            {value: 0, label: '未收货'},
        ],
        // multiple: true,
    });
}
/**
 * 初始化订单表格
 */
function initDictTypeDataGrid() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        url: '/pc/mall/cart/rest/findInfoByCartPage',
        height: el.bodyHeight - searchHeight,
        singleSelect: true,
        rownumbers: true,
        pagination: true,
        remoteSort:true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {quotaManageId:$(el.id).val()},
        // frozenColumns: [
        //     [
        //
        //     ]
        // ],
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'srmStatus',
                    title: '状态',
                    width: 100,
                    sortable:true,
                    exportEnum:[
                        {code:1,codeWithDesc:'待推送商城购物车'},
                        {code:2,codeWithDesc:'订单-7天无理由取消'},
                        {code:3,codeWithDesc:'订单-无法发货取消'},
                        {code:5,codeWithDesc:'待确认商城订单'},
                        {code:6,codeWithDesc:'生成订单成功'},
                        {code:7,codeWithDesc:'生成订单失败'},
                        {code:8,codeWithDesc:'7天未确认自动取消'},
                        {code:9,codeWithDesc:'电商因为自身原因无法发货而取消'},
                    ],
                    formatter: function (value) {
                        switch (Number(value)) {
                            case 1:
                                return '<span style="color: orange;">待推送商城购物车</span>';
                            case 2:
                                return '<span style="color: #750523;">订单-7天无理由取消</span>';
                            case 3:
                                return '<span style="color: #750523;">订单-无法发货取消</span>';
                            case 5:
                                return '<span style="color: orange;">待确认商城订单</span>';
                            case 6:
                                return '<span style="color: green;">生成订单成功</span>';
                            case 7:
                                return '<span style="color: red;">生成订单失败</span>';
                            case 8:
                                return '<span style="color: red;">7天未确认自动取消</span>';
                            case 9:
                                return '<span style="color: red;">电商因为自身原因无法发货而取消</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'deliveryStatus',
                    title: '发货状态',
                    width: 90,
                    exportEnum:[
                        {code:1,codeWithDesc:'已发货'},
                        {code:2,codeWithDesc:'签收'},
                        {code:3,codeWithDesc:'拒收'},
                        {code:0,codeWithDesc:'待发货'},
                    ],
                    formatter: function (value, row) {
                        //商城订单发货状态：发货状态（0-待发货，1-已发货，2-签收，3-拒收）
                        switch (Number(value)) {
                            case 0:
                                return '<span style="color: #050300;">待发货</span>';
                            case 1:
                                return '<span style="color: #3d49d5;">已发货</span>';
                            case 2:
                                return '<span style="color: #49b003;">签收</span>';
                            case 3:
                                return '<span style="color: red;">拒收</span>';
                            default:
                                return '--';
                        }
                    }
                },
                {
                    field: 'thirdOrder',
                    title: '订单号',
                    width: 160,
                    sortable:true,
                    formatter: function (value, row) {
                        return '<span onclick="lookupDicItem(' + row.id + ')" style="color: blue;cursor: pointer;" title="点击查看详情">' + value + '</span>';
                    }
                },
                {
                    field: 'storeName',
                    title: '商城来源',
                    sortable:true,
                    width: 70
                },
                {
                    field: 'orderId',
                    title: '商城返回订单号',
                    width: 180,
                    sortable:true
                },
                {
                    field: 'prCode',
                    title: '采购申请单号',
                    width: 180,
                    sortable:true
                },
                {
                    field: 'purchaseOrderNumber',
                    title: 'OA流程单号',
                    width: 180,
                    sortable:true
                },
                {
                    field: 'requireName',
                    title: '请购人',
                    width: 180,
                    sortable:true
                },
                {
                    field: 'teamName',
                    title: '请购部门',
                    width: 180,
                    sortable:true
                },
                {
                    field: 'price',
                    title: '请购单价',
                    width: 180,
                    sortable:true
                },
                // {
                //     field: 'srmOrderCode',
                //     title: 'SRM订单号',
                //     width: 140
                // },
                // {
                //     field: 'receiptStatus',
                //     title: '收货状态',
                //     width: 90,
                //     sortable:true,
                //     exportEnum:[
                //         {code:1,codeWithDesc:'已收货'},
                //         {code:2,codeWithDesc:'部分收货'},
                //         {code:0,codeWithDesc:'未收货'},
                //     ],
                //     formatter: function (value, row) {
                //         switch (Number(value)) {
                //             case 0:
                //                 return '<span style="color: #050300;">未收货</span>';
                //             case 1:
                //                 return '<span style="color: #49b003;">已收货</span>';
                //             case 2:
                //                 return '<span style="color: #3d49d5;">部分收货</span>';
                //             default:
                //                 return '--';
                //         }
                //     }
                // },
                {
                    field: 'whetherCallOff',
                    title: '线下取消状态',
                    width: 100,
                    sortable:true,
                    exportEnum:[
                        {code:1,codeWithDesc:'正常'},
                        {code:2,codeWithDesc:'已取消'},
                    ],
                    formatter: function (value, row) {
                        switch (Number(value)) {
                            case 1:
                                return '<span style="color: #49b003;">正常</span>';
                            case 2:
                                return '<span style="color: red;">已取消</span>';
                            default:
                                return '--';
                        }
                    }
                },
                {
                    field: 'skuName',
                    title: '商品名称',
                    width: 400,
                    formatter: function (value) {
                        return '<span style="display: inline-block;width: 450px;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;" title="' + value + '">' + value + '</span>';
                    }
                },
                {
                    field: 'unitCost',
                    title: '单价',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'unit',
                    title: '单位',
                    width: 70
                },
                {
                    field: 'qty',
                    title: '商品数量',
                    sortable:true,
                    width: 100
                },
                {
                    field: 'requireNum',
                    title: '请购数量',
                    sortable:true,
                    width: 100
                },
                {
                    field: 'receiptNum',
                    title: '收货数量',
                    sortable:true,
                    width: 100
                },
                {
                    field: 'returnQuatity',
                    title: '退货数量',
                    sortable:true,
                    width: 100
                },
                {
                    field: 'purchaseOrg',
                    title: '采购组织',
                    width: 120,
                    sortable:true,
                    formatter: function (value, row) {
                        return value + '-' + row.pgoName;
                    }
                },
                {
                    field: 'purchaseGroup',
                    title: '采购组',
                    width: 180,
                    sortable:true,
                    formatter: function (value, row) {
                        return value + '-' + row.pgName;
                    }
                },
                {
                    field: 'factoryCode',
                    title: '工厂',
                    width: 180,
                    sortable:true,
                    formatter: function (value, row) {
                        return value + '-' + row.factoryName;
                    }
                },
                {
                    field: 'receivingUser',
                    title: '收货人',
                    sortable:true,
                    width: 100
                },
                {
                    field: 'receivingTel',
                    title: '收货人联系电话',
                    sortable:true,
                    width: 100
                },
                {
                    field: 'invoiceState',
                    title: '开票方式',
                    width: 180,
                    sortable:true,
                    exportEnum:[
                        {code:1,codeWithDesc:'随单开票'},
                        {code:2,codeWithDesc:'集中开票'},
                    ],
                    formatter: function (value) {
                        if(Number(value) === 1){
                            return '随单开票';
                        } else if(Number(value) === 2){
                            return '集中开票';
                        } else {
                            return '';
                        }
                    }
                },
                {
                    field: 'invoiceType',
                    title: '发票类型',
                    width: 180,
                    sortable:true,
                    exportEnum:[
                        {code:1,codeWithDesc:'电子普通发票'},
                        {code:2,codeWithDesc:'增值税专用发票'},
                    ],
                    formatter: function (value) {
                        if(Number(value) === 1){
                            return '电子普通发票';
                        } else if(Number(value) === 2){
                            return '增值税专用发票';
                        } else {
                            return '';
                        }
                    }
                },
                {
                    field: 'createUserName',
                    title: '创建人',
                    sortable:true,
                    width: 180
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    width: 180,
                    sortable:true
                },
                {
                    field: 'invoiceTitle',
                    title: '抬头',
                    sortable:true,
                    width: 180
                },
                {
                    field: 'content',
                    title: '发票内容',
                    sortable:true,
                    width: 180
                },
                {
                    field: 'remark',
                    title: '备注说明',
                    sortable:true,
                    width: 180
                }
            ]
        ],
        toolbar: [
            {
                text: '查看',
                id: 'btn_look',
                iconCls: 'icon-add',
                handler: function () {
                    lookupDicItem('');
                    setOperationLog("查看按钮", "商城订单明细");

                }
            },
            '-',
            {
                text: '导出明细',
                hide: true,
                id: 'btn_export_detail',
                iconCls: 'icon-remove',
                handler: function () {
                    detailExport();
                }
            },
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole('shoppingCart');
            $(el.tb).datagrid('clearSelections');
        }
    });
}


/**
 * 线下取消
 *
 * @param optType 1:正常 2:已取消
 */
function callOff() {

    var rows = $(el.tb).datagrid("getSelections");
    if (rows.length == 0) {
        topWin.layer.msg("请选择数据",{icon:0});
        return;
    }

    var row = $(el.tb).datagrid('getSelected');
    var status = row.srmStatus;
    if (Number(status) == 5) {
        topWin.layer.alert('该订单(' + row.thirdOrder + ')状态为“待确认”，无需取消，请点击删除', {icon: 0});
        return false;
    }

    layer.confirm('是否确认更改数据状态?', function (index) {
        var loading = topWin.layer.msg('数据处理中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: '/pc/mall/cart/rest/callOff',
            method: "post",
            data: {
                id: rows[0].id,
                whetherCallOff:rows[0].whetherCallOff,
                // prItemNo:rows[0].prItemNo
            },
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg("操作成功",{icon:1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
        layer.close(index)
    })

}


/**
 * 导出明细
 */
function detailExport() {
    xhrPostExport('pc/mall/cart/rest/detail/export', getQuery());
}


/**
 * 获取查询条件
 */
function getQuery() {
    var queryParams = {};
    queryParams.thirdOrder = $.trim($(el.thirdOrder).val());
    queryParams.pgoName = $.trim($("#pgoName").val());
    queryParams.pgName = $.trim($("#pgName").val());
    queryParams.createUserName = $.trim($("#createUserName").val());
    queryParams.factoryName = $.trim($("#factoryName").val());
    queryParams.factoryCode = $.trim($("#factoryCode").val());
    queryParams.srmStatus = $.trim($("#srmStatus").combobox('getValue'));
    queryParams.receiptStatus = $.trim($("#receiptStatus").combobox('getValue'));
    queryParams.startCreateDate = $.trim($(el.startCreateDate).val());
    queryParams.endCreateDate = $.trim($(el.endCreateDate).val());

    return queryParams;
}


/**
 * 售后申请
 * @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 whetherCallOff = row.whetherCallOff;
        if (Number(whetherCallOff) !== 1) {
            topWin.layer.alert('只有“线下取消状态为正常”状态的单据才能执行该操作, 您选择的订单(' + row.thirdOrder + ')当前状态不正确, 请检查', {icon: 0});
            return false;
        }
    }

    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'].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.thirdOrder = $.trim($(el.thirdOrder).val());
    queryParams.pgoName = $.trim($("#pgoName").val());
    queryParams.pgName = $.trim($("#pgName").val());
    queryParams.createUserName = $.trim($("#createUserName").val());
    queryParams.factoryName = $.trim($("#factoryName").val());
    queryParams.factoryCode = $.trim($("#factoryCode").val());
    queryParams.srmStatus = $.trim($("#srmStatus").combobox('getValue'));
    queryParams.receiptStatus = $.trim($("#receiptStatus").combobox('getValue'));
    queryParams.startCreateDate = $.trim($(el.startCreateDate).val());
    queryParams.endCreateDate = $.trim($(el.endCreateDate).val());
    $(el.tb).datagrid('load');
}


/**
 * 重置查询
 */
function resetDictTypeSearch() {
    $(el.thirdOrder).val('');
    $("#pgoName").val('');
    $(el.startCreateDate).datebox('setValue','');
    $(el.endCreateDate).datebox('setValue','');
    $("#pgName").val('');
    $("#createUserName").val('');
    $("#factoryName").val('');
    $("#factoryCode").val('');
    $("#srmStatus").val('');
    $("#receiptStatus").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;
    }
    var whetherCallOff = row.whetherCallOff;
    if (Number(whetherCallOff) !== 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/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 whetherCallOff = row.whetherCallOff;
    if (Number(whetherCallOff) !== 1) {
        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;
    }
    if ( Number(row.whetherCallOff) !== 1) {
        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});
            }
        });
    });
}