<template>
    <div class="device-control">
        <!--指标拟合图 -->
        <div v-show="fullscreen">
            <PointTree :height="flag ? 106 : 50" @node-click="nodeClick" @pointTypeChange="pointTypeChange"></PointTree>
        </div>
        <div>
            <TableHeader datePicker @selectChange="selectChange" v-if="fullscreen" ref="TableHeaderRef"
                :timeKeyList="prop.timeKey">
                <template v-slot:select>
                    <!-- <el-form-item label="监测点">
                        <el-select filterable v-model="tableStore.table.params.lineId" placeholder="请选择监测点" clearable>
                            <el-option v-for="item in lineList" :key="item.lineId" :label="item.name"
                                :value="item.lineId" />
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="用户功率">
                        <el-select filterable v-model="tableStore.table.params.power" placeholder="请选择用户功率" clearable>
                            <el-option v-for="item in powerList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="统计类型">
                        <el-select style="min-width: 120px !important" placeholder="请选择"
                            v-model="tableStore.table.params.valueType" filterable>
                            <el-option value="max" label="最大值"></el-option>
                            <el-option value="min" label="最小值"></el-option>
                            <el-option value="avg" label="平均值"></el-option>
                            <el-option value="cp95" label="cp95"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="电能质量指标">
                        <el-select filterable v-model="tableStore.table.params.indicator" placeholder="请选择电能质量指标"
                            clearable>
                            <el-option v-for="item in indicatorList" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <div v-if="shouldShowHarmonicCount()"
                            style="display: flex; color: var(--el-text-color-regular)">
                            <span style="width: 160px">{{ getHarmonicTypeName() }}谐波次数</span>
                            <el-select v-model="tableStore.table.params.harmonicCount" placeholder="请选择谐波次数"
                                style="min-width: 80px !important" filterable>
                                <el-option v-for="num in harmonicCountOptions" :key="num" :label="num"
                                    :value="num"></el-option>
                            </el-select>
                        </div>
                    </el-form-item>
                </template>
            </TableHeader>

            <div v-loading="tableStore.table.loading">
                <my-echart class="tall" v-if="lineShow" :options="echartList" :style="{
                    width: `calc(${prop.width} - ${fullscreen ? 290 : 0}px)`,
                    height: `calc(${prop.height} - ${headerHeight}px + ${fullscreen ? 0 : 56}px )`
                }" />
                <el-empty v-else description="暂无监测点" :style="{
                    width: `calc(${prop.width} - ${fullscreen ? 290 : 0}px)`,
                    height: `calc(${prop.height} - ${headerHeight}px + ${fullscreen ? 0 : 56}px)`
                }" />
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, reactive, watch, h, computed, nextTick } from 'vue'
import TableStore from '@/utils/tableStore'
import TableHeader from '@/components/table/header/index.vue'
import MyEchart from '@/components/echarts/MyEchart.vue'
import { useConfig } from '@/stores/config'
import { cslineList, fittingData } from '@/api/harmonic-boot/cockpit/cockpit'
import { queryByCode, queryCsDictTree } from '@/api/system-boot/dictTree'
import { ElMessage } from 'element-plus'
import { getTime } from '@/utils/formatTime'
import { exportSeriesCSV } from '@/utils/echartMethod'
import PointTree from '@/components/tree/govern/pointTree.vue'

