// src/utils/chartUtils.ts
import * as echarts from 'echarts'

// 设备状态类型定义
export interface DeviceStatusRecord {
    工位号: string
    设备状态: string
    创建时间: string
}

export interface DeviceStatusConfig {
    value: string
    label: string
    color: string
}

export interface ChartSegment {
    itemStyle: {
        normal: {
            color: string
        }
    }
    name: string
    value: [number, string, string]
}

// 设备状态配置
export const DEVICE_STATUS_CONFIG: DeviceStatusConfig[] = [
    { value: '-1', label: '关机', color: '#9E9E9E' },
    { value: '0', label: '待机', color: '#FFC107' },
    { value: '1', label: '运行', color: '#4CAF50' },
    { value: '2', label: '报警', color: '#F44336' },
]

export const DEVICE_STATUS_COLORS = ['#9E9E9E', '#FFC107', '#4CAF50', '#F44336']
export const DEVICE_STATUS_LABELS = ['关机', '待机', '运行', '报警']

// 格式化日期时间
export const formatDateTime = (date: Date): string => {
    const pad = (n: number) => n.toString().padStart(2, '0')
    return (
        date.getFullYear() +
        '-' +
        pad(date.getMonth() + 1) +
        '-' +
        pad(date.getDate()) +
        ' ' +
        pad(date.getHours()) +
        ':' +
        pad(date.getMinutes()) +
        ':' +
        pad(date.getSeconds())
    )
}

// 状态映射
export const getStatusMap = (): Record<string, { name: string; color: string }> => {
    const statusMap: Record<string, { name: string; color: string }> = {}
    DEVICE_STATUS_CONFIG.forEach(status => {
        statusMap[status.value] = {
            name: status.label,
            color: status.color
        }
    })
    return statusMap
}

// 处理设备状态数据，生成图表数据段
export const processDeviceStatusData = (data: DeviceStatusRecord[]): ChartSegment[] => {
    const statusMap = getStatusMap()
    const segments: ChartSegment[] = []

    // 按时间排序
    const sortedData = [...data].sort(
        (a, b) => new Date(a.创建时间).getTime() - new Date(b.创建时间).getTime()
    )

    let lastStatus: string | null = null
    let segmentStart: string | null = null

    // 处理连续状态段
    sortedData.forEach((record, index) => {
        const currentStatus = record.设备状态?.toString()
        const currentTime = new Date(record.创建时间)

        if (currentStatus !== lastStatus) {
            // 结束上一个段
            if (lastStatus !== null && segmentStart !== null) {
                const statusInfo = statusMap[lastStatus] || { name: '未知', color: 'blue' }
                segments.push({
                    itemStyle: {
                        normal: {
                            color: statusInfo.color,
                        },
                    },
                    name: statusInfo.name,
                    value: [0, segmentStart, record.创建时间],
                })
            }

            // 开始新段
            segmentStart = record.创建时间
            lastStatus = currentStatus
        }

        // 处理最后一段
        if (index === sortedData.length - 1 && segmentStart !== null && lastStatus !== null) {
            const statusInfo = statusMap[lastStatus] || { name: '未知', color: 'blue' }
            const endTime = new Date(segmentStart)
            endTime.setMinutes(endTime.getMinutes() + 1) // 最后一段延长1分钟显示

            segments.push({
                itemStyle: {
                    normal: {
                        color: statusInfo.color,
                    },
                },
                name: statusInfo.name,
                value: [0, segmentStart, endTime.toISOString()],
            })
        }
    })

    return segments
}

// 生成模拟数据
export const generateMockData = (): DeviceStatusRecord[] => {
    const mockData: DeviceStatusRecord[] = []
    const now = new Date()

    for (let i = 0; i < 24; i++) {
        const time = new Date(now)
        time.setHours(now.getHours() - 23 + i)

        // 模拟不同的设备状态
        let status = '1' // 默认运行
        if (i < 2) status = '-1' // 前2小时关机
        else if (i < 6) status = '0' // 接下来4小时待机
        else if (i === 10) status = '2' // 第10小时报警
        else if (i > 18) status = '-1' // 最后几小时关机

        mockData.push({
            工位号: '模拟设备',
            设备状态: status,
            创建时间: time.toISOString(),
        })
    }

    return mockData
}

// 获取默认图表数据（用于无数据时显示）
export const getDefaultChartData = (): ChartSegment[] => {
    const now = new Date()
    const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000)

    return [
        {
            itemStyle: {
                normal: {
                    color: '#4CAF50',
                },
            },
            name: '运行',
            value: [0, oneHourAgo.toISOString(), now.toISOString()],
        },
    ]
}

// 初始化图表配置
export const getChartOption = (): echarts.EChartsOption => {
    return {
        color: DEVICE_STATUS_COLORS,
        tooltip: {
            formatter: (params: any) => {
                const statusMap = getStatusMap()
                const statusName = statusMap[params.name]?.name || params.name
                const startTime = params.value[1] ? new Date(params.value[1]).toLocaleTimeString() : ''
                const endTime = params.value[2] ? new Date(params.value[2]).toLocaleTimeString() : ''
                return `${statusName}: ${startTime} ~ ${endTime}`
            },
        },
        grid: {
            left: '10%',
            right: '5%',
            top: '15%',
            bottom: '15%',
            containLabel: true,
        },
        legend: {
            data: DEVICE_STATUS_LABELS,
            selectedMode: false,
            textStyle: {
                color: '#ffffff',
                fontSize: 10,
            },
            itemWidth: 10,
            itemHeight: 10,
            top: '0%',
            right: '10%',
        },
        xAxis: {
            type: 'time',
            axisLine: {
                lineStyle: {
                    color: '#ffffff',
                },
            },
            axisTick: {
                show: true,
                lineStyle: {
                    color: '#ffffff',
                },
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.3)',
                    width: 1,
                    type: 'dashed',
                },
            },
            axisLabel: {
                color: '#ffffff',
                fontSize: 10,
                formatter: (value: number) => {
                    const date = new Date(value)
                    return `${date.getHours().toString().padStart(2, '0')}:${date
                        .getMinutes()
                        .toString()
                        .padStart(2, '0')}`
                },
            },
        },
        yAxis: {
            type: 'category',
            data: ['设备运行履历'],
            axisLine: {
                lineStyle: {
                    color: '#ffffff',
                },
            },
            axisTick: {
                show: true,
                lineStyle: {
                    color: '#ffffff',
                },
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.3)',
                    width: 1,
                    type: 'solid',
                },
            },
            axisLabel: {
                color: '#ffffff',
                fontSize: 12,
            },
        },
        series: [
            { name: '关机', type: 'bar', data: [] },
            { name: '待机', type: 'bar', data: [] },
            { name: '运行', type: 'bar', data: [] },
            { name: '报警', type: 'bar', data: [] },
            {
                type: 'custom',
                renderItem: (params: any, api: any) => {
                    const categoryIndex = api.value(0)
                    const start = api.coord([api.value(1), categoryIndex])
                    const end = api.coord([api.value(2), categoryIndex])
                    const height = 20

                    return {
                        type: 'rect',
                        shape: {
                            x: start[0],
                            y: start[1] - height / 2,
                            width: end[0] - start[0],
                            height: height,
                        },
                        style: api.style(),
                    }
                },
                encode: {
                    x: [1, 2],
                    y: 0,
                },
                data: [],
            },
        ],
    }
}