let el = {
    tb: '#tb',
    supplierId: '#supplierId',
    searchForm: '#searchForm',
    hadExamine: '#hadExamine',
    examineState: '#examineState',
    state: '#state',
    type: '#type',

    bodyHeight: document.documentElement.clientHeight
};
var submitFlag = 0

let options = {
    columns: []
};

$(function () {
    initData();
    loadGrid();
});

/**
 * 初始化数据
 */
function initData() {
    //表格列
    options.columns = [
        {
            field: 'ck',
            checkbox: true
        },
        {
            field: 'optType',
            title: "发起类型",
            width: '95',
            formatter: function (value) {
                return value === 1 ? '供应商发起' : '采购发起'
            }
        },
        {
            field: 'supplierId',
            hidden: true,
            width: '95'
        },
        {
            field: 'supplierCode',
            title: itableTitlei18n.gysbm,
            width: '95'
        },
        {
            field: 'supplierName',
            title: itableTitlei18n.gysmc,
            width: '245'
        },
        {
            field: 'examineState',
            title: '商务审批状态',// itableTitlei18n.shzt,
            width: '95',
            formatter: function (value) {
                switch (value) {
                    case 0:
                        return '待采购审批';
                    case 1:
                        return '<span style="color:green">' + itablei8n.tg + '</span>';
                    case 2:
                        return '<span style="color:red">' + statusi18n.bh + '</span>';
                    default:
                        return statusi18n.wz;
                }
            }
        }, {
            field: 'userName',
            title: '采购审批人',
            width: '245'
        },
        {
            field: 'bpmState',
            title: 'OA审批状态',
            width: '80',
            formatter: function (value) {

                switch (value) {
                    case 0:
                        return '待提交'
                    case 1:
                        return '<span style="color:blue">审批中</span>';
                    case 2:
                        return '<span style="color:green">' + statusi18n.tg + '</span>';
                    case 3:
                        return '<span style="color:red">' + itablei8n.bh + '</span>';
                    default:
                        return statusi18n.wz;
                }
            }
        },
        {
            field: 'bpmCode',
            title: '流程号',
            width: 245,
            hidden: isSupplier,
            formatter: function (value, row) {
                return oaTrack(value, OaProcessType.SUPPLIER_CHANGE)
            }
        },
        {
            field: 'createTime',
            title: itableTitlei18n.cjsj,
            width: '135'
        },
        {
            field: 'version',
            title: itableTitlei18n.bb,
            width: '60'
        }
    ];
}

/**
 * 加载数据表格
 */
function loadGrid() {
    let searchHeight = $(el.searchForm).outerHeight() - 10;
    let pager = initGridPager(el.bodyHeight - searchHeight * 2 - 120, 40);
    let examineState = $(el.examineState).combobox('getValue');
    $(el.tb).datagrid({
        loadMsg: itablei8n.dataLoading,
        method: "GET",
        url: g.ctx + 'pc/supplier/supplierChange/rest/listAll',
        singleSelect: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        striped: true,
        height: el.bodyHeight - searchHeight - 10,
        rownumbers: true,
        queryParams: {
            minVersion: 0,
            examineState: examineState
        },
        columns: [options.columns],
        toolbar: [
            {
                text: '查看变更申请单',
                iconCls: 'icon-book',
                id: 'btn_look_all',
                handler: function () {
                    examine(1);
                }
            },
            {
                text: '查看供应商信息',
                iconCls: 'icon-search',
                id: 'btn_supplier_info_all',
                handler: function () {
                    supplierInfo();
                }
            },{
                text: '导出', iconCls: 'icon-print', id: 'btn_change_export', handler: function () {
                    exportExcel();
                }
            }, '-',
            {
                text: '删除',
                id: 'btn_supplier_oa_delete',
                iconCls: 'icon-remove',
                handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    if (!row) {
                        layer.msg("请选中一条记录");
                        return;
                    }
                    delSup(row.id);
                }
            }

        ],
        onLoadSuccess: function () {
            displayButtonByUserRole('SupplierChangeVersionAll');
        }
    });
}
/**
 * 导出excel
 */
function exportExcel() {
    openExportDialog( "pc/supplier/supplierChange/rest/export","tb", searchParams())
}
function supplierInfo() {
    let rows = $(el.tb).datagrid('getSelections');
    if (rows.length < 1) {
        parent.layer.msg('您未选中任何数据!');
        return;
    }
    if (rows.length > 1) {
        parent.layer.msg('该操作只能选中一条记录');
        return;
    }
    let id = rows[0].supplierId;
    var url = g.ctx + 'pc/supplier/detail?id=' + id
    var invitationEditDialog = openDialog('invitationEditDialog', url, {
        title: '查看供应商信息',
        width: "90%",
        height: "100%",
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            invitationEditDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.close, handler: function () {
                invitationEditDialog.dialog('close');
            }
        }]
    });
}

