<template>
    <div v-show="!isWaveCharts" class="event-statistics-curve" :style="pageHeight">
        <TableHeader ref="TableHeaderRef" :showReset="false" :timeKeyList="timeKeyList" datePicker
            @selectChange="selectChange"> <template v-slot:operation>
                <el-button icon="el-icon-Back" @click="handleBack">返回</el-button>
            </template>
        </TableHeader>
        <el-descriptions class="mt2" direction="vertical" :column="4" border>
            <el-descriptions-item align="center" label="名称">{{ data.name }}</el-descriptions-item>
            <el-descriptions-item align="center" label="事件总数">{{ data.gs }}</el-descriptions-item>
            <el-descriptions-item align="center" label="可容忍">{{ data.krr }}</el-descriptions-item>
            <el-descriptions-item align="center" label="不可容忍">{{ data.bkrr }}</el-descriptions-item>
        </el-descriptions>
        <my-echart v-loading="tableStore.table.loading" ref="chartRef" class="tall" :options="echartList"
            :style="chartStyle" @chart-click="handleChartClick" />
    </div>
    <waveFormAnalysis v-loading="loading" v-if="isWaveCharts" ref="waveFormAnalysisRef"
        @handleHideCharts="isWaveCharts = false" :wp="wp" />
</template>

<script setup lang="ts">
import { ref, onMounted, provide, reactive, computed, nextTick, inject } from 'vue'
import TableStore from '@/utils/tableStore'
import MyEchart from '@/components/echarts/MyEchart.vue'
import waveFormAnalysis from '@/views/govern/device/control/tabs/components/waveFormAnalysis.vue'
import TableHeader from '@/components/table/header/index.vue'
import { analyseWave } from '@/api/common'
import { getTime } from '@/utils/formatTime'
import { mainHeight } from '@/utils/layout'
import { ElMessage } from 'element-plus'
const pageHeight = mainHeight(105)
const eventStatisticsBack = inject<() => void>('eventStatisticsBack', () => {})
const handleBack = () => eventStatisticsBack()
const timeKeyList = ['1', '2', '3', '4', '5']
const defaultInterval = 3

const TableHeaderRef = ref()
const headerHeight = ref(57)
const echartList = ref()
const chartRef = ref()
const isWaveCharts = ref(false)
const loading = ref(false)
const wp = ref({})
const boxoList: any = ref({})
const waveFormAnalysisRef: any = ref(null)

const chartStyle = computed(() => ({
    width: '100%',
    height: `calc(${pageHeight.height} - 80px - ${headerHeight.value}px)`
}))

const data = reactive({
    name: '事件个数',
    gs: 0,
    krr: 0,
    bkrr: 0
})

const tableStore: any = new TableStore({
    url: '/cs-harmonic-boot/csevent/f47Curve',
    method: 'POST',
    showPage: false,
    column: [],
    beforeSearchFun: () => {
        setTime()
    },
    loadCallback: () => {
        const gongData = gongfunction(tableStore.table.data)
        data.gs = tableStore.table.data.length
        data.krr = gongData.pointF.length
        data.bkrr = gongData.pointFun.length
        echartList.value = {
            title: {
                text: 'F47曲线'
            },
            legend: {
                data: ['分割线', '可容忍事件', '不可容忍事件'],
                itemGap: 15
            },
            tooltip: {
                trigger: 'item',
                show: true,
                axisPointer: {
                    type: 'shadow',
                    label: {
                        color: '#fff',
                        fontSize: 16
                    }
                },
                textStyle: {
                    color: '#fff',
                    fontStyle: 'normal',
                    opacity: 0.35,
                    fontSize: 14
                },
                backgroundColor: 'rgba(0,0,0,0.55)',
                borderWidth: 0,
                formatter: function (a: any) {
                    let relVal = `<strong>${a.seriesName}</strong><br/>`
                    relVal += "<font style='color:" + "'>发生时间：" + a.value[2] + '</font><br/>'
                    relVal += "<font style='color:" + "'>特征幅值：" + Math.floor(a.value[1] * 100) / 100 + '%</font><br/>'
                    relVal += "<font style='color:" + "'>持续时间：" + a.value[0] + 's</font><br/>'
                    relVal += "<font style='color:" + "'>监测点名称：" + (a.value[4] || '/') + '</font><br/>'
                    relVal += "<font style='color:" + "'>设备名称：" + (a.value[5] || '/') + '</font><br/>'
                    relVal += "<font style='color:" + "'>项目名称：" + (a.value[6] || '/') + '</font><br/>'
                    relVal += "<font style='color:" + "'>工程名称：" + (a.value[7] || '/') + '</font>'
                    return relVal
                }
            },
            xAxis: [
                {
                    type: 'log',
                    min: 0.001,
                    max: 1000,
                    splitLine: {
                        show: false
                    },
                    name: 's'
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '%'
                }
            ],
            color: ['#DAA520', 'green', 'red'],
            options: {
                dataZoom: null,
                series: [
                    {
                        name: '分割线',
                        type: 'line',
                        data: [
                            [0.05, 0],
                            [0.05, 50],
                            [0.2, 50],
                            [0.2, 70],
                            [0.5, 70],
                            [0.5, 80],
                            [10, 80],
                            [1000, 80]
                        ],
                        showSymbol: false,
                        tooltips: {
                            show: false
                        }
                    },
                    {
                        name: '可容忍事件',
                        type: 'scatter',
                        symbol: 'circle',
                        symbolSize: 8,
                        data: gongData.pointF,
                        legendSymbol: 'circle'
                    },
                    {
                        name: '不可容忍事件',
                        type: 'scatter',
                        symbol: 'circle',
                        symbolSize: 8,
                        data: gongData.pointFun,
                        legendSymbol: 'rect'
                    }
                ]
            }
        }
    }
})