const CSV_DOWNLOAD_ICON =
    'path://M896 346.8c-0.1 0 0 0 0 0 0-0.9-0.1-1.7-0.2-2.5 0-0.1 0-0.3-0.1-0.4-0.2-1.7-0.5-3.3-1-4.9-0.5-1.7-1-3.3-1.7-4.9v-0.1c-0.3-0.8-0.7-1.5-1.1-2.3v-0.1c-0.4-0.7-0.8-1.5-1.2-2.2-0.1-0.1-0.1-0.2-0.2-0.3-0.4-0.6-0.8-1.2-1.3-1.9-0.1-0.1-0.1-0.2-0.2-0.2-0.5-0.6-1-1.3-1.5-1.9-0.1-0.1-0.2-0.3-0.4-0.4-0.5-0.6-1-1.2-1.6-1.7l-0.1-0.1L637.3 74.5c-0.6-0.6-1.2-1.1-1.8-1.6-0.1-0.1-0.3-0.2-0.4-0.4-0.6-0.5-1.2-1-1.9-1.5-0.1 0-0.1-0.1-0.2-0.1-0.6-0.5-1.3-0.9-1.9-1.3-0.1-0.1-0.2-0.1-0.3-0.2-0.7-0.4-1.4-0.9-2.2-1.3-0.8-0.4-1.5-0.8-2.3-1.1h-0.1c-1.6-0.7-3.2-1.3-4.9-1.7-1.6-0.4-3.2-0.8-4.9-1-0.1 0-0.3 0-0.4-0.1-1.4-0.2-2.8-0.3-4.3-0.3H164c-19.9 0-36 16.1-36 36v823.3c0 19.9 16.1 36 36 36h696c19.9 0 36-16.1 36-36V348.6v-1.8zM647.8 186.9l125.4 125.6H647.8V186.9zM200 887.2V135.9h375.8v212.7c0 19.9 16.1 36 36 36H824v502.7H200zM363.5 661.5c-7.2 6.3-15.8 9.5-25.8 9.5-13.5 0-24.5-5-33-15S292 629.3 292 605.7c0-22.2 4.3-38.2 12.9-48.1 8.6-9.9 19.8-14.9 33.6-14.9 10 0 18.5 2.8 25.5 8.4s11.6 13.2 13.8 22.9l37.2-8.9c-4.2-14.9-10.6-26.3-19-34.3-14.2-13.5-32.7-20.2-55.5-20.2-26.1 0-47.1 8.6-63.1 25.7s-24 41.2-24 72.2c0 29.3 8 52.4 23.9 69.3 15.9 16.9 36.2 25.3 60.9 25.3 20 0 36.5-4.9 49.4-14.8 13-9.9 22.3-24.9 27.9-45.3L379 631.6c-3.1 13.6-8.3 23.6-15.5 29.9zM561.5 597.2c-8.8-4.6-22.3-9.1-40.6-13.4s-29.8-8.5-34.5-12.4c-3.7-3.1-5.6-6.9-5.6-11.3 0-4.8 2-8.7 6-11.6 6.2-4.5 14.7-6.7 25.6-6.7 10.6 0 18.5 2.1 23.8 6.3 5.3 4.2 8.7 11.1 10.3 20.6l37.6-1.7c-0.6-17.1-6.8-30.8-18.6-41s-29.4-15.4-52.7-15.4c-14.3 0-26.5 2.2-36.6 6.5-10.1 4.3-17.9 10.6-23.2 18.9-5.4 8.3-8.1 17.1-8.1 26.6 0 14.7 5.7 27.2 17.1 37.5 8.1 7.3 22.3 13.4 42.4 18.4 15.7 3.9 25.7 6.6 30.1 8.1 6.4 2.3 10.9 5 13.5 8.1 2.6 3.1 3.9 6.8 3.9 11.2 0 6.9-3.1 12.8-9.2 18-6.1 5.1-15.3 7.7-27.4 7.7-11.4 0-20.5-2.9-27.2-8.6-6.7-5.8-11.2-14.8-13.4-27l-36.6 3.6c2.5 20.8 10 36.7 22.6 47.5 12.6 10.9 30.7 16.3 54.2 16.3 16.2 0 29.7-2.3 40.5-6.8s19.2-11.4 25.1-20.8c5.9-9.3 8.9-19.3 8.9-30 0-11.8-2.5-21.6-7.4-29.6s-11.7-14.3-20.5-19zM689.9 651.6l-47.1-137.7h-40.7L668.6 700h40.1l66.7-186.1h-39.9z'

const prop = defineProps({
    w: { type: [String, Number] },
    h: { type: [String, Number] },
    width: { type: [String, Number] },
    height: { type: [String, Number] },
    timeKey: { type: Array as () => string[] },
    timeValue: { type: Object },
    interval: { type: Number },
    flag: { type: Boolean }
})

const TableHeaderRef = ref()

