<template>
    <div class="device-control-detail child-router">
        <TableHeader :showSearch="false">
            <template #select>
                <el-form-item label="日期">
                    <DatePicker ref="datePickerRef"></DatePicker>
                </el-form-item>
                <el-form-item label="值类型">
                    <el-select v-model.trim="form.dataLevel" :disabled="props.dataLevel == 'Primary'">
                        <el-option value="Primary" label="一次值"></el-option>
                        <el-option value="Secondary" label="二次值"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数据类型" label-width="80px">
                    <el-select v-model.trim="form.statMethod" placeholder="请选择数据类型">
                        <el-option v-for="item in typeOptions" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </template>
            <template #operation>
                <el-button type="primary" icon="el-icon-Search" @click="init">查询</el-button>
                <el-button icon="el-icon-Back" @click="$emit('close')">返回</el-button>
            </template>
        </TableHeader>

        <MyEchart :options="echartsData" v-if="echartsData" style="flex: 1" class="mt10" />
        <el-empty description="暂无数据" v-else style="flex: 1" v-loading="loading"></el-empty>
    </div>
</template>
<script lang="ts" setup>
import { ref, inject, nextTick, onMounted } from 'vue'
import { reactive } from 'vue'
import DatePicker from '@/components/form/datePicker/index.vue'
import { getDeviceDataTrend } from '@/api/cs-harmonic-boot/datatrend'
import TableHeader from '@/components/table/header/index.vue'
import MyEchart from '@/components/echarts/MyEchart.vue'
import { yMethod, exportCSV } from '@/utils/echartMethod'
import { ITEM_RENDER_EVT } from 'element-plus/es/components/virtual-list/src/defaults'

interface Props {
    detail: anyObj
    dataLevel: string
}

