<template>
    <div class='default-main analyze-apf' :style='{ height: pageHeight.height }' v-loading='loading'>
        <DeviceTree @node-click='nodeClick' @init='nodeClick'></DeviceTree>
        <div class='analyze-apf-right'>
            <el-form :inline='true'>
                <el-form-item label='统计指标:'>
                    <el-select v-model='formInline.statisticalId' filterable placeholder='请选择'>
                        <el-option
                            v-for='item in zblist'
                            :key='item.value'
                            :label='item.label'
                            :value='item.value'
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label='值类型:'>
                    <el-select v-model='formInline.valueType' filterable placeholder='请选择'>
                        <el-option
                            v-for='item in typelist'
                            :key='item.value'
                            :label='item.label'
                            :value='item.value'
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label='时间:'>
                    <DatePicker ref='datePickerRef'></DatePicker>
                </el-form-item>
                <el-form-item>
                    <el-button type='primary' @click='search' icon='el-icon-Search'>查询</el-button>
                </el-form-item>
            </el-form>
            <el-empty description='暂无数据' v-if='!echartsData' style='flex: 1'></el-empty>
            <template v-else>
                <MyEchart :options='echartsData' style='flex: 1' />
                <span style='position: absolute; right: 10px; top: 10px'>
                    <i style='color: #ff9912' type='warning' class='el-icon-warning'></i>
                    总输出电流阈值和总输出电流比较
                </span>
            </template>
        </div>
    </div>
</template>

<script setup lang='ts'>
import { ref, reactive } from 'vue'
import { mainHeight } from '@/utils/layout'
import DeviceTree from '@/components/tree/govern/deviceTree.vue'
import { queryByCode, queryCsDictTree } from '@/api/system-boot/dictTree'
import { getDevCapacity } from '@/api/cs-device-boot/capacity'
import { queryCommonStatisticalByTime } from '@/api/cs-harmonic-boot/stable'
import DatePicker from '@/components/form/datePicker/index.vue'
import MyEchart from '@/components/echarts/MyEchart.vue'

defineOptions({
    name: 'govern/analyze/APF'
})
const pageHeight = mainHeight(20)
const loading = ref(false)
const echartsData = ref<any>(null)
const datePickerRef = ref()
const formInline = reactive({
    statisticalId: '',
    valueType: '',
    startTime: '',
    endTime: '',
    devId: ''
})
const devCapacity = ref(0)
const typelist = [
    {
        label: '平均值',
        value: 'avg'
    },
    {
        label: '最大值',
        value: 'max'
    },
    {
        label: '最小值',
        value: 'min'
    },
    {
        label: 'CP95值',
        value: 'cp95'
    }
]
const zblist = ref<any[]>([])

