<template>
    <el-dialog draggable :title="dialogTitle" v-model="dialogVisible" append-to-body width="70%">
        <!-- 总体指标占比详情谐波含有率 -->
        <div>
            <TableHeader ref="tableHeaderRef" :showSearch="false" @selectChange="selectChange">
                <template v-slot:select>
                    <el-form-item>
                        <DatePicker ref="datePickerRef"></DatePicker>
                    </el-form-item>
                    <el-form-item label="统计指标" label-width="80px">
                        <el-select multiple :multiple-limit="2" collapse-tags collapse-tags-tooltip
                            v-model="searchForm.index" placeholder="请选择统计指标" @change="onIndexChange($event)" filterable>
                            <el-option v-for="item in indexOptions" :key="item.id" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-radio-group v-model="searchForm.dataLevel" @change="init()">
                            <el-radio-button label="一次值" value="Primary" />
                            <el-radio-button label="二次值" value="Secondary" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="统计类型">
                        <el-select style="min-width: 120px !important" placeholder="请选择" v-model="searchForm.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>
                        <div class="history_count" v-for="(item, index) in countData" :key="index"
                            v-show="item.countOptions.length != 0">
                            <span class="mr12">
                                {{ item.name.includes('次数') ? item.name : item.name + '谐波次数' }}
                            </span>
                            <el-select v-model="item.count" @change="onCountChange($event, index)" placeholder="请选择谐波次数"
                                style="width: 100px" class="mr20" filterable>
                                <el-option v-for="vv in item.countOptions" :key="vv"
                                    :label="item.name.includes('间谐波') ? vv - 0.5 : vv" :value="vv"></el-option>
                            </el-select>
                        </div>
                    </el-form-item>
                </template>
                <template #operation>
                    <el-button type="primary" icon="el-icon-Search" @click="init()">查询</el-button>
                </template>
            </TableHeader>
        </div>
        <div class="history_chart" :style="pageHeight" v-loading="loading">
            <MyEchart ref="historyChart" :options="echartsData" v-if="showEchart" />
            <el-empty :style="pageHeight" v-else description="暂无数据" />
        </div>
    </el-dialog>
</template>
<script lang="ts" setup>
import { mainHeight } from '@/utils/layout'
import { queryByCode, queryCsDictTree } from '@/api/system-boot/dictTree'
import { ref, onMounted, watch } from 'vue'
import MyEchart from '@/components/echarts/MyEchart.vue'
import { useDictData } from '@/stores/dictData'
import { queryStatistical } from '@/api/system-boot/csstatisticalset'
import { yMethod, exportSeriesCSV, completeTimeSeries } from '@/utils/echartMethod'
import TableHeader from '@/components/table/header/index.vue'
import { trendData } from '@/api/harmonic-boot/cockpit/cockpit'
import DatePicker from '@/components/form/datePicker/index.vue'
import { color } from '@/components/echarts/color'
import { ElMessage } from 'element-plus'
const dictData = useDictData()
defineOptions({
    // name: 'govern/device/control'
})
const props = defineProps({
    TrendList: {
        type: Array
    }
})
const dialogTitle = ref('趋势图')

const dialogVisible: any = ref(false)
// console.log("🚀 ~ props:", props.TrendList)
const showEchart = ref(true)
const num = ref(0)
const timeControl = ref(false)
//值类型
const pageHeight = ref(mainHeight(57 * 1.6, 1.6))
const loading = ref(true)
const searchForm: any = ref({})
const tableHeaderRef = ref()
const typeOptions = [
    {
        name: '平均值',
        id: 'avg'
    },
    {
        name: '最大值',
        id: 'max'
    },
    {
        name: '最小值',
        id: 'min'
    },
    {
        name: 'CP95值',
        id: 'cp95'
    }
]
searchForm.value = {
    index: [],
    type: typeOptions[0].id,
    count: '',
    searchBeginTime: '',
    searchEndTime: '',
    dataLevel: 'Primary',
    valueType: 'avg'
}
//统计指标
const indexOptions: any = ref([])
//谐波次数
const countOptions: any = ref([])
// Harmonic_Type
// portable-harmonic
const legendDictList: any = ref([])

