<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>
                <el-button class="addline" type="primary" :icon="Plus" @click="addTime()"> 增加时间</el-button>
            </div>
            <div class="topRight">
                <el-button type="primary" :loading="isLoading" @click="statAnalysisOperate()">{{ t('statAnalysis.search') }}</el-button>
                <el-button style="color: #0064aa" @click="statAnalysisExport()">{{ t('statAnalysis.export') }}</el-button>
            </div>
        </el-header>
        <div class="main">
            <div
                ref="chartContainer"
                style="height: calc(100% - 140px); width: calc(100% - 60px); border: 1px solid rgb(217, 217, 217); margin: 40px"
            ></div>
        </div>
        <el-dialog v-model="showMeasure" title="选择测点" :width="800">
            <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>
        <el-dialog v-model="showTime" title="选择时间" :width="800">
            <div>
                <div class="selectPart">
                    <span>{{ t('statAnalysis.time') }}</span>
                    <el-date-picker
                        class="datetime-picker"
                        v-model="time"
                        :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"
                    />
                </div>
                <div class="transferRight">
                    <div class="transferHeader">
                        <span class="transferTitle"
                            >已选择<span>{{ times.length }}</span
                            >项</span
                        >
                        <div @click="clearList" style="color: rgb(0, 100, 170); cursor: pointer">清空</div>
                    </div>
                    <el-main class="transferMain">
                        <el-scrollbar>
                            <div class="selectItem" v-for="(item, index) in times" :key="index">
                                {{ statAnalysisSelect.attributes + (index + 1) }} : {{ item[0] }} 至 {{ item[1] }}
                                <div>
                                    <el-icon :size="20" @click="switchTime(index)"><Close /></el-icon>
                                </div>
                            </div>
                        </el-scrollbar>
                    </el-main>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="showTime = false"> 确认 </el-button>
                    <el-button @click="showTime = 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, Close } from '@element-plus/icons-vue'
import MeasurementPage from './analysisAttributes.vue'
import { getModelAttributeListReq } from '/@/api/backend/deviceModel/request'

import * as echarts from 'echarts'
const { t } = useI18n()
const statAnalysisSelect = reactive({
    deviceId: '',
    attributes: '',
    attributeCode: '',
    interval: '1h',
    time: '',
    unit: '',
})
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 time: any = ref([getFormattedDate(0) + ' 00:00:00', getFormattedDate(0) + ' 23:59:59'])
const times: any = reactive([[getFormattedDate(0) + ' 00:00:00', getFormattedDate(0) + ' 23:59:59']])
const addTime = () => {
    time.value = [getFormattedDate(0) + ' 00:00:00', getFormattedDate(0) + ' 23:59:59']
    showTime.value = true
}
const switchTime = (index: number) => {
    if (index == 0) {
        time.value = []
    }
    times.splice(index, 1)
    customName.splice(index, 1)
    customName.forEach((item: any, index: number, arr: any) => {
        arr[index] = statAnalysisSelect.attributes + String(index + 1)
    })
}
const timechange = (value: any) => {
    if (times.length) {
        const count = getTimeIntervals(times[0][0], times[0][1])
        const count1 = getTimeIntervals(value[0], value[1])
        if (count !== count1) {
            ElMessage.warning('查询时间点错误，请重新输入')
            return
        } else if (hasDuplicateArrays(value)) {
            ElMessage.info('存在相同的查询时间！')
            return
        } else {
            times.push(value)

            customName.push(statAnalysisSelect.attributes + times.length)
            customName.forEach((item: any, index: number, arr: any) => {
                arr[index] = statAnalysisSelect.attributes + String(index + 1)
            })
        }
    } else {
        times.push(value)
        customName.push(statAnalysisSelect.attributes + times.length)
        customName.forEach((item: any, index: number, arr: any) => {
            arr[index] = statAnalysisSelect.attributes + String(index + 1)
        })
    }
}

const showTime = ref(false)
const clearList = () => {
    times.length = 0
    time.value = []
    customName.length = 0
}

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 = ''
    statAnalysisSelect.unit = ''
}

const showMeasure = ref(false)
const selectedAttrRow: any = ref({
    attributeCode: '',
    attributeName: '',
    unit: '',
})
const handleRadioChange = (value: any) => {
    const { attributeCode, attributeName, unit } = { ...value }
    selectedAttrRow.attributeCode = attributeCode
    selectedAttrRow.attributeName = attributeName
    selectedAttrRow.unit = unit
}
const selectstatAnalysisAttributes = () => {
    statAnalysisSelect.attributes = selectedAttrRow.attributeName
    statAnalysisSelect.attributeCode = selectedAttrRow.attributeCode
    statAnalysisSelect.unit = selectedAttrRow.unit
    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: {},
}