const init = () => {
    return new Promise((resolve, reject) => {
        queryByCode('Harmonic_Type').then(res => {
            queryCsDictTree(res.data.id).then(res => {
                zblist.value = res.data.map((item: any) => {
                    return {
                        value: item.id,
                        label: item.name,
                        ...item
                    }
                })
                formInline.statisticalId = zblist.value[0]?.value
                formInline.valueType = typelist[0].value
                resolve(null)
            })
        })
    })
}
const nodeClick = async (e: anyObj) => {
    if (e.level == 2) {
        formInline.devId = e.id
        loading.value = true
        if (zblist.value.length === 0) {
            await init()
        }
        let getDevCapacityRes = await getDevCapacity(formInline.devId)
        devCapacity.value = getDevCapacityRes.data
        search()
    }
}
const search = () => {
    loading.value = true
    formInline.startTime = datePickerRef.value.timeValue[0]
    formInline.endTime = datePickerRef.value.timeValue[1]
    queryCommonStatisticalByTime(formInline).then(({ data }: { data: any[] }) => {
        if (data.length) {
            echartsData.value = {}
            let legend: any[] = []
            let xAxis: any[] = []
            data.forEach(item => {
                if (!xAxis.includes(item.time)) {
                    xAxis.push(item.time)
                }
                if (!legend.includes(item.anotherName)) {
                    legend.push(item.anotherName)
                }
            })
            let series = [
                // 总输出电流
                {
                    name: data.find(item => item.statisticalName === 'Apf_RmsI_TolOut').anotherName,
                    symbol: 'none',
                    smooth: true,
                    type: 'line',
                    //stack: 'Total',
                    data: data
                        .map(item => {
                            if (item.statisticalName === 'Apf_RmsI_TolOut') {
                                return item.statisticalData
                            } else {
                                return ''
                            }
                        })
                        .filter(item => item !== ''),
                    markLine: {
                        symbol: 'none',
                        data: [
                            {
                                yAxis: devCapacity.value,
                                label: {
                                    position: 'middle', // 表现内容展示的位置
                                    formatter: '总输出电流阈值', // 标线展示的内容
                                    color: '#daa569' // 展示内容颜色
                                }
                            }
                        ]
                    },
                    yAxisIndex: 1
                },
                //负载电流畸变率
                {
                    name: data.find(item => item.statisticalName === 'Apf_ThdA_Load').anotherName,
                    symbol: 'none',
                    smooth: true,
                    type: 'line',
                    data: data
                        .map(item => {
                            if (item.statisticalName === 'Apf_ThdA_Load') {
                                return item.statisticalData
                            } else {
                                return ''
                            }
                        })
                        .filter(item => item !== '')
                },
                // 电网电流畸变率
                {
                    name: data.find(item => item.statisticalName === 'Apf_ThdA_Sys').anotherName,
                    symbol: 'none',
                    smooth: true,
                    type: 'line',
                    data: data
                        .map(item => {
                            if (item.statisticalName === 'Apf_ThdA_Sys') {
                                return item.statisticalData
                            } else {
                                return ''
                            }
                        })
                        .filter(item => item !== '')
                }
            ]
            echartsData.value = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },
                legend: {
                    data: legend
                },
                grid: {
                    left: '20px',
                    right: '40px',
                    bottom: '50px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    name: '时间',
                    type: 'category',
                    boundaryGap: false,
                    data: xAxis,
                    axisLabel: {
                        formatter: function(value: string) {
                            return value.split(' ').join('\n')
                        }
                    },
                    axisLine: {
                        show: true,
                        // symbol: ["none", "arrow"],
                        lineStyle: {
                            color: '#333'
                        }
                    }
                },
                yAxis: [
                    {
                        name: '畸变率:(%)',
                        type: 'value',
                        max: 10,
                        min: 0,
                        axisLine: {
                            show: true,
                            //symbol: ["none", "arrow"],
                            lineStyle: {
                                color: '#333'
                            }
                        }
                    },
                    {
                        name: '电流:(A)',
                        type: 'value',
                        min: 0,
                        // 寻找data最大值
                        max:
                            series[0].data.reduce((a, b) => Math.max(a, b)) > devCapacity.value
                                ? series[0].data.reduce((a, b) => Math.max(a, b))
                                : devCapacity.value + devCapacity.value * 0.5,
                        interval:
                            (series[0].data.reduce((a, b) => Math.max(a, b)) > devCapacity.value
                                ? series[0].data.reduce((a, b) => Math.max(a, b))
                                : devCapacity.value) / 10,
                        axisLine: {
                            show: true,
                            //symbol: ["none", "arrow"],
                            lineStyle: {
                                color: '#333'
                            }
                        }
                    }
                ],
                options: {
                    series: series
                }
            }
        } else {
            echartsData.value = null
        }
        loading.value = false
    })
}
</script>

<style lang='scss'>
.analyze-apf {
    display: flex;

    &-right {
        height: 100%;
        overflow: hidden;
        flex: 1;
        padding: 10px 10px 10px 0;
        display: flex;
        flex-direction: column;
    }
}
</style>
