<template>
    <!-- 指标日趋势图 -->
    <el-dialog draggable :title="dialogTitle" v-model="dialogVisible" append-to-body width="70%">
        <div :style="pageHeight">
            <my-echart class="tall" :options="echartList" style="width: 100%" />
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, provide, reactive, watch, h } from 'vue'
import MyEchart from '@/components/echarts/MyEchart.vue'
import { useConfig } from '@/stores/config'
import { mainHeight } from '@/utils/layout'
import { limitExtentDayData } from '@/api/harmonic-boot/cockpit/cockpit'
import { yMethod } from '@/utils/echartMethod'
const prop = defineProps({
    width: { type: [String, Number] },
    height: { type: [String, Number] },
    timeKey: { type: Array as () => string[] },
    timeValue: { type: Object }
})

const pageHeight = mainHeight(0, 2)

const dialogVisible: any = ref(false)

const dialogTitle = ref('')

const config = useConfig()

const dialogText = ref('')

const echartList = ref()

const init = () => {
    echartList.value = {
        title: {
            text: dialogText.value
        },
        legend: {
            itemWidth: 20,
            itemHeight: 20,
            itemStyle: { opacity: 0 }, //去圆点
            right: 70
        },
        tooltip: {
            trigger: 'axis',
            formatter: (params: any) => {
                if (!params || params.length === 0) return ''

                // 使用第一个项目的轴标签作为时间标题
                let tooltipText = params[0].axisValueLabel + '<br/>'

                // 遍历所有项目并累加到tooltipText中
                params.forEach((item: any) => {
                    // 将数值格式化为保留两位小数
                    const formattedValue = Math.round(item.value[1] * 100) / 100
                    tooltipText += `${item.marker} ${item.seriesName}: ${formattedValue}<br/>`
                })

                return tooltipText
            }
        },
        xAxis: {
            type: 'time',
            axisLabel: {
                formatter: {
                    day: '{MM}-{dd}',
                    month: '{MM}',
                    year: '{yyyy}'
                }
            }
        },

        yAxis: {},

        options: {
            series: []
        }
    }
}

const initData = async (row: any) => {
    limitExtentDayData({ code: row.code, lineId: row.lineId, time: row.time }).then(res => {
        if (res.data && res.data.length > 0) {
            // 重新初始化图表
            init()
            let [min, max] = yMethod(res.data.map((item: any) => item.value.split(',')).flat())

            // 从第一条数据中提取时间作为x轴数据

            // 定义相位颜色映射
            const phaseColors: any = {
                A: '#DAA520',
                B: '#2E8B57',
                C: '#A52a2a'
            }

            // 处理每条相位数据
            const seriesData = res.data
                .filter(item => item.valueType == 'max')
                .sort((a, b) => {
                    return a.phasic.localeCompare(b.phasic)
                })
                .map((item: any) => {
                    const xAxisData = item.time.split(',')
                    const values = xAxisData.map((time: string, index: number) => {
                        // 将传入的日期与时间拼接成完整的时间字符串
                        const fullTime = `${row.time} ${time}`
                        const value = parseFloat(item.value.split(',')[index]) || 0
                        return [fullTime, value]
                    })

                    return {
                        name: `${item.phasic}相`,
                        type: 'line',
                        showSymbol: false,
                        smooth: true,
                        data: values,
                        itemStyle: {
                            normal: {
                                // 根据相位设置对应颜色
                                color: phaseColors[item.phasic] || config.layout.elementUiPrimary[0]
                            }
                        }
                    }
                })
            echartList.value.yAxis.max = max
            echartList.value.yAxis.min = min
            // 更新图表配置
            echartList.value.options.series = seriesData
            // 注意：使用时间轴时不需要设置 xAxis.data
        }
    })
}
onMounted(() => {})

const open = async (row: any) => {
    dialogVisible.value = true
    dialogTitle.value = row.name + '日趋势图'
    dialogText.value = `监测点名称:${row.lineName}　越限时间:${row.time}　指标名称:${row.name}`
    nextTick(() => {
        initData(row)
    })
}

defineExpose({ open })
</script>
<style lang="scss" scoped>
:deep(.el-select) {
    min-width: 80px;
}
</style>