const statAnalysisSelectOptions: any = reactive({
    interval: [
        { label: '一分钟', value: '1m' },
        { label: '五分钟', value: '5m' },
        { label: '十分钟', value: '10m' },
        { 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))
    }
    queryWindTurbines().then((res: any) => {
        statAnalysisSelect.deviceId = res.value
        getAttributeList({
            iotModelId: res.iotModelId,
            pageNum: 1,
            pageSize: 10,
            attributeType: '138',
        }).then((attrRes: any) => {
            statAnalysisSelect.attributes = attrRes.attributeName
            statAnalysisSelect.attributeCode = attrRes.attributeCode
            statAnalysisSelect.unit = attrRes.unit
            selectedAttrRow.attributeCode = attrRes.attributeCode
            selectedAttrRow.attributeName = attrRes.attributeName
            selectedAttrRow.unit = attrRes.unit
            customName.forEach((item: any, index: number, arr: any) => {
                arr[index] = statAnalysisSelect.attributes + String(index + 1)
            })
            statAnalysisOperate()
        })
    })
})

const getAttributeList = (requestData: any) => {
    return new Promise((resolve) => {
        getModelAttributeListReq(requestData)
            .then((res: any) => {
                if (res.rows && res.rows.length > 0) {
                    resolve(res.rows[0])
                } else {
                }
            })
            .catch((err: any) => {
                ElMessage.error(err?.response?.data?.msg ?? '查询失败')
            })
    })
}

const queryWindTurbines = () => {
    return new Promise((resolve) => {
        queryWindTurbinesPages()
            .then((res) => {
                if (res.code == 200) {
                    statAnalysisSelectOptions.deviceId = res.data.map((item: any) => {
                        return {
                            value: item.irn,
                            label: item.name ?? '-',
                            iotModelId: item.modelId,
                        }
                    })
                    resolve(statAnalysisSelectOptions.deviceId[0])
                } else {
                    ElMessage.error(res.msg)
                }
            })
            .catch((err) => {
                ElMessage.error(err ?? '查询失败')
            })
    })
}

const radioActiveName = ref(138)

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

