<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="deviceIdChange"
                        :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="attributesChange"
                        :placeholder="'请选择' + t('statAnalysis.attributes')"
                    ></el-input>
                </div>
                <div class="selectPart">
                    <span>{{ t('statAnalysis.interval') }}</span>
                    <el-select v-model="statAnalysisSelect.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="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">
                        <el-input v-model="customName[index]" class="customName"></el-input>
                        <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"
                            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
                            @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; border: 1px solid rgb(217, 217, 217)"></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" :irn="irn" @handleRadioChange="handleRadioChange"></MeasurementPage>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="selectstatAnalysisAttributes"> 保存 </el-button>
                    <el-button @click="showMeasure = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, markRaw } from 'vue'
import { useI18n } from 'vue-i18n'
import { queryWindTurbinesPages, historyReq, trendAnalyseExport } from '/@/api/backend/statAnalysis/request'
import { ElMessage } 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: any = reactive([{ time: '' }])
const addTime = (index: any) => {
    times.push({ time: '' })
    customName.push(statAnalysisSelect.attributes + String(index + 2))
}
const switchTime = (index: number) => {
    times.splice(index, 1)
    customName.splice(index, 1)
    calculate.splice(index, 1)
}
const timechange = (value: any) => {
    const count = getTimeIntervals(times[0][0], times[0][1])
    const count1 = getTimeIntervals(times[value][0], times[value][1])
    if (count !== count1) {
        times[value] = { time: '' }
        ElMessage.warning('查询时间点错误，请重新输入')
    }
}
const isExpand = ref(false)
const handleClick = () => {
    isExpand.value = !isExpand.value
}

const iotModelId = ref('')
const irn = ref('')
const attributesChange = () => {
    const row: any = statAnalysisSelectOptions.deviceId.filter((item: any) => {
        return item.value == statAnalysisSelect.deviceId
    })
    if (row.length) {
        iotModelId.value = row[0].iotModelId
        showMeasure.value = true
        irn.value = statAnalysisSelect.attributeCode || ''
    } else {
        ElMessage.warning('请选择风机！！')
    }
}

const deviceIdChange = () => {
    statAnalysisSelect.attributes = ''
    statAnalysisSelect.attributeCode = ''
}

const showMeasure = ref(false)
const selectedAttrRow: any = ref({
    attributeCode: '',
    attributeName: '',
})
const handleRadioChange = (value: any) => {
    const { attributeCode, attributeName } = { ...value }
    selectedAttrRow.attributeCode = attributeCode
    selectedAttrRow.attributeName = attributeName
}
const selectstatAnalysisAttributes = () => {
    statAnalysisSelect.attributes = selectedAttrRow.attributeName
    statAnalysisSelect.attributeCode = selectedAttrRow.attributeCode
    showMeasure.value = false
    customName.forEach((item: any, index: number, arr: any) => {
        arr[index] = statAnalysisSelect.attributes + String(index + 1)
    })
}

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

const option: any = {
    tooltip: {},
    legend: {
        icon: 'circle',
        itemGap: 20,
        itemWidth: 8,
        itemHeight: 8,
        data: [],
    },
    xAxis: {
        data: [],
    },
    yAxis: {
        type: 'value',
    },
    series: [],
    grid: {
        left: '3%',
        right: '3%',
    },
}

const statAnalysisSelectOptions: any = reactive({
    interval: [
        { label: '五分钟', value: '5m' },
        { label: '十五分钟', value: '15m' },
        { label: '一小时', value: '1h' },
        { label: '一天', value: '1d' },
        { label: '原始', value: 'NONE' },
    ],
    deviceId: [],
})
const customName = reactive([statAnalysisSelect.attributes + '1'])
const chart: any = ref(null)

onMounted(() => {
    if (chartContainer.value) {
        chart.value = markRaw(echarts.init(chartContainer.value))
        chart.value.setOption({
            xAxis: {
                type: 'category',
            },
            yAxis: {
                type: 'category',
            },
            series: [
                {
                    type: 'line',
                },
            ],
            grid: {
                left: '3%',
                right: '3%',
            },
        })
    }
    queryWindTurbines()
})
const queryWindTurbines = () => {
    queryWindTurbinesPages().then((res) => {
        if (res.code == 200) {
            statAnalysisSelectOptions.deviceId = res.data.map((item: any) => {
                return {
                    value: item.irn,
                    label: item.name ?? '-',
                    iotModelId: item.modelId,
                }
            })
        }
    })
}

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

