import {modals} from "@mantine/modals";
import {Button, Group, Stack, Text} from "@mantine/core";
import {showInfoMessage} from "~/utils/utils.ts";
import type {PerformanceGetListData} from "~/utils/models.ts";

export function confirmExportData(exportObject: PerformanceGetListData[], fileName: string) {
    const onClickExportJson = (download: boolean) => {
        const dataStr = JSON.stringify(exportObject, null, 4)

        const blob = new Blob([dataStr], { type: 'application/json' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        if (download) {
            a.download = `${fileName}_${Date.now()}.json`
        }
        else {
            a.target = '_blank'
        }
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        URL.revokeObjectURL(url)
        showInfoMessage("Data exported successfully", "Export Data")

        modals.closeAll()
    }

    const onClickExportCsv = () => {
        const csvData = exportObject.map(item => {
            // 处理 grpc 数据，去掉 response_data，展开 networking_size
            const grpcData = { ...item.grpc };
            delete grpcData.response_data;
            const grpcFlattened = {
                ...grpcData,
                networking_size_request_size: grpcData.networking_size?.request_size || 0,
                networking_size_response_size: grpcData.networking_size?.response_size || 0
            };
            // @ts-ignore
            delete grpcFlattened.networking_size;


            const restData = { ...item.rest };
            delete restData.response_data;
            const restFlattened = {
                ...restData,
                networking_size_request_size: restData.networking_size?.request_size || 0,
                networking_size_response_size: restData.networking_size?.response_size || 0
            };
            // @ts-ignore
            delete restFlattened.networking_size;

            // 组合最终的行数据
            return {
                idx: item.idx,
                request_count: item.request_count,
                grpc_client_networking_ping: grpcFlattened.client_networking_ping,
                grpc_client_request_cpu: grpcFlattened.client_request_cpu,
                grpc_client_request_time: grpcFlattened.client_request_time,
                grpc_server_deserialize_cpu: grpcFlattened.server_deserialize_cpu,
                grpc_server_deserialize_time: grpcFlattened.server_deserialize_time,
                grpc_server_serialize_cpu: grpcFlattened.server_serialize_cpu,
                grpc_server_serialize_time: grpcFlattened.server_serialize_time,
                grpc_server_protocol_total_time: grpcFlattened.server_protocol_total_time,
                grpc_networking_size_request_size: grpcFlattened.networking_size_request_size,
                grpc_networking_size_response_size: grpcFlattened.networking_size_response_size,

                rest_client_networking_ping: restFlattened.client_networking_ping,
                rest_client_request_cpu: restFlattened.client_request_cpu,
                rest_client_request_time: restFlattened.client_request_time,
                rest_server_deserialize_cpu: restFlattened.server_deserialize_cpu,
                rest_server_deserialize_time: restFlattened.server_deserialize_time,
                rest_server_serialize_cpu: restFlattened.server_serialize_cpu,
                rest_server_serialize_time: restFlattened.server_serialize_time,
                rest_server_protocol_total_time: restFlattened.server_protocol_total_time,
                rest_networking_size_request_size: restFlattened.networking_size_request_size,
                rest_networking_size_response_size: restFlattened.networking_size_response_size,
            };
        });


        const headers = [
            'idx',
            'request_count',
            'grpc_client_networking_ping',
            'grpc_client_request_cpu',
            'grpc_client_request_time',
            'grpc_server_deserialize_cpu',
            'grpc_server_deserialize_time',
            'grpc_server_serialize_cpu',
            'grpc_server_serialize_time',
            'grpc_server_protocol_total_time',
            'grpc_networking_size_request_size',
            'grpc_networking_size_response_size',
            'rest_client_networking_ping',
            'rest_client_request_cpu',
            'rest_client_request_time',
            'rest_server_deserialize_cpu',
            'rest_server_deserialize_time',
            'rest_server_serialize_cpu',
            'rest_server_serialize_time',
            'rest_server_protocol_total_time',
            'rest_networking_size_request_size',
            'rest_networking_size_response_size'
        ];

        // 生成 CSV 内容
        const csvContent = [
            headers.join(','),
            ...csvData.map(row =>
                headers.map(header => {
                    return row[header as keyof typeof row];
                }).join(',')
            )
        ].join('\n');

        const BOM = '\uFEFF';
        const csvWithBOM = BOM + csvContent;

        const blob = new Blob([csvWithBOM], { type: 'text/csv;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${fileName}_${Date.now()}.csv`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);

        showInfoMessage("Data exported successfully", "Export Data");
        modals.closeAll();
    };

    modals.open({
        title: "Export Performance Test Data",
        centered: true,
        children: (
            <Stack>
                <Text>Export Performance Test Data</Text>
                <Group>
                    <Button onClick={() => onClickExportJson(true)}>Download Json</Button>
                    <Button onClick={() => onClickExportJson(false)}>Preview Json</Button>
                    <Button onClick={() => onClickExportCsv()}>CSV</Button>
                </Group>
                <Group mt="md" justify="flex-end">
                    <Button onClick={() => modals.closeAll()}>Cancel</Button>
                </Group>
            </Stack>
        )
    })
}