const initCode = (field: string, title: string) => {
    queryByCode('gridSide_exceedTheLimit').then(res => {
        queryCsDictTree(res.data.id).then(item => {
            //排序
            indexOptions.value = item.data.sort((a: any, b: any) => {
                return a.sort - b.sort
            })
            // const titleMap: Record<string, number> = {
            //     flickerOvertime: 0,
            //     uaberranceOvertime: 3,
            //     ubalanceOvertime: 4,
            //     freqDevOvertime: 5
            // }

            // let defaultIndex = 0 // 默认值

            // if (field in titleMap) {
            //     defaultIndex = titleMap[field]
            // } else if (field.includes('uharm')) {
            //     defaultIndex = 1
            // } else if (field.includes('iharm')) {
            //     defaultIndex = 2
            // }
            let codeKey = field.includes('flickerOvertime')
                ? '闪变'
                : field.includes('uharm')
                    ? '谐波电压'
                    : field.includes('iharm')
                        ? '谐波电流'
                        : field.includes('uaberrance')
                            ? '电压偏差'
                            : field.includes('ubalanceOvertime')
                                ? '不平衡'
                                : ''
            let defaultIndex = indexOptions.value.findIndex((item: any) => item.name.includes(codeKey)) || 0

            searchForm.value.index[0] = indexOptions.value[defaultIndex].id
        })
        queryStatistical(res.data.id).then(vv => {
            legendDictList.value = vv.data
            indexOptions.value.map((item: any, index: any) => {
                if (!countDataCopy.value[index]) {
                    countDataCopy.value[index] = {
                        index: item.id,
                        countOptions: [],
                        count: [],
                        name: indexOptions.value.find((vv: any) => {
                            return vv.id == item.id
                        })?.name
                    }
                }
                legendDictList.value?.selectedList?.map((vv: any, vvs: any) => {
                    //查找相等的指标
                    if (item.id == vv.dataType) {
                        vv.eleEpdPqdVOS.map((kk: any, kks: any) => {
                            if (kk.harmStart && kk.harmEnd) {
                                range(0, 0, 0)

                                if (kk.showName == '间谐波电压含有率') {
                                    countDataCopy.value[index].countOptions = range(kk.harmStart, kk.harmEnd, 1).map(
                                        (item: any) => {
                                            return item - 0.5
                                        }
                                    )
                                } else {
                                    countDataCopy.value[index].countOptions = range(kk.harmStart, kk.harmEnd, 1)
                                }
                                if (title && countDataCopy.value[index].countOptions.includes(Number(title))) {
                                    countDataCopy.value[index].count = Number(title)
                                } else if (title && countDataCopy.value[index].countOptions.includes(title)) {
                                    countDataCopy.value[index].count = title
                                } else if (
                                    !countDataCopy.value[index].count ||
                                    countDataCopy.value[index].count.length == 0
                                ) {
                                    // 只有当count为空时才设置默认值
                                    countDataCopy.value[index].count = countDataCopy.value[index].countOptions[0]
                                }
                            }
                        })
                    }
                })
            })
            nextTick(() => {
                formatCountOptions()
            })
            init()
        })
    })
}

