/**
 *
 * @author BOGON
 * @version 1.0
 */

var page = {
    submitFlag: 0,
    initDataGrid: function () {
        let toolbar = [
            {
                text: '导出信息',
                id: 'btn-export',
                iconCls: 'icon-print',
                handler: function () {
                    page.exportExcel();
                }
            },
            {
                text: '信息查看',
                id: 'btn-info-look',
                iconCls: 'icon-book',
                handler: function () {
                    page.information();
                }
            },
            {
                text: '信息查看(品质)',
                id: 'btn-info-look',
                iconCls: 'icon-book',
                handler: function () {
                    page.information1();
                }
            },
            {
                text: 'SQE评分',
                id: 'btn-sqe-score',
                iconCls: 'icon-book',
                handler: function () {
                    page.sqeScore();
                }
            }, {
                text: '转小批量',
                id: 'btn-convert-smallbatch',
                iconCls: 'icon-ok',
                handler: function () {
                    if (page.submitFlag == 1) {
                        return;
                    }
                    let rows = $("#tb").datagrid('getSelections');
                    if (rows.length == 0) {
                        topWin.layer.msg('请选择至少一条数据', {icon: 0});
                        return;
                    }
                    //需要判断选中的数据中是否存在审批中，
                    //需要判断oaId是否全部相同，否则无法转小批量
                    //需要判断supplierId是否全部相同，否则无法转小批量
                    let tipMsg = []
                    let oaIdMap = {}
                    let supplierIdMap = {}
                    $.each(rows, function (index, row) {
                        oaIdMap[row.oaId] = 1
                        supplierIdMap[row.supplierId] = 1
                        if (row.apprState === 2 || row.apprState === 1) {
                            tipMsg.push("选中的第" + (index + 1) + "条数据审批状态不正确")
                        }
                    })
                    // 检查 oaIdMap 的键是否重复
                    const oaIdKeys = Object.keys(oaIdMap);
                    const oaIdSet = new Set(oaIdKeys);
                    const oaIdDuplicate = oaIdKeys.length !== oaIdSet.size;

                    if (oaIdDuplicate) {
                        tipMsg.push("不同的OA单据无法一起提交")
                    }
                    // 检查 supplierIdMap 的键是否重复
                    const supplierIdKeys = Object.keys(supplierIdMap);
                    const supplierIdSet = new Set(supplierIdKeys);
                    const supplierIdDuplicate = supplierIdKeys.length !== supplierIdSet.size;

                    if (supplierIdDuplicate) {
                        tipMsg.push("不同的供应商数据无法一起提交")
                    }
                    if (tipMsg.length > 0) {
                        topWin.layer.msg(tipMsg.join("<br/>"), {icon: 0});
                        return;
                    }
                    page.submitFlag = 1;
                    topWin.layer.load(1);
                    $.ajax({
                        url: g.ctx + 'pc/supplier/purchaseCategory/rest/convertSmallbatch',
                        type: 'POST',
                        data: {
                            ids: rows.map(row => row.id).join(",")
                        },
                        success: function (data) {
                            topWin.layer.closeAll('loading');
                            page.submitFlag = 0;
                            topWin.layer.alert("操作成功!", {icon: 1})
                            $("#tb").datagrid("reload");
                        },
                        error: function (data) {
                            page.submitFlag = 0;
                            topWin.layer.closeAll('loading');
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                        }
                    })
                }
            }, {
                text: 'SQE处理',
                iconCls: 'icon-redo',
                id: 'btn-sqe-todo',
                handler: function () {
                    let rows = $("#tb").datagrid('getChecked');
                    if (rows.length < 1) {
                        topWin.layer.msg('请选择至少一条数据', {icon: 0});
                        return;
                    }
                    //过滤rows中reportFlag不是空字符串的
                    for (let i = 0; i < rows.length; i++) {
                        if (rows[i].reportFlag === "" || rows[i].reportFlag === 2) {

                        } else {
                            topWin.layer.msg('请选中SQE处理状态为空或SQE驳回的数据', {icon: 0});
                            return;
                        }
                    }
                    //获取rows中的id然后组装成数组
                    let ids = rows.map(row => row.id);
                    topWin.layer.confirm('您确认要提交吗?', {icon: 3}, function (index) {
                        let load = topWin.layer.load(1);
                        $.ajax({
                            url: g.ctx + "pc/supplier/purchaseCategory/rest/updateReportFlag",
                            method: "post",
                            data: {
                                ids: ids.join(","),
                            },
                            complete: function () {
                                topWin.layer.close(index)
                                topWin.layer.close(load)
                            },
                            success: function (data) {
                                $("#tb").datagrid('reload');
                                $("#tb").datagrid('clearSelections');
                            },
                            error: function (data) {
                                topWin.layer.alert(data.responseJSON.message, {icon: 2});
                            }
                        });
                    });
                }
            }, {
                text: '认证报告',
                id: 'btn-qualified—attachment',
                iconCls: 'icon-redo',
                handler: function () {
                    var row = $("#tb").datagrid("getChecked");
                    if (row.length == 0 || row.length != 1) {
                        topWin.layer.msg("请选择一条数据");
                        return;
                    }
                    var id = row[0].supplierId
                    var purchaseCategoryCode = row[0].purchaseCategoryCode
                    var approvalOpinion = row[0].approvalOpinion
                    page.onSiteAuthenticationFilesLookupDialog(id, purchaseCategoryCode,approvalOpinion)
                }
            },
            {
                text: '更新ERP编号',
                id: 'btn-update-erp-code',
                iconCls: 'icon-edit',
                handler: function () {
                    var row = $("#tb").datagrid("getChecked");
                    if (row.length == 0 || row.length != 1) {
                        topWin.layer.msg("请选择一条数据");
                        return;
                    }
                    var supplierId = row[0].supplierId
                    topWin.layer.prompt({title: '请输入ERP编码'}, function (value, index, elem) {
                        if (value === '') return elem.focus()
                        if (page.submitFlag == 1) return;
                        page.submitFlag = 1
                        let load = topWin.layer.load(0);
                        $.ajax({
                            type: "post",
                            url: g.ctx + "pc/supplier/rest/updateErpCode",
                            data: {erpCode: value, id: supplierId},
                            complete: function () {
                                topWin.layer.close(load);
                                page.submitFlag = 0
                            },
                            success: function (data) {
                                topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                                    topWin.layer.close(idx);
                                    topWin.layer.close(index);
                                });
                            },
                            error: function (data) {
                                topWin.layer.alert(JSON.parse(data.responseText).message, {icon: 2});
                            }
                        });
                    })
                }
            },
            {
                text: 'SQE驳回',
                id: 'btn-sqe-reject',
                iconCls: 'icon-edit',
                handler: function () {
                    let rows = $("#tb").datagrid('getChecked');
                    if (rows.length > 1 || rows.length == 0) {
                        topWin.layer.msg('请选择一条数据', {icon: 0});
                        return;
                    }
                    var reportFlag;
                    $.each(rows, function (index, row) {

                        reportFlag = row.reportFlag;
                    })
                    if (reportFlag === 0 && reportFlag !== "") {
                        let ids = rows.map(row => row.id);
                        topWin.layer.prompt({title: '请输入驳回原因'}, function (value, index, elem) {
                            if (value === '') return elem.focus()
                            if (page.submitFlag == 1) return;

                            page.submitFlag = 1
                            let load = topWin.layer.load(0);
                            $.ajax({
                                type: "post",
                                url: g.ctx + "pc/supplier/purchaseCategory/rest/updateSqeReject",
                                data: {remark: value, ids: ids.join(",")},
                                complete: function () {
                                    topWin.layer.close(load);
                                    page.submitFlag = 0
                                },
                                success: function (data) {
                                    topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                                        topWin.layer.close(idx);
                                        topWin.layer.close(index);
                                        location.reload();
                                    });
                                },
                                error: function (data) {
                                    topWin.layer.alert(JSON.parse(data.responseText).message, {icon: 2});
                                }
                            });
                        })
                    } else {
                        topWin.layer.msg('非SQE处理状态不允许驳回', {icon: 0});
                        return;
                    }
                }
            }
        ]
        let column = [[
            {
                field: 'ck',
                checkbox: 'true'
            },
            {
                field: 'state',
                title: '供应商状态',
                width: '100',
                align: 'left',
                exportEnum: [
                    {code: 1, codeWithDesc: '注册'},
                    {code: 2, codeWithDesc: '潜在'},
                    {code: 3, codeWithDesc: '正式'},
                    {code: 4, codeWithDesc: '临时'},
                    {code: 5, codeWithDesc: '退出'},
                    {code: 6, codeWithDesc: '合格'},
                    {code: 7, codeWithDesc: '小批量'},
                    {code: "", codeWithDesc: '初始'}
                ],
                formatter: function (value) {
                    switch (value) {
                        case 1:
                            return '注册';
                        case 2:
                            return '潜在';
                        case 3:
                            return '正式';
                        case 4:
                            return '临时';
                        case 5:
                            return '退出';
                        case 6:
                            return '合格';
                        case 7:
                            return '小批量';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'reportFlag',
                title: 'SQE处理状态',
                width: '115',
                align: 'left',
                exportEnum: [
                    {code: 1, codeWithDesc: 'SQE已处理'},
                    {code: 0, codeWithDesc: '待SQE处理'},
                    {code: 2, codeWithDesc: 'SQE驳回'}
                ],
                formatter: function (value) {
                    if (value === '') {
                        return value
                    } else if (value === 0) {
                        return '<span style="color: red;">待SQE处理</span>'
                    } else if (value === 1) {
                        return '<span style="color: darkgreen;">SQE已处理</span>'
                    } else if (value === 2) {
                        return '<span style="color: orange;">SQE驳回</span>'
                    }else if (value === 3) {
                        return '<span style="color: orange;">报告已上传</span>'
                    }else {
                        return '';
                    }
                }
            },
            {
                field: 'supplierCode',
                title: '供应商编号',
                width: '100',
                align: 'left',
                sortable: true
            },
            {
                field: 'supplierErpCode',
                title: '供应商ERP编号',
                width: '100',
                align: 'left',
                sortable: true
            },
            {
                field: 'supplierName',
                title: '供应商名称',
                width: '260',
                align: 'left'

            },
            {
                field: 'companyCode',
                title: '公司名称',
                width: '260',
                align: 'left',
                sortable: true,
                exportEnum: getNecessaryDataList('pc/sys/company/rest/listAll'),
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/company/rest/listAll', value)
                }

            },
            {
                field: 'assessType',
                title: '评审方式',
                width: 100,
                exportEnum: getDictList("assess_type"),
                formatter: function (value) {
                    return getDicName('assess_type', value)
                }
            },
            {
                field: 'purchaseGroupCode',
                title: '对账采购组',
                width: '120',
                align: 'left',
                exportEnum: getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll'),
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll', value)
                }
            },
            {
                field: 'purchaseCategoryCode',
                title: '采购品类编码',
                width: '120',
                align: 'left'
            },
            {
                field: 'purchaseCategoryName',
                title: '采购品类名称',
                width: '120',
                align: 'left'
            },
            {
                field: 'remark',
                title: '备注',
                width: '60',
                align: 'left'
            },{
                field: 'specialRemark',
                title: '特批说明',
                width: '60',
                align: 'left'
            },
            {
            field: 'approvalOpinion',
            title: 'SQE审批原因',
            width: '60',
            align: 'left'
            },
            {
                field: 'supplierGenre',
                title: '供应商类型',
                width: 120,
                exportEnum: getDictList('supplier_classify'),
                formatter: function (value) {
                    return getDicName('supplier_classify', value)
                }
            },
            {
                field: 'apprState',
                title: '审批状态',
                width: '60',
                align: 'left',
                exportEnum: [
                    {code: 3, codeWithDesc: '驳回'},
                    {code: 2, codeWithDesc: '同意'},
                    {code: 1, codeWithDesc: '审批中'},
                    {code: 0, codeWithDesc: '新建'}
                ],
                formatter: function (value) {
                    if (value == 3) {
                        return '<span style="color: red">驳回</span>'
                    } else if (value == 2) {
                        return '<span style="color: green">同意</span>'
                    } else if (value == 1) {
                        return '<span style="color: grey">审批中</span>'
                    } else if (value == 0) {
                        return '<span style="color: grey">新建</span>'
                    }
                }
            },
            {
                field: 'oaId',
                title: 'OA流程编号',
                width: '245',
                align: 'left',
                formatter: function (value) {
                    return oaTrack(value, OaProcessType.SUPPLIER_ACCESS);
                }
            },
            {
                field: 'fftt',
                title: '认证报告',
                width: '110',
                align: 'left',
                exportHidden: true,
                formatter: function (value, row) {
                    return "<a href='javascript:void(0)' onclick=\"page.onSiteAuthenticationFilesLookupDialog('" + row.supplierId + "','" + row.purchaseCategoryCode + "','',1)\">" + "点击查看" + "</a>";
                }
            }
        ]]
        $("#tb").datagrid({
            height: document.documentElement.clientHeight - $('#searchForm').outerHeight(),
            width: gridwidth,
            url: g.ctx + 'pc/supplier/purchaseCategory/rest/potentialList',
            singleSelect: false,
            method: "GET",
            pagination: true,
            autoHeight: true,
            loadMsg: "数据加载中......",
            rownumbers: true,
            fitColumns: false,
            striped: true,
            page: 1,
            pageSize: 10,
            columns: column,
            toolbar: toolbar,
            onLoadSuccess: function () {
                displayButtonByUserRole('Potential Supplier Manage');
            }
        });
    },
    /**
     * 查看供应商注册信息
     */
    information: function () {
        let row = $("#tb").datagrid('getSelected');
        if (!row) {
            topWin.layer.msg("请选中一条记录");
            return;
        }
        let id = row.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');
                }
            }]
        });
    },
    information1: function () {
        let row = $("#tb").datagrid('getSelected');
        if (!row) {
            topWin.layer.msg("请选中一条记录");
            return;
        }
        let id = row.supplierId;
        var url = g.ctx + 'pc/supplier/detailPz?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');
                }
            }]
        });
    },

    exportExcel: function () {
        openExportDialog('pc/supplier/purchaseCategory/rest/potentialExport', 'tb', searchParams())
    },
    onSiteAuthenticationFilesLookupDialog: function (id, purchaseCategoryCode,approvalOpinion, readOnly) {
        let url = g.ctx + 'pc/supplier/purchaseCategory/page/siteAuthenticationFile'
        url = url + '?id=' + id + '&purchaseCategoryCode=' + purchaseCategoryCode +'&approvalOpinion='+approvalOpinion
        var buttons = [{
            text: itablei8n.submit, handler: function () {
                topWin.frames["siteAuthenticationScoreDialog"].page.submit(function () {
                    siteAuthenticationScoreDialog.dialog('close');
                    page.initDataGrid.datagrid("reload")
                    $("#tb").datagrid('reload');
                });

            }
        }, {
            text: itablei8n.close, handler: function () {
                siteAuthenticationScoreDialog.dialog('close');
            }
        }]
        if (readOnly) {
            buttons.shift()
        }
        siteAuthenticationScoreDialog = openDialog('siteAuthenticationScoreDialog', url, {
            title: '认证报告',
            width: "750px",
            height: "100%",
            cache: false,
            modal: true,
            border: false,
            draggable: true,
            shadow: false,
            onClose: function () {
                siteAuthenticationScoreDialog.dialog('destroy');
                $("#tb").datagrid('reload');
            },
            buttons: buttons
        });

    },
    sqeScore: function () {
        let row = $("#tb").datagrid('getSelected');
        if (!row) {
            topWin.layer.msg("请选中一条记录");
            return;
        }
        let id = row.supplierId;
        var url = g.ctx + 'pc/supplier/sqescore/page/index?supplierId=' + id
        var sqeScoreDialog = openDialog('sqeScoreDialog', url, {
            title: 'SQE评分',
            width: "90%",
            height: "60%",
            cache: false,
            modal: true,
            border: false,
            draggable: true,
            shadow: false,
            onClose: function () {
                sqeScoreDialog.dialog('destroy');
            },
            buttons: [{
                text: itablei8n.save, handler: function () {
                    topWin.frames["sqeScoreDialog"].page.submit(function () {
                        sqeScoreDialog.dialog('close');
                        page.initDataGrid.datagrid("reload")
                    });

                }
            }, {
                text: itablei8n.close, handler: function () {
                    sqeScoreDialog.dialog('close');
                }
            }]
        });
    }
}
$(function () {
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll,pc/sys/company/rest/listAll')
    initDict("supplier_classify,assess_type")
    page.initDataGrid()
})