<template>
    <div class="contain">
        <el-header class="headerPart">
            <div class="topLeft">
                <div class="selectPart">
                    <span>{{ t('statAnalysis.deviceId') }}</span>
                    <el-select
                        v-model="statAnalysisSelect.deviceId"
                        @change="selectstatAnalysis('deviceId')"
                        :placeholder="'请选择' + t('statAnalysis.deviceId')"
                        class="statAnalysisSelect"
                    >
                        <el-option v-for="v in statAnalysisSelectOptions.deviceId" :key="v.value" :label="v.label" :value="v.value"></el-option>
                    </el-select>
                </div>
                <div class="selectPart">
                    <span>{{ t('statAnalysis.attributes') }}</span>
                    <el-input
                        class="statAnalysisSelect"
                        v-model="statAnalysisSelect.attributes"
                        @click="showMeasure = true"
                        :placeholder="'请选择' + t('statAnalysis.attributes')"
                    ></el-input>
                </div>
                <div class="selectPart">
                    <span>{{ t('statAnalysis.interval') }}</span>
                    <el-select
                        v-model="statAnalysisSelect.interval"
                        @change="selectstatAnalysis('interval')"
                        :placeholder="'请选择' + t('statAnalysis.interval')"
                        class="statAnalysisSelect"
                    >
                        <el-option v-for="v in statAnalysisSelectOptions.interval" :key="v.value" :label="v.label" :value="v.value"></el-option>
                    </el-select>
                </div>
            </div>
            <div class="topRight">
                <el-button type="primary" @click="statAnalysisOperate()">{{ t('statAnalysis.search') }}</el-button>
                <el-button style="color: #0064aa" @click="statAnalysiImport()">{{ t('statAnalysis.import') }}</el-button>
                <el-button style="color: #0064aa" @click="statAnalysisExport()">{{ t('statAnalysis.export') }}</el-button>
            </div>
        </el-header>
        <div class="timeColumns" :class="{ expand: isExpand }">
            <div class="headerPart" v-for="(time, index) in times" :key="index">
                <div class="topLeft">
                    <div class="selectPart">
                        <span>{{ index + 1 }}</span>
                        <span>{{ t('statAnalysis.time') }}</span>
                        <el-date-picker
                            class="datetime-picker"
                            v-model="times[index]"
                            :type="statAnalysisSelect.interval == '1d' ? 'daterange' : 'datetimerange'"
                            :value-format="statAnalysisSelect.interval == '1d' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'"
                            :teleported="false"
                            :shortcuts="shortcuts"
                            @change="timechange(index)"
                        />
                    </div>
                    <div class="topLeft">
                        <div class="icon">
                            <el-button v-show="index === times.length - 1" type="primary" size="small" :icon="Plus" circle @click="addTime(index)">
                            </el-button>
                        </div>
                        <div class="icon">
                            <el-button v-show="index !== 0" type="danger" size="small" :icon="Delete" @click="switchTime(index)" circle></el-button>
                        </div>
                        <div class="selectPart" v-if="calculate[index] && calculate[index]['max']">
                            <span>{{ t('statAnalysis.max') }}</span>
                            <span class="max">{{ calculate[index]['max'] }}</span>
                        </div>
                        <div class="selectPart" v-if="calculate[index] && calculate[index]['min']">
                            <span>{{ t('statAnalysis.min') }}</span>
                            <span class="min">{{ calculate[index]['min'] }}</span>
                        </div>
                        <div class="selectPart" v-if="calculate[index] && calculate[index]['average']">
                            <span>{{ t('statAnalysis.average') }}</span>
                            <span class="average">{{ calculate[index]['average'] }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div v-if="times.length > 2" class="ralIcon" @click="handleClick">
            <el-icon :size="20" color="#0064AA"><DArrowRight /></el-icon>
        </div>
        <div ref="chartContainer" style="width: 100%; height: 400px"></div>
        <el-dialog v-model="showMeasure" title="测点名称" :width="800">
            <template #header>
                <div class="measureSlotHeader">
                    <span style="font-size: 20px">测点名称</span>
                </div>
            </template>
            <div class="measureSlot">
                <MeasurementPage :show="showMeasure" :iotModelId="iotModelId" @handleRadioChange="handleRadioChange"></MeasurementPage>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showMeasure = false">取消</el-button>
                    <el-button type="primary" @click="selectstatAnalysisAttributes"> 确认 </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { onUnmounted, reactive, ref, watch, nextTick, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { queryWindTurbinesPages, historyReq } from '/@/api/backend/statAnalysis/request'
import { ElMessage, ElMenu } from 'element-plus'
import { DArrowRight, Plus, Delete } from '@element-plus/icons-vue'
import MeasurementPage from './analysisAttributes.vue'
import * as echarts from 'echarts'
const { t } = useI18n()
const statAnalysisSelect = reactive({
    deviceId: '',
    attributes: '',
    attributeCode: '',
    interval: '',
    time: '',
})
const times = reactive([{ time: '' }])
const addTime = (index) => {
    times.push({ time: '' })
    customName.value.push(index + 2)
}
const switchTime = (index) => {
    times.splice(index, 1)
    customName.value.splice(index, 1)
    calculate.splice(index, 1)
}
const timechange = (value) => {
    const count = getTimeIntervals(times[0][0], times[0][1])
    const count1 = getTimeIntervals(times[value][0], times[value][1])
    if (count !== count1) {
        times[value] = { time: '' }
        value = ElMessage.warning('查询时间点错误，请重新输入')
    }
}
const isExpand = ref(false)
const handleClick = () => {
    isExpand.value = !isExpand.value
}

const iotModelId = ref('')
watch(
    () => statAnalysisSelect.deviceId,
    (newVal) => {
        if (newVal) {
            const row = statAnalysisSelectOptions.deviceId.filter((item) => {
                return item.value == newVal
            })
            iotModelId.value = row[0].iotModelId
        }
    },
    {
        immediate: true,
    }
)

const showMeasure = ref(false)
const selectedAttrRow = ref({
    attributeCode: '',
    attributeName: '',
})
const handleRadioChange = (value) => {
    const { attributeCode, attributeName } = { ...value }
    selectedAttrRow.attributeCode = attributeCode
    selectedAttrRow.attributeName = attributeName
}
const selectstatAnalysisAttributes = () => {
    statAnalysisSelect.attributes = selectedAttrRow.attributeName
    statAnalysisSelect.attributeCode = selectedAttrRow.attributeCode
    showMeasure.value = false
}

const chartContainer = ref<HTMLElement | null>(null)

const option = reactive({
    dataZoom: [
        {
            type: 'inside',
            start: 0,
            end: 100,
        },
        {
            start: 0,
        },
    ],
    tooltip: {},
    legend: {
        icon: 'circle',
        itemGap: 20,
        itemWidth: 8,
        itemHeight: 8,
        data: [],
    },
    xAxis: {
        type: 'category',
        data: [],
    },
    yAxis: {
        type: 'value',
    },
    series: [],
    grid: {
        left: '3%',
        right: '3%',
    },
})

const statAnalysisSelectOptions = reactive({
    interval: [
        { label: '五分钟', value: '5m' },
        { label: '十五分钟', value: '15m' },
        { label: '一小时', value: '1h' },
        { label: '一天', value: '1d' },
        { label: '原始', value: 'NONE' },
    ],
    deviceId: [],
})
const customName = ref(['1'])
const chart = ref(null)
onMounted(() => {
    if (chartContainer.value) {
        chart.value = echarts.init(chartContainer.value)
        chart.value.setOption(option)
    }
    queryWindTurbines()
})
const queryWindTurbines = () => {
    queryWindTurbinesPages().then((res) => {
        if (res.code == 200) {
            statAnalysisSelectOptions.deviceId = res.data.map((item) => {
                return {
                    value: item.irn,
                    label: item.name ?? '-',
                    iotModelId: item.modelId,
                }
            })
        }
    })
}

window.onresize = () => {
    chart.value.resize()
}

const handleSelect = (index) => {
    activeIndex.value = index
}
const selectstatAnalysis = () => {}

const shortcuts = [
    {
        text: '昨日',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            return [start, end]
        },
    },
    {
        text: '前三天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
            return [start, end]
        },
    },
    {
        text: '前七天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '上个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
]
const getTimeIntervals = (startTimestamp, endTimestamp) => {
    const startDate = new Date(startTimestamp)
    const endDate = new Date(endTimestamp)
    let count = 0

    switch (statAnalysisSelect.interval) {
        case 'NONE':
            count = Math.floor((endDate - startDate) / 1000)
            break
        case '5m':
            count = Math.floor((endDate - startDate) / (5 * 60 * 1000))
            break
        case '15m':
            count = Math.floor((endDate - startDate) / (15 * 60 * 1000))
            break
        case '1h':
            count = Math.floor((endDate - startDate) / (1 * 60 * 60 * 1000))
            break
        case '1d':
            count = c((endDate - startDate) / (1 * 24 * 60 * 60 * 1000))
            break
        // default:
        // throw new Error('Invalid interval')
    }

    return count
}
const statAnalysisOperate = () => {
    option.tooltip = {}
    option.xAxis.data = []
    option.legend.data = []
    option.series = []
    times.forEach((time, index) => {
        if (time[0] && time[1]) {
            const requestData = {
                devices: [
                    {
                        deviceId: statAnalysisSelect.deviceId,
                        attributes: [statAnalysisSelect.attributeCode],
                    },
                ],
                interval: statAnalysisSelect.interval,
                startTime: new Date(time[0]).getTime(),
                endTime: new Date(time[1]).getTime(),
            }
            historyDataReq(requestData, index)
        }
    })
}
const calculate = reactive([{ max: '', min: '', average: '' }])
const historyDataReq = (data, index) => {
    historyReq(data).then((res) => {
        if (res.code == 200) {
            const deviceId = statAnalysisSelect.deviceId
            const attributeCode = statAnalysisSelect.attributeCode
            const resData = (res.data && deviceId in res.data && res.data[deviceId][attributeCode]) || undefined
            if (resData) {
                const xData = resData['times']
                const yData = resData['values']

                calculate[index] = {
                    max: Math.floor(Math.max(...yData)),
                    min: Math.floor(Math.min(...yData)),
                    average: Math.floor(yData.reduce((a, b) => a + b, 0) / yData.length),
                }

                option.tooltip = {
                    show: true,
                    formatter: function (params) {
                        const x = timestampToTime(xData[params.dataIndex])
                        return `${params.marker} ${params.seriesName} ${x}   : ${params.data}`
                    },
                }
                option.xAxis.data = Array.from({ length: xData.length }, (_, index) => index)
                const seriesData = {
                    name: String(index + 1),
                    type: 'line',
                    data: yData,
                }
                option.legend.data.push(String(index + 1))
                option.series.push(seriesData)
                chart.value.setOption(option)
            } else {
                ElMessage.warning('查询失败1')
            }
        } else {
            ElMessage.warning('查询失败')
        }
    })
}

const statAnalysisExport = () => {}
const statAnalysiImport = () => {}

const timestampToTime = (timestamp) => {
    timestamp = timestamp ? timestamp : null
    let date = new Date(timestamp)
    let Y = date.getFullYear() + '-'
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
    let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    return Y + M + D + h + m
}
</script>
<style scoped lang="scss">
.statAnalysis {
    height: 100%;
    .headerPart {
        padding: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .topLeft {
            display: flex;
            .icon {
                width: 40px;
                height: 40px;
                padding: 10px 0;
            }
            .selectPart {
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 40px;
                margin-right: 20px;
                span {
                    margin-right: 10px;
                }
                .statAnalysisSelect {
                    width: 200px;
                    :deep(.el-select__wrapper) {
                        height: 40px;
                    }
                    :deep(.el-input__inner) {
                        height: 38px;
                    }
                }
                .max,
                .min,
                .average {
                    border-radius: 6px;
                    height: 40px;
                    width: 72px;
                    text-align: center;
                    line-height: 40px;
                }
                .max {
                    background: rgba(254, 55, 49, 0.2);
                    border: 1px solid #fe3731;
                    color: #fe3731;
                }
                .min {
                    background: rgba(0, 160, 150, 0.2);
                    border: 1px solid #00a096;
                    color: #00a096;
                }
                .average {
                    background: rgba(0, 100, 170, 0.2);
                    border: 1px solid #0064aa;
                    color: #0064aa;
                }
            }
            .dialog-footer button:first-child {
                margin-right: 10px;
            }
        }
        .topRight {
            // width: 436px;
            display: flex;
            justify-content: space-between;
            .el-button {
                width: 100px;
                height: 40px;
            }
        }
    }
    .timeColumns {
        max-height: 120px;
        overflow: hidden;
        .headerPart {
            padding: 10px 20px;
        }
        &.expand {
            max-height: max-content;
            height: auto;
            overflow: inherit;
        }
    }
    .timeColumns.expand + div.ralIcon {
        transform: rotate(-90deg);
    }
    .ralIcon {
        width: 100%;
        text-align: center;
        transform: rotate(90deg);
    }
    #myEChart {
        width: 100%;
        height: 300px;
    }
}
</style>