const chartsList = ref<any>([])
const chartTitle: any = ref('')
const echartsData = ref<any>(null)
//加载echarts图表
//历史趋势数据
const historyDataList: any = ref([])
const range = (start: any, end: any, step: any) => {
    return Array.from({ length: (end - start) / step + 1 }, (_, i) => start + i * step)
}
//获取请求趋势数据参数
const trendRequestData = ref()
const getTrendRequest = (val: any) => {
    trendRequestData.value = val
    // init()
}
//初始化趋势图
const headerRef = ref()
const datePickerRef = ref()
const lineStyle = [{ type: 'solid' }, { type: 'dashed' }, { type: 'dotted' }]
const init = async () => {
    loading.value = true
    // 选择指标的时候切换legend内容和data数据
    let list: any = []
    legendDictList.value?.selectedList?.map((item: any) => {
        searchForm.value.index.map((vv: any) => {
            if (item.dataType == vv) {
                list.push(item.eleEpdPqdVOS)
            }
        })
    })

    //颜色数组
    const colorList = color
    //选择的指标使用方法处理
    formatCountOptions()
    //查询历史趋势
    historyDataList.value = []
    chartTitle.value = ''

    searchForm.value.index.map((item: any, indexs: any) => {
        indexOptions.value.map((vv: any) => {
            if (vv.id == item) {
                chartTitle.value += indexs == searchForm.value.index.length - 1 ? vv.name : vv.name + '/'
            }
        })
    })
    let lists: any = []
    let frequencys: any = null
    countData.value.map((item: any, index: any) => {
        if (item.name.includes('谐波含有率')) {
            frequencys = item.count
        } else {
            frequencys = ''
        }
        lists[index] = {
            statisticalId: item.index,
            frequency: frequencys !== null && frequencys !== undefined ? String(frequencys) : ''
        }
    })
    let obj = {
        //...trendRequestData.value,
        lineId: trendRequestData.value.lineId,
        list: lists,
        dataLevel: searchForm.value.dataLevel,
        valueType: searchForm.value.valueType,
        searchBeginTime: datePickerRef.value && datePickerRef.value.timeValue[0],
        searchEndTime: datePickerRef.value && datePickerRef.value.timeValue[1]
    }
    if (searchForm.value.index.length == 0) {
        ElMessage.warning('请选择统计指标')
        loading.value = false
        return
    }
    if (obj.list.length != 0) {
        try {
            showEchart.value = true
            await trendData(obj)
                .then((res: any) => {
                    if (res.code == 'A0000') {
                        if (res.data.length == 0) {
                            loading.value = false
                            showEchart.value = false
                            return
                        }
                        historyDataList.value = res.data
                        chartsList.value = JSON.parse(JSON.stringify(res.data))
                        loading.value = false
                        setEchart()
                    }
                })
                .catch(error => {
                    loading.value = false
                })
        } catch (error) {
            loading.value = false
        }
    }
}
const setEchart = () => {
    loading.value = true
    echartsData.value = {}
    //icon图标替换legend图例

    // y轴单位数组
    let unitList: any = []

    let groupedData = chartsList.value.reduce((acc: any, item: any) => {
        let key = ''
        if (item.phase == null) {
            key = item.unit
        } else {
            key = item.anotherName
        }

        if (!acc[key]) {
            acc[key] = []
        }
        acc[key].push(item)
        return acc
    }, {})
    let result = Object.values(groupedData)
    if (chartsList.value.length > 0) {
        unitList = result.map((item: any) => {
            return item[0].unit
        })
    }

    echartsData.value = {
        exportFileName: {
            subject: trendRequestData.value?.lineName,
            feature: '趋势图',
            date: datePickerRef.value?.timeValue?.[1] || datePickerRef.value?.timeValue?.[0]
        },
        legend: {
            itemWidth: 20,
            itemHeight: 20,
            itemStyle: { opacity: 0 }, //去圆点
            type: 'scroll', // 开启滚动分页
            // orient: 'vertical', // 垂直排列
           
            // width: 550,
            // height: 50
        },
        grid: {
            top: '80px'
        },
        tooltip: {
            axisPointer: {
                type: 'cross',
                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(params: any) {
                const xname = params[0].value[0]
                let str = `${xname}<br>`
                params.forEach((el: any, index: any) => {
                    let marker = ''

                    if (el.value[3] == 'dashed') {
                        for (let i = 0; i < 3; i++) {
                            marker += `<span style="display:inline-block;border: 2px ${el.color} solid;margin-right:5px;width:10px;height:0px;background-color:#ffffff00;"></span>`
                        }
                    } else {
                        marker = `<span style="display:inline-block;border: 2px ${el.color} ${el.value[3]};margin-right:5px;width:40px;height:0px;background-color:#ffffff00;"></span>`
                    }
                    let unit = el.value[2] ? el.value[2] : ''
                    str += `${marker}${el.seriesName.split('(')[0]}：${el.value[1]}${unit}
                                            <br>`
                })
                return str
            }
        },
        color: ['#DAA520', '#2E8B57', '#A52a2a', ...color],
        xAxis: {
            type: 'time',
            axisLabel: {
                formatter: {
                    day: '{MM}-{dd}',
                    month: '{MM}',
                    year: '{yyyy}'
                }
            }
        },
        yAxis: [{}],
        toolbox: {
            featureProps: {
                myTool1: {
                    show: true,
                    title: '下载csv',
                    icon: 'path://M642 673.1H301.6c-9.9 0-17.9-8-17.9-17.9s8-17.9 17.9-17.9H642c9.9 0 17.9 8 17.9 17.9s-8 17.9-17.9 17.9zM642 511.8H301.6c-9.9 0-17.9-8-17.9-17.9 0-9.9 8-17.9 17.9-17.9H642c9.9 0 17.9 8 17.9 17.9 0 9.9-8 17.9-17.9 17.9zM480.7 350.6H301.6c-9.9 0-17.9-8-17.9-17.9s8-17.9 17.9-17.9h179.2c9.9 0 17.9 8 17.9 17.9s-8.1 17.9-18 17.9zM874.9 350.6H695.7c-49.4 0-89.6-40.2-89.6-89.6V81.9c0-9.9 8-17.9 17.9-17.9 9.9 0 17.9 8 17.9 17.9V261c0 29.6 24.1 53.7 53.7 53.7h179.2c9.9 0 17.9 8 17.9 17.9s-7.9 18-17.8 18zM794.3 959.7H221c-49.4 0-89.6-40.2-89.6-89.6V153.5c0-49.4 40.2-89.6 89.6-89.6h403.1c4.8 0 9.3 1.9 12.7 5.2L887.6 320c3.4 3.4 5.2 7.9 5.2 12.7v537.5c0 52.7-51.9 89.5-98.5 89.5zM221 99.8c-29.6 0-53.7 24.1-53.7 53.7v716.6c0 29.6 24.1 53.7 53.7 53.7h573.3c29 0 62.7-23.5 62.7-53.7v-530L616.7 99.8H221z',
                    onclick: () => {
                        exportSeriesCSV(echartsData.value.options.series, echartsData.value.exportFileName)
                    }
                },
                myTool2: {
                    show: true,
                    title: timeControl.value ? '关闭缺失数据' : '缺失数据',
                    icon: 'path://M832 512l-192-192v128H128v128h512v128l192-192zM192 512l192 192v-128h512v-128H384V320L192 512z',
                    iconStyle: timeControl.value ? { borderColor: '#409EFF' } : {},
                    onclick: () => {
                        setTimeControl()
                    }
                }
            }
        },
        options: {
            series: []
        }
    }
    // console.log("🚀 ~ unitList.forEach ~ unitList:", unitList)

    if (chartsList.value.length > 0) {
        let yData: any = []
        echartsData.value.yAxis = []
        let setList = [...new Set(unitList)]

        setList.forEach((item: any, index: any) => {
            if (index > 2) {
                echartsData.value.grid.right = (index - 1) * 80
            }
            yData.push([])
            let right = {
                position: 'right',
                offset: (index - 1) * 80
            }
            // console.log("🚀 ~ unitList.forEach ~ right.index:", index)
            echartsData.value.yAxis.push({
                name: item,
                yAxisIndex: index,
                splitNumber: 5,
                minInterval: 1,
                splitLine: {
                    show: false
                },
                ...(index > 0 ? right : null)
            })
        })
        // console.log("🚀 ~ result.forEach ~ result:", result)
        // '电压负序分量', '电压正序分量', '电压零序分量'
        let ABCName = [
            ...new Set(
                chartsList.value.map((item: any) => {
                    return item.anotherName == '电压负序分量'
                        ? '电压不平衡'
                        : item.anotherName == '电压正序分量'
                            ? '电压不平衡'
                            : item.anotherName == '电压零序分量'
                                ? '电压不平衡'
                                : item.anotherName
                })
            )
        ]
        // console.log("🚀 ~ .then ~ ABCName:", ABCName)
        result.forEach((item: any, index: any) => {
            let yMethodList: any = []

            let ABCList = Object.values(
                item.reduce((acc, item) => {
                    let key = ''
                    if (item.phase == null) {
                        key = item.anotherName
                    } else {
                        key = item.phase
                    }

                    if (!acc[key]) {
                        acc[key] = []
                    }
                    acc[key].push(item)
                    return acc
                }, {})
            )
            // console.log("🚀 ~ ABCList.forEach ~ ABCList:", ABCList)

            ABCList.forEach((kk: any) => {
                let colorName = kk[0].phase?.charAt(0).toUpperCase()
                let lineS = ABCName.findIndex(
                    item =>
                        item ===
                        (kk[0].anotherName == '电压负序分量'
                            ? '电压不平衡'
                            : kk[0].anotherName == '电压正序分量'
                                ? '电压不平衡'
                                : kk[0].anotherName == '电压零序分量'
                                    ? '电压不平衡'
                                    : kk[0].anotherName)
                )

                let seriesList: any = []
                kk.forEach((cc: any) => {
                    if (cc.statisticalData !== null) {
                        yData[setList.indexOf(kk[0].unit)].push(cc.statisticalData?.toFixed(2))
                    }

                    seriesList.push([cc.time, cc.statisticalData?.toFixed(2), cc.unit, lineStyle[lineS].type])
                })
                // console.log(kk);

                echartsData.value.options.series.push({
                    name: kk[0].phase ? kk[0].phase + '相' + kk[0].anotherName : kk[0].anotherName,
                    type: 'line',
                    smooth: true,
                    color:
                        colorName == 'A' ? '#DAA520' : colorName == 'B' ? '#2E8B57' : colorName == 'C' ? '#A52a2a' : '',
                    symbol: 'none',
                    // data: seriesList,
                    data: timeControl.value ? completeTimeSeries(seriesList) : seriesList,
                    lineStyle: lineStyle[lineS],
                    yAxisIndex: setList.indexOf(kk[0].unit)
                })
            })
        })
        yData.forEach((item: any, index: any) => {
            let [min, max] = yMethod(item)
            echartsData.value.yAxis[index].min = min
            echartsData.value.yAxis[index].max = max
        })
        // console.log("🚀 ~ result.forEach ~ echartsData.value:", echartsData.value)
    }
    loading.value = false
}
const setTimeControl = () => {
    timeControl.value = !timeControl.value
    setEchart()
}

const selectChange = (flag: boolean, height: any) => {
    pageHeight.value = mainHeight(height * 1.6, 1.6)
}
//导出
const historyChart = ref()

const countData: any = ref([])
const countDataCopy: any = ref([])

//根据选择的指标处理谐波次数
const formatCountOptions = () => {
    countData.value = []
    if (searchForm.value.index.length != 0) {
        searchForm.value.index.forEach((item: any, index: any) => {
            countDataCopy.value.forEach((vv: any, vvs: any) => {
                if (vv.index == item) {
                    countData.value.push(vv)
                }
            })
        })

        countData.value.map((item: any, key: any) => {
            if (item.name == '谐波电流有效值') {
                item.name = '谐波电流次数'
            } else if (item.name == '谐波电压含有率') {
                item.name = '谐波电压次数'
            } else if (item.name == '间谐波电压含有率') {
                item.name = '间谐波电压次数'
            }
        })
    }
    // setTimeout(() => {
    //     tableHeaderRef.value.computedSearchRow()
    // }, 500)
}
// 判断下拉框是否存在
const onCountChange = (val: any, index: any) => {
    if (val.length == 0) {
        countData.value[index].count = countData.value[index].countOptions[0]
    }
}
const flag = ref(true)
const onIndexChange = (val: any) => {
    num.value += 1
    let pp: any = []
    indexOptions.value.forEach((item: any) => {
        const filteredResult = val.filter(vv => item.id == vv)
        if (filteredResult.length > 0) {
            pp.push(filteredResult[0])
        }
    })
    searchForm.value.index = pp
    flag.value = true
    formatCountOptions()
}
watch(
    () => searchForm.value.index,
    (val: any, oldval: any) => { },
    {
        deep: true,
        immediate: true
    }
)

const openDialog = async (row: any, field: any, title: any) => {
    dialogVisible.value = true

    dialogTitle.value = row?.lineName + '_趋势图'
    trendRequestData.value = row

    nextTick(() => {
        // 默认当天
        datePickerRef.value.setInterval(5)
        datePickerRef.value.timeValue = [row.time, row.time]
        initCode(field, title)
    })
}

defineExpose({ getTrendRequest, openDialog })
</script>

<style lang="scss" scoped>
.history_header {
    display: flex;

    // flex-wrap: wrap;
    #history_select {
        width: 100%;
        display: flex;
        // justify-content: flex-start;
        // overflow-x: auto;
        height: auto;
        flex-wrap: wrap;

        .el-form-item {
            flex: none !important;
            // max-width: 380px;
        }

        .el-select {
            margin-right: 10px;
        }
    }

    // #history_select::-webkit-scrollbar {
    //     width: 0 !important;
    //     display: none !important;
    // }

    .history_searchBtn {
        flex: 1;
        display: flex;
        justify-content: flex-end;
        margin-top: 3px;
    }
}

.history_chart {
    width: 100%;

    // flex: 1;
    margin-top: 10px;
}

.history_count {
    .el-select {
        min-width: 100px;
    }
}
</style>
