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/list',
        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: itablei8n.newAdd,
                iconCls: 'icon-add',
                id: 'btn_add',
                handler: function () {
                    addOrEdit(0);
                }
            },
            {
                text: '新增(采购端)',
                iconCls: 'icon-add',
                id: 'btn_add_admin',
                handler: function () {
                    selectSupplier();
                }
            },
            {
                text: '新增(供应商)',
                iconCls: 'icon-add',
                id: 'btn_add_supp',
                handler: function (value, row, index) {
                    addOrEdit(0);
                }
            },
            //重新提交审批
            {
                text: itablei8n.againSubmit,
                id: 'btn_re_submit',
                iconCls: 'icon-reload',
                handler: function () {
                    addOrEdit(1);
                }
            },
            {
                text: "采购确认",
                id: 'btn_examine',
                iconCls: 'icon-ok',
                handler: function () {
                    examine(0);
                }
            },
            {
                text: '查看变更申请单',
                iconCls: 'icon-book',
                id: 'btn_look',
                handler: function () {
                    examine(1);
                }
            },
            {
                text: '查看供应商信息',
                iconCls: 'icon-search',
                id: 'btn_supplier_info',
                handler: function () {
                    supplierInfo();
                }
            }, '-',
            {
                text: "OA审批通过",
                id: 'btn_supplier_oa_agree',
                iconCls: 'icon-ok',
                handler: function () {
                    textBpm(2);
                }
            }, '-',
            {
                text: "OA审批拒绝",
                id: 'btn_supplier_oa_refuse',
                iconCls: 'icon-cancel',
                handler: function () {
                    textBpm(3);
                }
            }, '-',
            {
                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('SupplierChangeVersion');
        }
    });
}

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;

/**
 * 替供应商做信息变更，
 * 由系统人员发起
 */
function selectSupplier() {
    var supplierDialogElement = openDialog("supplierDialog", g.ctx + "pc/supplier/supplierSelect?single=1", {
        title: "供应商选择",
        width: '650px',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            supplierDialogElement.dialog('destroy');
        },
        buttons: [{
            text: '选择', iconCls: 'icon-save', handler: function () {
                topWin.frames['supplierDialog'].chooseRow(function (data) {
                    addOrEdit(null, data['id'])
                    supplierDialogElement.dialog('close');
                });
            }
        }, {
            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                supplierDialogElement.dialog('close');
            }
        }]
    })
}

/**
 * 新增、编辑
 * @param type 0.新增 1.选中一条记录，以此条记录做变更 - 相当于编辑
 */
function addOrEdit(type, supplierId) {
    var row = $(el.tb).datagrid("getSelected");

    if(type === 1 && row.bpmState !== 3){//重新发起要检验，OA审批状态是否为驳回
        topWin.layer.msg("仅驳回状态的供应商变更信息单可重新提交", {icon: 0});
        return;
    }

     // if ((type === 1 ||  type ===  0 ) && (row.examineState !== 2 && row.bpmState !== 3)) {
     //    topWin.layer.msg("仅驳回状态的供应商变更信息单可重新提交", {icon: 0});
     //     return;
     // }
    var url = ''
    if (supplierId !== undefined) {
        url = g.ctx + 'pc/supplier/supplierChange/page/detail?supplierId=' + supplierId;
    } else {
        switch (type) {
            case 0:
                url = g.ctx + 'pc/supplier/supplierChange/page/detail?supplierId=0'
                break;

            case 1:
                /**
                 * 供应商重新提交变更审批的
                 */

                url = g.ctx + 'pc/supplier/supplierChange/page/detail?supplierId=' + row.supplierId +'&id=' + row.id
                break;
            default:
        }

    }
    var modifyDialog = openDialog("modifyDialog", url, {
        title: '供应商信息变更',
        width: '85%',
        height: '100%',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            modifyDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.submit, handler: function () {
                topWin.frames['modifyDialog'].submitForm(function () {
                    $("#tb").datagrid("reload")
                    modifyDialog.dialog('close')
                })
            }
        }, {
            text: '关闭', handler: function () {
                modifyDialog.dialog('close');
            }
        }]
    });
}

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
    });
}

/**
 * 测试bpm接口，临时功能
 */
function textBpm(state) {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        layer.msg(tipsi18n.qxzspsj);
        return
    }
    if (row.bpmState !== 1) {
        layer.msg(tipsi18n.qxzbpmspz);
        return;
    }
    if (submitFlag == 1) {
        return;
    }
    parent.layer.confirm('是否审批' + (state == 2 ? '通过' : '驳回') + '？', function (index) {
        parent.layer.load(1);
        submitFlag = 1;
        $.ajax({
            url: g.ctx + 'pc/supplier/supplierChange/rest/oaExamine',
            method: "post",
            data: {
                id: row.id,
                state: state
            },
            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});
            }
        })
    })

}

/**
 * 查看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});
            }
        })
    })
}
