var page = {
    submitFlag: 0, dataGrid: {}, dialogElement: {}, tableReload: function () {
        page.dataGrid.datagrid("reload");
    }, approvel: function (type) {
        //type=1主管确认 2:价格确认
        var row = page.dataGrid.datagrid("getSelected");
        if (!row) {
            topWin.layer.msg("请选择需要查看的招标单!");
            return
        }
        if (row.openBidUserSize !== row.bidedUserSize) {
            topWin.layer.msg("选择的招标单开标小组未确认完成!");
            return
        }
        const toolbars = [
            {
                text: '同意', handler: function () {
                    page.postApproval(row.id, type, 1, function () {
                        page.lookupdialogElement.dialog('close');
                    })
                }
            },
            {
                text: '驳回', handler: function () {
                    page.postApproval(row.id, type, 0, function () {
                        page.lookupdialogElement.dialog('close');
                    })
                }
            },
            {
                text: '关闭', handler: function () {
                    page.lookupdialogElement.dialog('close');
                }
            }]
        var title = "审核定标"
        var url = g.ctx + "pc/tender/benchmarks/page/detail?id=" + row.id + "&type=0";
        page.lookupdialogElement = openDialog("lookupdialogElement", url, {
            title: title,
            width: '100%',
            height: '100%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                page.lookupdialogElement.dialog('destroy');
            },
            buttons: toolbars
        });
    }, info: function (type) {
        var row = page.dataGrid.datagrid("getSelected");
        if (!row) {
            topWin.layer.msg("请选择需要查看的招标单!");
            return
        }
        if (row.openBidUserSize !== row.bidedUserSize) {
            topWin.layer.msg("选择的招标单开标小组未确认完成!");
            return
        }
        const toolbars = [{
            text: '关闭', handler: function () {
                page.lookupdialogElement.dialog('close');
            }
        }]
        var title = ''
        if (type === 0) {
            title = "查看定标"
        } else if (type === 1) {
            title = "定标"
            toolbars.unshift({
                text: '暂存', handler: function () {
                    topWin.frames['lookupdialogElement'].page.saveOrUpdate(function () {
                        page.lookupdialogElement.dialog('close');
                        page.tableReload();
                    }, 0);
                }
            }, {
                text: '定标', handler: function () {
                    debugger;
                    var row = page.dataGrid.datagrid('getSelected');
                    //进行未报价的物料是否有有效价格进行校验
                    //定标时进行物料有效价格的查询
                    $.ajax({
                        url: g.ctx + 'pc/tender/benchmarks/rest/supplierUnquotedMaterials?id=' + row.id,
                        type: "GET",
                        dataType: 'json',
                        async: false, // 设置为同步
                        success: function (data) {
                            debugger;
                            console.log(data)
                            if (Array.isArray(data)) {
                                if(data.length  > 0){
                                    topWin.layer.alert("供应商未报价的物料：请先在系统中维护有效价格：["+data+"]", {icon: 2});
                                    return;
                                }else{
                                    //全部有有效价格后才能进行定标
                                    topWin.frames['lookupdialogElement'].page.saveOrUpdate(function () {
                                        page.lookupdialogElement.dialog('close');
                                        page.tableReload();
                                    }, 1);
                                }
                            }
                        },
                        error: function (data) {
                            topWin.layer.alert("获取未报价物料价格数据失败数据", {icon: 2});
                        }
                    });

                }
            })
        } else if (type === 2) {
            title = "结果发布"
            toolbars.unshift({
                text: '提交', handler: function () {
                    topWin.frames['lookupdialogElement'].page.release(function () {
                        page.lookupdialogElement.dialog('close');
                        page.tableReload();
                    });
                }
            })
        }
        var url = g.ctx + "pc/tender/benchmarks/page/detail?id=" + row.id + "&type=" + type;
        page.lookupdialogElement = openDialog("lookupdialogElement", url, {
            title: title,
            width: '100%',
            height: '100%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                page.lookupdialogElement.dialog('destroy');
            },
            buttons: toolbars
        });
    },
    postApproval: function (id, type, agreeFlag, call) {
        topWin.layer.prompt({title: '请输入审批意见', formType: 2, value: "同意"}, function (value, index, elem) {
            if (page.submitFlag === 1) {
                return
            }
            page.submitFlag = 1;
            $.ajax({
                url: g.ctx + 'pc/tender/benchmarks/rest/approvel',
                type: "POST", data: {id: id, type: type, agreeFlag: agreeFlag, remark: value},
                complete: function () {
                    page.submitFlag = 0
                },
                success: function (d) {
                    topWin.layer.msg("操作成功", {icon: 1});
                    topWin.layer.close(index);
                    $('#tb').datagrid("reload")
                    call()
                },
                error: function (data) {
                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                }
            });
        });
    },
    initTableDataGrid: function () {
        var toolbars = [{
            text: '确认开标', iconCls: 'icon-select-all', hidden: true, id: 'batchOpen', handler: function () {
                var rows = page.dataGrid.datagrid("getChecked");
                if (rows.length < 1) {
                    topWin.layer.msg("请选择需要确认开标的招标单!");
                    return;
                }
                if (page.submitFlag == 1) {
                    return;
                }
                var ids = [];
                $.each(rows, function (index, item) {
                    if (item.selfOpenStatus === OPEN_BID_STATUS["1"].val) {
                        ids.push(item.id);
                    }
                });
                if (ids.length <= 0) {
                    topWin.layer.alert("选中的招标不需要您确认开标或已经确认开标了!", {icon: 2});
                    return;
                }
                topWin.layer.confirm('是否确认开标？', function (index) {
                    page.submitFlag = 1;
                    $.ajax({
                        url: g.ctx + "pc/tender/benchmarks/rest/updateOpenBidStatus",
                        type: 'POST',
                        data: {idStr: ids.join(",")},
                        complete: function () {
                            page.submitFlag = 0;
                        },
                        success: function (d) {
                            topWin.layer.close(index);
                            page.dataGrid.datagrid("reload");
                            topWin.layer.alert('操作成功', {icon: 1});
                        },
                        error: function (data) {
                            topWin.layer.close(index);
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                        }
                    });
                });
            }
        }, '-', {
            text: '查看', iconCls: 'icon-book', id: "open_bid_look", handler: function () {
                var rows = page.dataGrid.datagrid('getSelections');
                if (rows.length != 1) {
                    topWin.layer.msg("请选择一条需要查看的招标单!");
                    return;
                }
                page.info(0);
            }
        }, "-", {
            text: '定标', iconCls: 'icon-book-fix', hidden: true, id: 'calibrationBtn', handler: function () {
                var row = page.dataGrid.datagrid("getSelected");
                if (!row) {
                    topWin.layer.msg("请选择需要查看的招标单!");
                    return
                }
                if (row.status !== 3 && row.status !== 98 && row.status !== 97) {
                    topWin.layer.msg("请选择已截止或者驳回招标单!");
                    return
                }
                page.info(1);
            }
        }, "-", {
            text: '主管审批',
            iconCls: 'icon-confirm',
            id: 'btn_charge_confirm',
            handler: function () {
                var row = page.dataGrid.datagrid("getSelected");
                if (!row) {
                    topWin.layer.msg("请选择需要查看的招标单!");
                    return
                }
                if (row.status !== 7) {
                    topWin.layer.msg("请选择主管确认的招标单!");
                    return
                }
                page.approvel(1);
            }
        }, "-",
            {
                text: '总监审批',
                iconCls: 'icon-confirm',
                id: 'btn_price_confirm',
                handler: function () {
                    var row = page.dataGrid.datagrid("getSelected");
                    if (!row) {
                        topWin.layer.msg("请选择需要查看的招标单!");
                        return
                    }
                    if (row.status !== 8) {
                        topWin.layer.msg("请选择价格确认的招标单!");
                        return
                    }
                    page.approvel(2);
                }
            },
            '-', {
                text: '发布结果', iconCls: 'icon-book', id: "release_bid_look", handler: function () {
                    var rows = page.dataGrid.datagrid('getSelections');
                    if (rows.length != 1) {
                        topWin.layer.msg("请选择一条需要发布结果的招标单!");
                        return;
                    }
                    if (rows[0].status != TENDER_STATUS_CONST[5].val) {
                        topWin.layer.msg("请选择已定标的招标单!");
                        return;
                    }
                    page.info(2);
                }
            },
            '-', {
                text: '生成合同',
                iconCls: 'icon-sum',
                id: 'tender_contract',
                handler: function () {
                    var row = page.dataGrid.datagrid('getSelected');
                    if (row == null) {
                        topWin.layer.msg("请选择一条招标单!");
                        return;
                    }
                    if (row.status != 5 && row.status != 9) {
                        topWin.layer.msg("请选择一条已定标的招标单!");
                        return;
                    }
                    CREATE_CONTRACT_COMMON.lookCreateContract(CONTRACT_TYPE.ASSET, '#tb', BUSINESS_TYPE.TENDER, row.id);
                }
            },
            '-', {
                text: '生成费用合同',
                iconCls: 'icon-sum',
                id: 'btn_cost_contract',
                handler: function () {
                    var row = page.dataGrid.datagrid('getSelected');
                    if (row == null) {
                        topWin.layer.msg("请选择一条招标单!");
                        return;
                    }
                    if (row.purchaseRequestType !== "01") {
                        topWin.layer.msg("请选择费用合同类招投标的招标单！");
                        return;
                    }
                    if (row.status !== 5 && row.status !== 9) {
                        topWin.layer.msg("请选择一条已定标或已完成的招标单!");
                        return;
                    }
                    CREATE_CONTRACT_COMMON.lookCreateContract(CONTRACT_TYPE.COST, '#tb', BUSINESS_TYPE.TENDER, row.id);
                }
            }

        ];

        var columns = [[{
            field: 'id', hidden: true
        }, {
            field: 'ck', checkbox: true
        }, {
            field: 'status', title: '招标状态', width: 85, align: 'center', formatter: function (value, row, index) {
                return TENDER_STATUS_CONST[value].color
            }
        }, {

            field: 'ok',
            title: '议价情况',
            width: 100,
            align: 'center',
            formatter: function (val, row) {
                if (row.ok === '' && row.notOk === '') {
                    return '未议价'
                } else {
                    return '<a href="javascript:void(0)" class="easyui-linkbutton lookup_confirm" ' +
                        'data-id="' + row.id + '"' + '">查看(' + row.ok + '/' + (Number(row.ok) + Number(row.notOk)) + ')</a>';
                }
            }
        },

            {
                field: '1',
                title: '开标确认进度',
                width: 95,
                align: 'center',
                formatter: function (value, row, index) {
                    return '<a href="javascript:void(0)" class="easyui-linkbutton lookup" data-id="' + row.id + '">' + row.bidedUserSize + " / " + row.openBidUserSize + '</a>';

                }
            }, {
                field: 'selfOpenStatus',
                title: '开标状态',
                width: 110,
                align: 'center',
                formatter: function (value, row, index) {
                    if (value) {
                        return OPEN_BID_STATUS[value].color
                    }
                    return '';
                }
            }, {
                field: 'code', title: '招标编号', width: 180
            }, {
                field: 'title', title: '招标标题', width: 300, align: 'left'

            }, {
                field: 'createName', title: '创建人', width: 110, align: 'center'

            }, {
                field: 'purchaseGroupCode', title: '采购组', width: 100, align: 'left'
            }, {
                field: 'oaWorkId',
                title: 'OA流程号',
                width: 200,
                sortable: true,
                formatter: function (value, row) {
                    return oaTrack(value, OaProcessType.TENDER_PRICE)
                }
            }]];
        var url = '';
        url = 'pc/tender/benchmarks/rest/list';
        let queryParams = {
            page: 1, rows: 10
        }
        if ($("#status").combobox("getValue") === undefined) {
            queryParams['status'] = 3
            $("#status").combobox("setValue", "3")
        } else {
            queryParams['status'] = $("#status").combobox("getValue")
        }
        console.log(queryParams);
        page.dataGrid = $('#tb').datagrid({
            iconCls: 'icon-list',
            width: '100%',
            method: "GET",
            url: g.ctx + url,
            height: $(window).height() - $('#searchForm').outerHeight() - 10,
            singleSelect: false,
            pagination: true,
            loadMsg: "数据加载中......",
            rownumbers: true,
            nowrap: true,
            remoteSort: true,
            striped: true,
            page: 1,
            pageSize: 20,
            queryParams: queryParams,
            columns: columns,
            toolbar: toolbars,
            onLoadSuccess: function () {
                displayButtonByUserRole('定标管理');
            },
            onCheck: function (index, rowData) {
            }
        });
    }, release: function () {
        var row = page.dataGrid.datagrid("getSelected");
        if (!row) {
            topWin.layer.msg("请选择需要发布结果的招标单!");
            return
        }
        $.ajax({
            url: g.ctx + 'open/bid/rest/valid/open', type: "get", data: {id: row.id}, success: function (d) {
                if (d == '') {
                    page.openReleasResultDialog(row.id)
                } else {
                    topWin.layer.alert(d.msg, {icon: 2});
                }

            }
        });
    },
    openConfigDialog: function (id) {
        var openConfigDialog = openDialog("openConfigDialog", g.ctx + "pc/tender/benchmarks/page/confirmUser?tenderId=" + id, {
            title: "开标确认进度",
            width: 350,
            height: 500,
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                openConfigDialog.dialog('destroy');
            },
            buttons: [{
                text: '关闭', handler: function () {
                    openConfigDialog.dialog('close');
                }
            }]
        });
    },
    openReleasResultDialog: function (id) {
        page.releasDialogElement = openDialog("releasDialog", "/open/bid/page/wining/supplier?tenderId=" + id, {
            title: "发布中标信息",
            width: '90%',
            height: '100%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                page.releasDialogElement.dialog('destroy');
            },
            buttons: [{
                text: '发布', handler: function () {
                    topWin.frames['releasDialog'].page.save(page.closeReleasResultDialog);
                }
            }, {
                text: '关闭', handler: function () {
                    page.releasDialogElement.dialog('close');
                }
            }]
        });
    }, closeReleasResultDialog: function () {
        page.releasDialogElement.dialog('close');
        page.tableReload();
    }, lookup: function (id) {

        var dialogHeight = 0;
        var windowHeight = $(window).height();
        var minHeight = 750;
        var maxHeight = 900;

        if (windowHeight <= maxHeight) {
            dialogHeight = minHeight;
        } else {
            dialogHeight = maxHeight;
        }
        this.openUserLookupDialogElement = openDialog("open_user_lookup_iframe", "/page/comm/open/user/lookup?tenderId=" + id, {
            title: "开标小组成员查看",
            width: 1200,
            height: dialogHeight,
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                page.openUserLookupDialogElement.dialog('destroy');
            },
            buttons: [{
                text: '关闭', handler: function () {
                    page.openUserLookupDialogElement.dialog('close');
                }
            }]
        });
    }, initStatusCombox: function () {
        $("#status").combobox({
            editable: false,
            valueField: 'value',
            multiple: true,
            textField: 'txt',
            data: [
                {value: '3', txt: '已截止'},
                {value: '6', txt: '定标审批中'},
                {value: '7', txt: '主管审批中'},
                {value: '8', txt: '总监审批中'},
                {value: '5', txt: '已定标'},
                {value: '9', txt: '已完成'},
                {value: '98', txt: '发布驳回'},
                {value: '97', txt: '定标驳回'}
            ]
        })
    },

    lookup: function (id, type) {
        var url = '';
        url = g.ctx + "pc/tender/page/bargainingProcess?id=" + id + "&type=" + type;
        page.lookupProcessDialog = openDialog("lookupProcessDialog", url,
            {
                title: "议价情况",
                width: 800,
                height: 565,
                cache: false,
                modal: true,
                border: false,
                draggable: false,
                shadow: false,
                onClose: function () {
                    page.lookupProcessDialog.dialog('destroy');
                },
                buttons: [{
                    text: '关闭',
                    handler: function () {
                        page.lookupProcessDialog.dialog('close');
                    }
                }]
            });
    },
};

$(function () {
    page.initStatusCombox();
    page.initTableDataGrid();
    $("#table_div").delegate('.lookup', 'click', function (event) {
        var id = $(this).data("id");
        page.openConfigDialog(id);
    });
    $("#table_div").delegate('.lookup_confirm', 'click', function (event) {
        var id = $(this).data("id");
        page.lookup(id, 0);
    });
});