const shortcuts = [
    {
        text: '今天',
        value: () => {
            const start = getFormattedDate(0) + ' 00:00:00'
            const end = new Date()
            return [start, end]
        },
    },
    {
        text: '昨天',
        value: () => {
            const start = getFormattedDate(-1) + ' 00:00:00'
            const end = getFormattedDate(-1) + ' 23:59:59'
            return [start, end]
        },
    },
    {
        text: '前3天',
        value: () => {
            const start = getFormattedDate(-3) + ' 00:00:00'
            const end = getFormattedDate(-1) + ' 23:59:59'
            return [start, end]
        },
    },
    {
        text: '本周',
        value: () => {
            return getDateRange('week')
        },
    },
    {
        text: '本月',
        value: () => {
            return getDateRange('month')
        },
    },
]
const getFormattedDate = (offset: number) => {
    const date = new Date()
    date.setDate(date.getDate() + offset)

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}
const getDateRange = (type: 'week' | 'month') => {
    const today = new Date()
    if (type === 'week') {
        const dayOfWeek = today.getDay()
        const startOfWeek = new Date(today)
        startOfWeek.setDate(today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1))
        startOfWeek.setHours(0, 0, 0, 0)
        const endOfWeek = new Date(startOfWeek)
        endOfWeek.setDate(startOfWeek.getDate() + 6)
        endOfWeek.setHours(23, 59, 59, 999)
        return [startOfWeek, endOfWeek]
    }
    if (type === 'month') {
        const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
        startOfMonth.setHours(0, 0, 0, 0)
        const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0)
        endOfMonth.setHours(23, 59, 59, 999)
        return [startOfMonth, endOfMonth]
    }
}
const getTimeIntervals = (startTimestamp: number, endTimestamp: number) => {
    const startDate: any = new Date(startTimestamp)
    const endDate: any = 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 = Math.floor((endDate - startDate) / (1 * 24 * 60 * 60 * 1000))
            break
        // default:
        // throw new Error('Invalid interval')
    }

    return count
}
const calculate: any = reactive([{ max: '', min: '', average: '' }])
var xDatas: any = []
const statAnalysisOperate = () => {
    option.series = []
    option.legend.data = []
    xDatas = []
    chart.value.setOption(option, { notMerge: true })
    times.forEach((time: any, index: number) => {
        if (time[0] && time[1]) {
            const requestData = {
                devices: [
                    {
                        deviceId: statAnalysisSelect.deviceId,
                        attributes: [statAnalysisSelect.attributeCode],
                    },
                ],
                interval: statAnalysisSelect.interval || '5m',
                startTime: new Date(time[0]).getTime(),
                endTime: new Date(time[1]).getTime(),
            }
            historyDataReq(requestData, index)
        }
    })
}

const historyDataReq = (data: any, index: number) => {
    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] = calculateStats(yData)
                xDatas.push({
                    series: String(customName[index]),
                    data: xData,
                })
                option.tooltip = {
                    show: true,
                    trigger: 'axis',
                    formatter: function (params: any) {
                        return params
                            .map((item: any) => {
                                const matchData = xDatas.filter((x: any) => x.series == item.seriesName)
                                const x = timestampToTime(matchData[0]['data'][item.dataIndex])
                                return `${item.marker}${item.seriesName} (${x}): ${item.data}`
                            })
                            .join('<br/>')
                    },
                }
                option.xAxis.data = Array.from({ length: xData.length }, (_, index) => index)
                const seriesData = {
                    name: customName[index],
                    type: 'line',
                    data: yData,
                    showSymbol: true,
                }
                option.legend.data.push(customName[index])
                option.series.push(seriesData)
                chart.value.setOption(option)
            } else {
                ElMessage.warning('查询失败1')
            }
        } else {
            ElMessage.warning('查询失败')
        }
    })
}

const statAnalysisExport = () => {
    const requestData: any = []
    times.forEach((time: any, index: number) => {
        if (time[0] && time[1]) {
            const devices = {
                devices: [
                    {
                        deviceId: statAnalysisSelect.deviceId,
                        attributes: [statAnalysisSelect.attributeCode],
                    },
                ],
                interval: statAnalysisSelect.interval || '5m',
                startTime: new Date(time[0]).getTime(),
                endTime: new Date(time[1]).getTime(),
                timeName: customName[index],
            }
            requestData.push(devices)
        }
    })
    console.log(requestData)
    trendAnalyseExport(requestData).then((res: any) => {
        const downloadUrl = window.URL.createObjectURL(res)
        const a = document.createElement('a')
        a.href = downloadUrl
        a.download = '趋势分析' + new Date().getTime()
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(downloadUrl)
        document.body.removeChild(a)
    })
}

function calculateStats(numbers: any) {
    const max = Math.max(...numbers)
    const min = Math.min(...numbers)
    const sum = numbers.reduce((acc: number, current: number) => acc + current, 0)
    const average = sum / numbers.length

    return {
        max: max.toFixed(2),
        min: min.toFixed(2),
        average: average.toFixed(2),
    }
}
const timestampToTime = (timestamp: any) => {
    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;
                }
                .customName {
                    width: 120px;
                    margin-right: 10px;
                }
            }
            .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>