const shortcuts = [
    {
        text: '今天',
        value: () => {
            const start = getFormattedDate(0) + ' 00:00:00'
            const end = getFormattedDate(0) + ' 23:59:59'
            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 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 '1m':
            count = Math.floor((endDate - startDate) / (60 * 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 '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:
            count = Math.floor((endDate - startDate) / (5 * 60 * 1000))
    }

    return count
}
const calculate: any = ref([{ max: '', min: '', average: '' }])
var xDatas: any = []
const isLoading = ref(false)
const statAnalysisOperate = () => {
    const findTime = times.filter((item: any) => {
        return Array.isArray(item)
    })
    if (!statAnalysisSelect.deviceId) {
        ElMessage.info('请选择风机！')
        return
    } else if (!statAnalysisSelect.attributeCode) {
        ElMessage.info('请选择测点名称！')
        return
    } else if (!findTime.length) {
        ElMessage.info('请选择查询时间！')
        return
    }
    isLoading.value = true
    option.series = []
    option.legend.data = []
    xDatas = []
    calculate.value = []
    chart.value.setOption(option, { notMerge: true })
    const promises: any = []

    times.forEach((time: any, index: number) => {
        if (time && 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(),
            }
            const promise = new Promise((resolve, reject) => {
                historyReq(requestData)
                    .then((res) => {
                        if (res.code == 200) {
                            resolve(res.data)
                        } else {
                            ElMessage.warning('查询失败')
                        }
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
            promises.push(promise)
        }
    })
    historyDataReq(promises)
}

const historyDataReq = (promises: any) => {
    Promise.all(promises)
        .then((results: any) => {
            isLoading.value = false
            const deviceId = statAnalysisSelect.deviceId
            const attributeCode = statAnalysisSelect.attributeCode
            results.forEach((res: any, index: number) => {
                const resData = (res && deviceId in res && res[deviceId][attributeCode]) || undefined
                if (!resData['values'].length) {
                    ElMessage.info(`${customName[index]}数据为空`)
                    return
                }
                const alltimes = getTimestamps(
                    new Date(times[index][0]).getTime(),
                    new Date(times[index][1]).getTime(),
                    statAnalysisSelect.interval || '5m'
                )
                const fillData = fillMissingData(alltimes, resData)
                const xData = fillData['times']
                const yData = fillData['values']
                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}${statAnalysisSelect.unit}`
                            })
                            .join('<br/>')
                    },
                }
                option.xAxis.data = Array.from({ length: xData.length }, (_, index) => index)
                const seriesData = {
                    name: customName[index],
                    type: 'line',
                    data: yData,
                    showSymbol: true,
                    animation: false,
                }
                option.legend.data.push(customName[index])
                option.series.push(seriesData)
                chart.value.setOption(option)
            })
        })
        .catch((error) => {
            isLoading.value = false
            console.error(error)
            ElMessage.warning(error)
        })
}

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('🚀 ~ times.forEach ~ requestData:', 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)
    })
}

const hasDuplicateArrays = (arr: any) => {
    arr = [...times, arr]
    const seen = new Set()
    for (let subArray of arr) {
        const subArrayStr = JSON.stringify(subArray)
        if (seen.has(subArrayStr)) {
            return true
        }
        seen.add(subArrayStr)
    }
    return false
}

const getTimestamps = (start: any, end: any, interval: any) => {
    let timestamps = []
    let current = start

    while (current < end) {
        timestamps.push(current)
        switch (interval) {
            case '1m':
                current += 60 * 1000
                break
            case '5m':
                current += 5 * 60 * 1000
                break
            case '10m':
                current += 10 * 60 * 1000
                break
            case '1d':
                current += 24 * 60 * 60 * 1000
                break
            case '15m':
                current += 15 * 60 * 1000
                break
            case 'NONE':
                current += 40 * 1000
                break
            case '1h':
                current += 60 * 60 * 1000
                break
            default:
                throw new Error('Unsupported interval')
        }
    }

    return timestamps
}

const fillMissingData = (intervals: any, data: any) => {
    const { times, values } = data
    const filledTimes: any = []
    const filledValues: any = []
    intervals.forEach((time: any) => {
        const index = times.indexOf(time)
        filledTimes.push(time)
        if (index !== -1) {
            filledValues.push(values[index])
        } else {
            filledValues.push('')
        }
    })
    return { times: filledTimes, values: filledValues }
}
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%;
    .contain {
        height: calc(100% - 60px);
        // display: flex;
        .main {
            display: flex;
            height: calc(100% - 60px);

            .right {
                width: calc(100% - 418px);
                height: 100%;
            }
        }

        .headerPart {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
            height: 60px;
            .addline {
                height: 40px;
            }
            .topLeft {
                display: flex;
                .icon {
                    width: 40px;
                    height: 40px;
                    padding: 10px 0;
                }
                .dialog-footer button:first-child {
                    margin-right: 10px;
                }
            }
            .topRight {
                display: flex;
                margin: 12px 0;
                .el-button {
                    width: 100px;
                    height: 40px;
                }
            }
        }
    }

    .timeColumns {
        .moduleRow {
            .item {
                position: relative;
                margin: 0px 12px 12px;
                padding: 12px 12px 8px;
                border-radius: 20px;
                box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
                .topLeft {
                    display: flex;
                }
                .selectPart {
                    width: 388px;
                    justify-content: left;
                    margin: 4px;
                    span {
                        white-space: nowrap;
                    }
                }
            }
        }
        .removeModule {
            position: absolute;
            top: 6px;
            right: 8px;
            color: rgba(0, 0, 0, 0);
            cursor: pointer;
            transition: color 0.5s;
        }
        &:hover {
            .removeModule {
                color: rgba(0, 0, 0, 0.55);
                border: 1px solid rgba(0, 0, 0, 0.55);
                border-radius: 50px;
            }
        }
        .headerPart {
            padding: 2px 20px;
        }
    }
    .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;
            }
        }
        .customName {
            width: 360px;
        }
    }
    #myEChart {
        width: 100%;
        height: 300px;
    }
    .transferRight {
        height: 400px;
        border: 1px solid #e1edf6;
        border-radius: 6px;
        margin-top: 20px;
        .transferHeader {
            height: 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 10px;
            color: #333333;
            background: #f7f9fc;
            border-bottom: 1px solid #e1edf6;
            border-radius: 6px 6px 0 0;
        }
        .transferMain {
            padding: 0;
            :deep(.el-table__row) {
                height: 40px;
                padding: 0 20px;
                background: #eff0f1;
                border-radius: 4px;
            }
            .selectItem {
                height: 40px;
                padding: 0 20px;
                background: #eff0f1;
                border-radius: 4px;
                margin: 10px;
                list-style: none;
                display: flex;
                justify-content: space-between;
                align-items: center;
                .el-icon {
                    cursor: pointer;
                }
            }
        }
        .mainFooter {
            padding: 10px;
        }
    }
}
</style>