const config = useConfig()

const lineList: any = ref()

const powerList: any = ref()

const chartsList = ref<any>([])
const lineShow = ref(true)
// 计算是否全屏展示
const fullscreen = computed(() => {
    const w = Number(prop.w)
    const h = Number(prop.h)


    if (!isNaN(w) && !isNaN(h) && w === 12 && h === 6) {
        // 执行相应逻辑
        return true
    } else {
        return false
    }
})
const exceedingTheLimitList: any = ref([
    {
        label: '越限',
        value: '1'
    },
    {
        label: '不越限',
        value: '0'
    }
])

const indicatorList = ref()

// const initLineList = async () => {
//     cslineList({}).then(res => {
//         setTime()
//         if (res.data.length == 0) {
//             lineShow.value = false
//             return (tableStore.table.loading = false)
//         }
//         lineShow.value = true
//         lineList.value = res.data
//         tableStore.table.params.lineId = lineList.value[0].lineId
//         initCode()
//     })
// }
const nodeClick = (e: any) => {
    if (e == undefined) {
    }
    if (e.level == 3) {
        tableStore.table.params.lineId = e.id
        initCode()
    }
}
const pointTypeChange = (val: any, obj: any) => {
    nodeClick(obj)
}

const echartList = ref()

const headerHeight = ref(57)
const selectChange = (showSelect: any, height: any, datePickerValue?: any) => {
    headerHeight.value = height
    if (datePickerValue && datePickerValue.timeValue) {
        // 更新时间参数
        tableStore.table.params.searchBeginTime = datePickerValue.timeValue[0]
        tableStore.table.params.searchEndTime = datePickerValue.timeValue[1]
    }
}

const formatExceedanceValue = (value: any) => {
    if (value == 0) return '不越限'
    if (value == 1) return '越限'
    return value
}

const getSeriesForCsvExport = () => {
    const indicatorSeriesName = indicatorList.value?.find(
        (item: any) => item.id === tableStore.table.params.indicator
    )?.name
    return echartList.value.options.series.map((item: any) => ({
        name: item.name,
        data: item.data?.map((point: any) => [
            point[0],
            item.name === indicatorSeriesName ? formatExceedanceValue(point[1]) : point[1],
            point[2]
        ])
    }))
}