const props = withDefaults(defineProps<Props>(), {
    detail: () => {
        return {}
    },
    dataLevel: () => {
        return ''
    }
})
const datePickerRef = ref()
const form: any = reactive({
    code: '',
    icon: '',
    id: '',
    name: '',
    path: '',
    pid: '0',
    remark: '',
    routeName: '',
    sort: 100,
    dataLevel: '',
    statMethod: 'avg'
})
const typeOptions = [
    {
        name: '平均值',
        id: 'avg'
    },
    {
        name: '最大值',
        id: 'max'
    },
    {
        name: '最小值',
        id: 'min'
    },
    {
        name: 'CP95值',
        id: 'cp95'
    }
]
const echartsData = ref<any>(null)
const dialogVisible = ref(false)
const loading = ref(true)
onMounted(() => {
    if (props.dataLevel == 'Secondary') {
        form.dataLevel = 'Primary'
    } else {
        form.dataLevel = props.dataLevel
    }
    init()
})
const init = () => {
    echartsData.value = null
    loading.value = true
    // console.log(props.detail.children, 'props.detail.children')
    let statisticalParams = props.detail.children
    statisticalParams[0].statMethod = form.statMethod
    getDeviceDataTrend({
        devId: props.detail.devId,
        endTime: datePickerRef.value.timeValue[1],
        lineId: props.detail.lineId,
        startTime: datePickerRef.value.timeValue[0],
        statisticalParams: statisticalParams,
        dataLevel: form.dataLevel,
        statMethod: form.statMethod
    }).then(res => {


        if (res.data.length && res.data[0].length) {
            let arr: any[] = []
            res.data.forEach((item: any[]) => {
                arr.push(...item)
            })
            let [min, max] = yMethod(arr.map((item: any) => item.statisticalData.toFixed(2)))
            echartsData.value = {
                exportFileName: {
                    subject: props.detail.name?.split('(')[0],
                    feature: '历史趋势',
                    date: datePickerRef.value?.timeValue?.[1] || datePickerRef.value?.timeValue?.[0]
                },

                options: {
                    legend: {
                        right: 70,
                        top: 5,
                        data: res.data.map((item: any[]) => {
                            return item[0]?.anotherName
                        })
                    },
                    grid: {
                        top: '60px',
                        left: '10px',
                        right: '20px',
                        bottom: '40px',
                        containLabel: true
                    },
                    series: res.data.map((item: any) => {
                        return {
                            data: item.map((item: any, i: any) => {
                                return [res.data[0][i]?.time, item.statisticalData.toFixed(2)]
                            }),
                            // data: [
                            //     [1584086222000, '573'],
                            //     [1584086342000, '57'],
                            //     [1584086462000, '56']
                            // ],
                            // markPoint: {
                            //     symbol: 'circle',
                            //     symbolSize: 0,
                            //     label: {
                            //         show: false
                            //     },
                            //     data: [
                            //         { type: 'max', name: 'Max' },
                            //         { type: 'min', name: 'Min' }
                            //     ]
                            // },
                            type: 'line',
                            showSymbol: false,
                            smooth: true,
                            name: item[0]?.anotherName
                        }
                    })
                },
                title: {
                    text: props.detail.name?.split('(')[0],
                },
                tooltip: {
                    axisPointer: {
                        type: 'cross',
                        label: {
                            color: '#fff',
                            fontSize: 16
                        }
                    },
                    textStyle: {
                        color: '#fff',
                        fontStyle: 'normal',
                        opacity: 0.35,
                        fontSize: 14
                    },
                    borderWidth: 0
                },

                yAxis: {
                    name: `单位:(${arr[0].unit == null ? ' / ' : arr[0].unit})`,
                    type: 'value',


                    min: min,
                    max: max,
                    // interval:interval,

                    // min: 134,
                    // max: 500,
                    // min: Math.ceil(
                    //     arr
                    //         .map((item: any) => item.statisticalData)
                    //         .sort((a, b) => {
                    //             return a - b
                    //         })[0]
                    // ),
                    // max: Math.floor(
                    //     arr
                    //         .map(item => item.statisticalData)
                    //         .sort((a, b) => {
                    //             return b - a
                    //         })[0]
                    // ),
                    // interval: (Math.floor(
                    //     arr
                    //         .map(item => item.statisticalData)
                    //         .sort((a, b) => {
                    //             return b - a
                    //         })[0]
                    // ) - Math.ceil(
                    //     arr
                    //         .map((item: any) => item.statisticalData)
                    //         .sort((a, b) => {
                    //             return a - b
                    //         })[0]
                    // )) / 5,


                },

                xAxis: {
                    type: 'time',
                    axisLabel: {
                        formatter: {
                            day: '{MM}-{dd}',
                            month: '{MM}',
                            year: '{yyyy}',
                        }
                    }
                    // data: res.data[0].map((item: any) => {
                    //     return item.time
                    // }),

                    // axisLabel: {
                    //     formatter: function (value: string) {
                    //         return value.split(' ').join('\n')
                    //     }
                    // }
                },
                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: (e) => {


                                let list = echartsData.value.options.series.map(item => item.data)
                                let dataList = list[0].map((item, index) => {
                                    const value1 = list[1] && list[1][index] ? list[1][index][1] : null;
                                    const value2 = list[2] && list[2][index] ? list[2][index][1] : null;
                                    const value3 = list[3] && list[3][index] ? list[3][index][1] : null;

                                    return [item[0], item[1], value1, value2, value3];
                                });
                                exportCSV(
                                    echartsData.value.options.series.map(item => item.name),
                                    dataList,
                                    echartsData.value.exportFileName
                                )

                            }
                        }
                    }
                }
            }
            if ((echartsData.value.legend = ['A相', 'B相', 'C相'])) {
                echartsData.value.color = ['#DAA520', '#2E8B57', '#A52a2a']
            }

        } else {
            echartsData.value = null
        }
        loading.value = false
    })
}




defineExpose({ open })
</script>
<style lang="scss">
.device-control-detail {
    padding-bottom: 10px;
    display: flex;
    flex-direction: column;
}

.el-form--inline .el-form-item {
    margin-bottom: 10px !important;
}
</style>