var modifyDialog = undefined;
var submitFlag = 0;





var examineDialog = undefined;

/**
 * 审批、查看
 * @param type 0.审批 1.查看
 */
function examine(type) {
    let title = handlei18n.xxbgsq;
    let url;
    let row;
    var btns = [];
    switch (type) {
        case 0:
            row = $(el.tb).datagrid('getSelected');
            if (!row) {
                layer.msg(handlei18n.qxzspsj);
                return
            }
            if (row.examineState !== 0) {
                layer.msg(handlei18n.gsjysp);
                return;
            }
            btns = [{
                text: "同意", handler: function () {

                    var result = topWin.frames['examineDialog'].getRemark();
                    if (result.oaType === '') {
                        topWin.layer.msg("请选择变更类型")
                        return
                    }
                    if (result.isFreeze === '') {
                        topWin.layer.msg("请选择是否冻结")
                        return
                    }
                    examineChangeSubmit(row.id, result.remark, 1, result.oaType, result.isFreeze);
                }
            }, {
                text: statusi18n.bh, handler: function () {
                    var result = topWin.frames['examineDialog'].getRemark();
                    examineChangeSubmit(row.id, result.remark, 2, result.oaType, result.isFreeze);
                }
            }, {
                text: itablei8n.close, handler: function () {
                    examineDialog.dialog('close');
                }
            }];

            break;
        case 1:
            row = $(el.tb).datagrid('getSelected');
            if (!row) {
                layer.msg(tipsi18n.wxzrhsj);
                return
            }
            if (!row) {
                layer.msg(tipsi18n.qxzckdsj);
                return
            }
            btns = [{
                text: itablei8n.close, handler: function () {
                    examineDialog.dialog('close');
                }
            }];
            break;
        default:
    }
    url = g.ctx + 'pc/supplier/supplierChange/page/lookup?id=' + row.id + '&type=' + type;
    examineDialog = openDialog("examineDialog", url, {
        title: title,
        width: '85%',
        height: '100%',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            examineDialog.dialog('destroy');
        },
        buttons: btns
    });
}

/**
 * 查看oa流程
 * @param ele
 */
function lookOaApproveLog(ele) {
    billCommon.lookOaApproveLog($(ele).data('billid'), $(ele).data('processid'), $(ele).data('sender'))
}

/**
 * 关闭详情页面，刷新表格
 */
function closeDetailWin() {
    $(el.tb).datagrid('reload');
    parent.layer.closeAll();
}

//查询按钮
function searchGrid() {
    let query = $(el.searchForm).serializeJson();
    query.type = 1;
    query['minVersion'] = 0;
    $(el.tb).datagrid('options').queryParams = query;
    $(el.tb).datagrid('load');
}

//重置查询条件
function resetSearch() {
    $(el.searchForm).form('clear');
    searchGrid();
}

var submitFlag = 0;

/**
 * 变更审批提交
 * @param index 表格索引
 * @param layero 窗口
 * @param row 行
 * @param state 1.通过 2.驳回
 */
function examineChangeSubmit(id, remark, state, oaType, isFreeze) {
    if (submitFlag == 1) {
        return
    }
    if (state === 2 && remark === "") {
        topWin.layer.alert("请填写驳回原因", {icon: 3});
        return;
    }
    parent.layer.load(1);
    submitFlag = 1;
    $.ajax({
        url: g.ctx + 'pc/supplier/supplierChange/rest/examine',
        method: "POST",
        data: JSON.stringify({
            id: id,
            state: state,
            remark: remark,
            oaType: oaType === undefined ? 0 : oaType,
            isFreeze: isFreeze === undefined ? 0 : isFreeze
        }),
        contentType: 'application/json',
        complete: function () {
            topWin.layer.closeAll('loading')
            submitFlag = 0
        },
        success: function (data) {
            topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                topWin.layer.close(idx);
                examineDialog.dialog('close');
                $(el.tb).datagrid('load');
            });
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    })

}
function delSup(id) {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg("请选中一条记录",{icon: 0});
        return;
    }
    debugger;

    // 0 待提交  3 驳回
    if (row.bpmState != 0 && row.bpmState != 3 ) {
        topWin.layer.msg("请选中待提交/驳回的记录");
        return;
    }

    topWin.layer.confirm("您确定要删除选中的记录吗?", function (index) {
        $.ajax({
            url: g.ctx + 'pc/supplier/supplierChange/rest/remove',
            type: 'POST',
            data: {id: id},
            success: function (data) {
                topWin.layer.alert("删除成功", {icon: 1}, function (idx) {
                    $(el.tb).datagrid("reload")
                    topWin.layer.close(index);
                    topWin.layer.close(idx);
                });
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        })
    })
}