const setEchart = () => {
    // 获取当前选择的功率和指标名称
    const powerName = powerList.value?.find((item: any) => item.id === tableStore.table.params.power)?.name || '功率'
    const indicatorName =
        indicatorList.value?.find((item: any) => item.id === tableStore.table.params.indicator)?.name || '电能质量指标'

    const chartTitle = `${indicatorName}与${powerName}负荷曲线拟合图`

    echartList.value = {
        title: {
            text: chartTitle
        },
        toolbox: {
            featureProps: {
                myTool1: {
                    show: true,
                    title: '下载csv',
                    icon: CSV_DOWNLOAD_ICON,
                    onclick: () => {
                        exportSeriesCSV(
                            getSeriesForCsvExport(),
                            `${echartList.value.title?.text || '负荷曲线拟合图'}.csv`
                        )
                    }
                }
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params: any) {
                let result = params[0].axisValueLabel
                params.forEach((item: any) => {
                    if (item.seriesName === indicatorName) {
                        // 对于电能质量指标，格式化Y轴值显示
                        let valueText = formatExceedanceValue(item.value[1])
                        if (valueText === item.value[1]) {
                            valueText = item.value[1]
                        }
                        result += `<br/>${item.marker}${item.seriesName}: ${valueText}`
                    } else {
                        // 对于功率数据，正常显示数值
                        result += `<br/>${item.marker}${item.seriesName}: ${item.value[1]} ${item.value[2]}`
                    }
                })
                return result
            }
        },
        xAxis: {
            type: 'time',
            axisLabel: {
                formatter: {
                    day: '{MM}-{dd}',
                    month: '{MM}',
                    year: '{yyyy}'
                }
            }
        },
        yAxis: [
            {},
            indicatorName
                ? {
                    min: 0,
                    max: 1,
                    axisLabel: {
                        formatter: function (value: number) {
                            if (value === 0) {
                                return '不越限'
                            } else if (value === 1) {
                                return '越限'
                            }
                            return value
                        }
                    }
                }
                : {}
        ],
        // grid: {
        //     left: '10px',
        //     right: '30px',
        // },
        options: {
            // dataZoom: [
            //     {
            //         type: 'inside',
            //         start: 0,
            //         end: 100,
            //         filterMode: 'filter'
            //     },
            //     {
            //         type: 'slider',
            //         start: 0,
            //         end: 100,
            //         height: 13,
            //         bottom: '20px',
            //         filterMode: 'filter'
            //     }
            // ],
            series: [
                {
                    type: 'bar',
                    name: powerName, // 动态设置功率名称
                    data: [],
                    clip: true,
                    itemStyle: {
                        normal: {
                            color: function (params: any) {
                                if (params.value[1] == 0 || params.value[1] == 3.14159) {
                                    return '#ccc'
                                } else {
                                    return config.layout.elementUiPrimary[0]
                                }
                            }
                        }
                    },
                    yAxisIndex: 0
                },
                {
                    name: indicatorName, // 动态设置指标名称
                    type: 'line',
                    step: 'end',
                    showSymbol: false,
                    clip: true,
                    data: [],
                    yAxisIndex: 1
                }
            ]
        }
    }

    try {
        // 用户功率数据和电能质量数据
        let powerData: any[] = []
        let qualityData: any[] = []

        chartsList.value.forEach((item: any) => {
            // 根据统计项ID判断是功率数据还是电能质量数据
            if (item.statisticalIndex === tableStore.table.params.power) {
                powerData.push(item)
            } else if (item.statisticalIndex === tableStore.table.params.indicator) {
                qualityData.push(item)
            }
        })

        // 处理功率数据
        const processedPowerData = powerData.map((item: any) => {
            return [
                item.time,
                item.statisticalData !== null && item.statisticalData !== undefined
                    ? parseFloat(item.statisticalData.toFixed(2))
                    : null,
                item.unit
            ]
        })

        // 处理电能质量数据
        const processedQualityData = qualityData.map((item: any) => {
            return [
                item.time,
                item.statisticalData !== null && item.statisticalData !== undefined
                    ? parseFloat(item.statisticalData.toFixed(2))
                    : null,
                item.unit
            ]
        })

        // 检查是否有有效数据
        const hasPowerData = processedPowerData.length > 0 && processedPowerData.some(item => item[1] !== null)
        const hasQualityData = processedQualityData.length > 0 && processedQualityData.some(item => item[1] !== null)

        // 更新图表配置
        echartList.value.options.series[0].data = processedPowerData
        echartList.value.options.series[1].data = processedQualityData
    } catch (error) {
        console.error('处理图表数据时出错:', error)
    }
}

const initCode = () => {
    queryByCode('steady_state_limit_fitting').then(res => {
        queryCsDictTree(res.data.id).then(item => {
            powerList.value = item.data.filter((item: any) => {
                return item.name == '三相总无功功率' || item.name == '三相总有功功率'
            })

            indicatorList.value = item.data.filter((item: any) => {
                return item.name != '三相总无功功率' && item.name != '三相总有功功率'
            })

            tableStore.table.params.power = powerList.value[0].id
            tableStore.table.params.indicator = indicatorList.value[0].id
            nextTick(() => {
                // setTime()
                tableStore.index()
            })
        })
    })
}