const tableRef = ref()
provide('tableRef', tableRef)
provide('tableStore', tableStore)

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 setTime = () => {
    const time = getTime(
        (TableHeaderRef.value?.datePickerRef.interval || defaultInterval) ?? 0,
        timeKeyList,
        [tableStore.table.params.searchBeginTime, tableStore.table.params.searchEndTime]
    )

    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 不是一个有效数组')
    }
}

function gongfunction(arr: any) {
    let standI = 0
    let unstandI = 0
    let standF = 0
    let unstandF = 0
    let pointIun: any[] = []
    let pointI: any[] = []
    let pointF: any[] = []
    let pointFun: any[] = []
    const total = arr.length

    if (total > 0) {
        for (let i = 0; i < arr.length; i++) {
            const xx = arr[i].persistTime
            const yy = arr[i].eventValue
            const time = arr[i].time
            const eventId = arr[i].eventId
            const lineName = arr[i].lineName
            const equipmentName = arr[i].equipmentName
            const projectName = arr[i].projectName
            const engineeringName = arr[i].engineeringName
            const point = [xx, yy, time, eventId, lineName, equipmentName, projectName, engineeringName]

            if (xx <= 0.003) {
                const line = 250 - 30000 * xx
                if (yy > line) {
                    unstandI++
                    pointIun.push({ value: point, itemStyle: { normal: { color: 'red' } } })
                } else {
                    standI++
                    pointI.push({ value: point, itemStyle: { normal: { color: 'green' } } })
                }
            } else if (xx <= 0.02) {
                if (yy > 120) {
                    unstandI++
                    pointIun.push({ value: point, itemStyle: { normal: { color: 'red' } } })
                } else {
                    standI++
                    pointI.push({ value: point, itemStyle: { normal: { color: 'green' } } })
                }
            } else if (xx <= 0.5) {
                if (yy > 120 || yy < 70) {
                    unstandI++
                    pointIun.push({ value: point, itemStyle: { normal: { color: 'red' } } })
                } else {
                    standI++
                    pointI.push({ value: point, itemStyle: { normal: { color: 'green' } } })
                }
            } else if (xx <= 10) {
                if (yy > 110 || yy < 80) {
                    unstandI++
                    pointIun.push({ value: point, itemStyle: { normal: { color: 'red' } } })
                } else {
                    standI++
                    pointI.push({ value: point, itemStyle: { normal: { color: 'green' } } })
                }
            } else {
                if (yy > 110 || yy < 90) {
                    unstandI++
                    pointIun.push({ value: point, itemStyle: { normal: { color: 'red' } } })
                } else {
                    standI++
                    pointI.push({ value: point, itemStyle: { normal: { color: 'green' } } })
                }
            }

            if (xx < 0.05) {
                standF++
                pointF.push({ value: point, itemStyle: { normal: { color: 'green' } } })
            } else if (xx < 0.2) {
                if (yy > 50) {
                    standF++
                    pointF.push({ value: point, itemStyle: { normal: { color: 'green' } } })
                } else {
                    unstandF++
                    pointFun.push({ value: point, itemStyle: { normal: { color: 'red' } } })
                }
            } else if (xx < 0.5) {
                if (yy > 70) {
                    standF++
                    pointF.push({ value: point, itemStyle: { normal: { color: 'green' } } })
                } else {
                    unstandF++
                    pointFun.push({ value: point, itemStyle: { normal: { color: 'red' } } })
                }
            } else {
                if (yy > 80) {
                    standF++
                    pointF.push({ value: point, itemStyle: { normal: { color: 'green' } } })
                } else {
                    unstandF++
                    pointFun.push({ value: point, itemStyle: { normal: { color: 'red' } } })
                }
            }
        }
    }

    return { standI, unstandI, pointI, pointIun, standF, unstandF, pointF, pointFun }
}

onMounted(() => {
    setTimeout(() => {
        tableStore.index()
    }, 100)
})

const handleChartClick = (params: any) => {
    if (params.seriesName === '可容忍事件' || params.seriesName === '不可容忍事件') {
        handleTolerableEventClick(params)
    }
}

const handleTolerableEventClick = async (row: any) => {
    loading.value = true
    ElMessage.info(`正在加载，请稍等...`)
    await analyseWave(row.value[3])
        .then(res => {
            if (res != undefined) {
                loading.value = true
                isWaveCharts.value = true
                boxoList.value = {
                    persistTime: row.value[0],
                    featureAmplitude: row.value[1] / 100,
                    startTime: row.value[2],
                    lineName: row.value[4],
                    engineeringName: row.value[6],
                    systemType: 'YPT'
                }
                wp.value = res.data
            }
            loading.value = false
        })
        .catch(() => {
            loading.value = false
        })

    nextTick(() => {
        waveFormAnalysisRef.value?.getWpData(wp.value, boxoList.value, true)
    })
}
</script>

<style scoped>
.event-statistics-curve {
    width: 100%;
}
</style>