const tableStore: any = new TableStore({
    url: '/cs-device-boot/csGroup/fittingData',
    method: 'POST',
    showPage: false,
    exportName: '主要监测点列表',
    column: [],
    beforeSearchFun: () => {
        setTime()
        // 只有当 lineList 已加载且有数据时才设置默认 lineId
        if (!tableStore.table.params.lineId && lineList.value && lineList.value.length > 0) {
            tableStore.table.params.lineId = lineList.value[0].lineId
        }

        // 构建请求参数 lists
        let lists: any = []

        // 处理用户功率指标
        const selectedPower = powerList.value?.find((item: any) => item.id === tableStore.table.params.power)
        if (selectedPower) {
            lists.push({
                statisticalId: tableStore.table.params.power,
                valueType: tableStore.table.params.valueType
            })
        }

        // 处理电能质量指标
        const selectedIndicator = indicatorList.value?.find(
            (item: any) => item.id === tableStore.table.params.indicator
        )
        if (selectedIndicator) {
            let frequencys = ''
            if (selectedIndicator.name.includes('谐波含有率')) {
                frequencys = tableStore.table.params.harmonicCount
            }

            lists.push({
                statisticalId: tableStore.table.params.indicator,
                frequency: frequencys !== null && frequencys !== undefined ? String(frequencys) : ''
            })
        }

        // 将 lists 添加到请求参数中
        tableStore.table.params.list = lists
        tableStore.table.params.dataLevel = 'Primary'
    },
    loadCallback: () => {
        tableStore.table.height = `calc(${prop.height} - 80px)`
        // 数据加载完成后的处理
        if (tableStore.table.data) {
            chartsList.value = JSON.parse(JSON.stringify(tableStore.table.data))
            setEchart()
        }
    }
})

const tableRef = ref()
provide('tableRef', tableRef)
tableStore.table.params.indicator = '1'
tableStore.table.params.exceedingTheLimit = '1'
tableStore.table.params.valueType = 'avg'
tableStore.table.params.searchValue = ''
provide('tableStore', tableStore)

// 添加谐波次数选项（2-50）
const harmonicCountOptions = ref(Array.from({ length: 49 }, (_, i) => i + 2))

// 判断是否应该显示谐波次数选择框
const shouldShowHarmonicCount = () => {
    if (!tableStore.table.params.indicator || !indicatorList.value) return false

    const currentIndicator = indicatorList.value.find((item: any) => item.id === tableStore.table.params.indicator)

    return (
        currentIndicator &&
        (currentIndicator.name.includes('电压谐波含有率') || currentIndicator.name.includes('电流谐波含有率'))
    )
}

// 获取谐波类型名称
const getHarmonicTypeName = () => {
    const currentIndicator = indicatorList.value.find((item: any) => item.id === tableStore.table.params.indicator)

    if (currentIndicator) {
        if (currentIndicator.name.includes('电压谐波含有率')) {
            return '电压'
        } else if (currentIndicator.name.includes('电流谐波含有率')) {
            return '电流'
        }
    }
    return ''
}

// 监听指标变化，当指标变化时重置谐波次数
watch(
    () => tableStore.table.params.indicator,
    newVal => {
        if (shouldShowHarmonicCount()) {
            // 如果之前没有设置过谐波次数，则默认设置为2
            if (!tableStore.table.params.harmonicCount) {
                tableStore.table.params.harmonicCount = 2
            }
        } else {
            // 如果不是谐波含有率指标，则清除谐波次数设置
            tableStore.table.params.harmonicCount = ''
        }
    }
)

onMounted(async () => {
    // await initCode()
})

watch(
    () => prop.timeKey,
    val => {
        tableStore.index()
    }
)
const setTime = () => {
    const time = getTime(
        (TableHeaderRef.value?.datePickerRef.interval || prop.interval) ?? 0,
        prop.timeKey,
        fullscreen.value
            ? [tableStore.table.params.searchBeginTime, tableStore.table.params.searchEndTime]
            : prop.timeValue
    )

    if (Array.isArray(time)) {
        tableStore.table.params.searchBeginTime = time[0]
        tableStore.table.params.searchEndTime = time[1]
        TableHeaderRef.value?.setInterval(time[2] - 0)
        TableHeaderRef.value?.setTimeInterval([time[0], time[1]])
    } else {
        console.warn('获取时间失败，time 不是一个有效数组')
    }
}

watch(
    () => prop.timeValue,
    (newVal, oldVal) => {
        tableStore.index()
    },
    {
        deep: true
    }
)
</script>
<style lang="scss" scoped>
// :deep(.el-select) {
//     min-width: 80px;
// }
.device-control {
    display: flex;
}

:deep(.cn-tree) {
    padding: 0 10px 0 0 !important;
}
</style>
