<template>
    <div
        class="default-main device-control"
        :style="{ height: pageHeight.height }"
        v-loading="loading"
        style="position: relative"
    >
        <PointTree @node-click="nodeClick" @init="nodeClick"></PointTree>
        <div class="device-control-right" v-if="deviceData">
            <el-descriptions title="设备基本信息" class="mb10" :column="3" border>
                <template #extra>
                    <el-button
                        v-if="dataSet.indexOf('_realtimedata') != -1"
                        size="small"
                        type="primary"
                        @click="handleDownLoadTemplate"
                    >
                        模版下载
                    </el-button>
                    <el-button
                        v-if="dataSet.indexOf('_realtimedata') != -1"
                        size="small"
                        type="primary"
                        @click="handleImport"
                    >
                        离线数据导入
                    </el-button>
                    <el-button
                        v-if="dataSet.indexOf('_realtimedata') != -1"
                        size="small"
                        type="primary"
                        @click="handleaddDevice"
                    >
                        设备补招
                    </el-button>
                    <el-button
                        v-if="dataSet.indexOf('_realtimedata') != -1"
                        size="small"
                        type="primary"
                        @click="handleAnalysisList"
                    >
                        解析列表
                    </el-button>
                </template>
                <el-descriptions-item label="名称">
                    {{ deviceData.name ? deviceData.name : '/' }}
                </el-descriptions-item>
                <el-descriptions-item label="类型">
                    {{ echoName(deviceData.devType, devTypeOptions) }}
                </el-descriptions-item>

                <el-descriptions-item label="接入方式">
                    {{ deviceData.devAccessMethod ? deviceData.devAccessMethod : '/' }}
                </el-descriptions-item>
                <el-descriptions-item label="识别码">
                    {{ deviceData.ndid ? deviceData.ndid : '/' }}
                </el-descriptions-item>
                <el-descriptions-item label="型号">
                    {{ echoName(deviceData.devModel, devModelOptions) }}
                </el-descriptions-item>
                <el-descriptions-item label="接入时间">
                    {{ deviceData.time ? deviceData.time : '/' }}
                </el-descriptions-item>
            </el-descriptions>
            <el-tabs v-model="dataSet" type="border-card" class="device-control-box-card" @tab-click="handleClick">
                <el-tab-pane
                    lazy
                    :label="item.name"
                    :name="item.id"
                    v-for="(item, index) in deviceData.dataSetList"
                    :key="index"
                ></el-tab-pane>
                <el-form
                    :inline="true"
                    style="white-space: nowrap; margin-top: 10px"
                    v-if="
                        dataSet.indexOf('_trenddata') == -1 &&
                        dataSet.indexOf('_realtimedata') == -1 &&
                        dataSet.indexOf('_event') == -1
                    "
                >
                    <el-form-item label="指标">
                        <el-input
                            v-model="formInline.searchValue"
                            autocomplete="off"
                            clearable
                            placeholder="请输入关键词"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="日期" v-show="dataSet.indexOf('_history') != -1">
                        <DatePicker ref="datePickerRef"></DatePicker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-Search" @click="handleClick">查询</el-button>
                    </el-form-item>
                </el-form>
                <div
                    style="overflow: auto"
                    :style="{ height: tableHeight }"
                    v-loading="tableLoading"
                    v-if="
                        dataSet.indexOf('_trenddata') == -1 &&
                        dataSet.indexOf('_realtimedata') == -1 &&
                        dataSet.indexOf('_event') == -1 &&
                        tableData.length != 0
                    "
                >
                    <!-- 循环渲染的card 最新数据/历史数据显示 -->
                    <div class="content">
                        <el-card class="box-card" v-for="(item, index) in tableData" :key="index">
                            <template #header>
                                <div class="clearfix">
                                    <span style="flex: 1">{{ item.name }}</span>
                                    <Icon
                                        name="el-icon-TrendCharts"
                                        class="ml10"
                                        @click="getDeviceDataTrend(item)"
                                        style="font-size: 26px; cursor: pointer; color: #fff"
                                    ></Icon>
                                </div>
                            </template>
                            <!-- 模块数据 -->
                            <div class="box-card-content" v-if="dataSet.indexOf('_history') == -1">
                                <div v-for="(child, childIndex) in item.children" :key="childIndex">
                                    {{ child.anotherName }}:
                                    {{ child.dataValue === 3.1415926 ? '暂无数据' : child.dataValue }}
                                </div>
                                <div class="mt10">
                                    统计时间：{{ item.children.length ? item.children[0].time : '' }}
                                </div>
                            </div>
                            <div v-else-if="item.children.length">
                                <div style="display: flex; align-items: center">
                                    <el-tag
                                        effect="dark"
                                        type="danger"
                                        style="width: 40px; text-align: center"
                                        class="mr10"
                                    >
                                        MAX
                                    </el-tag>
                                    {{
                                        item.children[0].maxValue === 3.1415956 || !item.children[0].maxValue
                                            ? '暂无数据'
                                            : item.children[0].maxValue
                                    }}
                                </div>
                                <div style="display: flex; align-items: center" class="mt10">
                                    <el-tag
                                        effect="dark"
                                        type="success"
                                        style="width: 40px; text-align: center"
                                        class="mr10"
                                    >
                                        AVG
                                    </el-tag>
                                    {{
                                        item.children[0].avgValue === 3.1415956 || !item.children[0].avgValue
                                            ? '暂无数据'
                                            : item.children[0].avgValue
                                    }}
                                </div>
                                <div style="display: flex; align-items: center" class="mt10">
                                    <el-tag
                                        effect="dark"
                                        type="warning"
                                        style="width: 40px; text-align: center"
                                        class="mr10"
                                    >
                                        MIN
                                    </el-tag>
                                    <!-- || !item.children[0].minValue -->
                                    {{
                                        item.children[0].minValue === 3.1415956 
                                            ? '暂无数据'
                                            : item.children[0].minValue
                                    }}
                                </div>
                            </div>
                        </el-card>
                        <el-empty description="暂无数据" v-if="tableData.length === 0"></el-empty>
                    </div>
                </div>
                <el-pagination
                    v-if="
                        tableData.length &&
                        dataSet.indexOf('_trenddata') == -1 &&
                        dataSet.indexOf('_realtimedata') == -1 &&
                        dataSet.indexOf('_event') == -1
                    "
                    background
                    class="mr2 mt10"
                    style="float: right"
                    @size-change="handleSizeChange"
                    @current-change="pageChange"
                    :current-page="formInline.pageNum"
                    :page-sizes="[20, 30, 40, 50, 100]"
                    :page-size="formInline.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="formInline.total"
                ></el-pagination>

                <!-- 趋势数据 -->
                <div style="height: calc(100vh - 200px)" v-show="dataSet.indexOf('_trenddata') != -1">
                    <Trend ref="trendRef"></Trend>
                </div>
                <!-- 实时数据 -->
                <div style="height: calc(100vh - 200px)" v-if="dataSet.indexOf('_realtimedata') != -1">
                    <div class="view_top_btn" v-if="realTimeFlag">
                        <!-- <el-button type="primary" size="small" :icon="Platform" @click="handleRecordWaves">
                            实时录波
                        </el-button> -->
                        <el-button type="primary" size="small" :icon="TrendCharts" @click="handleTrend">
                            实时趋势
                        </el-button>
                        <el-button type="primary" size="small" :icon="DataLine" @click="handleHarmonicSpectrum">
                            谐波频谱
                        </el-button>
                    </div>
                    <div class="view_top_btn" v-if="!realTimeFlag">
                        <el-button type="primary" :icon="ArrowLeft" size="small" @click="handleReturn">返回</el-button>
                    </div>
                    <!-- 实时数据主界面组件 -->
                    <realTime v-if="realTimeFlag" ref="realTimeRef"></realTime>
                    <!-- 实时数据-实时录波组件 -->
                    <recordWoves v-if="!realTimeFlag && sonTab == 0"></recordWoves>
                    <!-- 实时数据-实时趋势组件 -->
                    <realTrend v-show="!realTimeFlag && sonTab == 1" ref="realTrendRef"></realTrend>
                    <!-- 实时数据-谐波频谱组件 -->
                    <harmonicSpectrum
                        v-show="!realTimeFlag && sonTab == 2"
                        ref="harmonicSpectrumRef"
                    ></harmonicSpectrum>
                </div>
                <!-- 暂态事件 -->
                <div style="height: calc(100vh - 200px)" v-show="dataSet.indexOf('_event') != -1">
                    <Event ref="eventRef"></Event>
                </div>
                <div v-if="!tableData" style="height: 42px"></div>
            </el-tabs>
        </div>
        <el-empty v-else description="请选择设备" class="device-control-right" />
        <Detail ref="detailRef" :detail="detail" @close="detail = null" v-if="detail"></Detail>
        <!-- 离线数据导入组件 -->
        <offLineDataImport ref="offLineDataImportRef"></offLineDataImport>
        <!-- 解析列表 -->
        <analysisList ref="analysisListRef"></analysisList>
    </div>
</template>
<script setup lang="ts">
import Detail from './detail.vue'
import PointTree from '@/components/tree/govern/pointTree.vue'
import { mainHeight } from '@/utils/layout'
import { queryByCode, queryByid, queryCsDictTree } from '@/api/system-boot/dictTree'
import { getDeviceData, getTabsDataByType } from '@/api/cs-device-boot/EquipmentDelivery'
import { deviceHisData, deviceRtData, getGroup } from '@/api/cs-device-boot/csGroup'
import { ref, reactive, nextTick, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import DatePicker from '@/components/form/datePicker/index.vue'
import Trend from './tabs/trend.vue' //趋势数据
import realTime from './tabs/realtime.vue' //实时数据-主界面
import realTrend from './tabs/components/realtrend.vue' //实时数据-实时趋势
import harmonicSpectrum from './tabs/components/harmonicSpectrum.vue' //实时数据-谐波频谱子页面
import recordWoves from './tabs/components/recordwoves.vue' //实时数据-实时录波子页面
import offLineDataImport from './offLineDataImport/index.vue'
import Event from './tabs/event.vue'
import { useRouter } from 'vue-router'
import { defineConfig, loadEnv } from 'vite'
import type { UserConfig, ConfigEnv } from 'vite'
import { Platform, TrendCharts, DataLine, ArrowLeft } from '@element-plus/icons-vue'
import analysisList from './analysisList/index.vue'
defineOptions({
    name: 'govern/device/control'
})
const pageHeight = mainHeight(20)
const loading = ref(true)
const tableLoading = ref(false)
const getGroupLoading = ref(false)
const deviceData = ref<any>(null)
const dataSet = ref('')
const devTypeOptions = ref([])
const devModelOptions = ref([])
const tableData = ref<any[]>([])
const tableHeight = mainHeight(330).height
const mangePopup = ref()
const datePickerRef = ref()
const formInline = reactive({
    searchValue: '',
    pageNum: 1,
    pageSize: 30,
    total: 0,
    startTime: '',
    endTime: '',
    id: '',
    lineId: ''
})
const detail = ref<any>(null)
//是否显示实时数据默认内容
const realTimeFlag = ref(true)
//实时数据子菜单
const sonTab = ref()
//实时录波
const handleRecordWaves = () => {
    realTimeFlag.value = false
    sonTab.value = 0
    window.clearInterval(timer.value)
}
//实时趋势
const realTrendRef = ref()
const handleTrend = () => {
    realTimeFlag.value = false
    sonTab.value = 1
    realTrendRef.value && realTrendRef.value.open({ devId: deviceId.value, lineId: lineId.value })
    window.clearInterval(timer.value)
}
//谐波频谱
const harmonicSpectrumRef = ref()
const handleHarmonicSpectrum = () => {
    realTimeFlag.value = false
    sonTab.value = 2
    harmonicSpectrumRef.value &&
        harmonicSpectrumRef.value.getHarmonicSpectrumParams({ devId: deviceId.value, lineId: lineId.value })
    window.clearInterval(timer.value)
}
//返回
const handleReturn = () => {
    realTimeFlag.value = true
    sonTab.value = null
    handleClick()
}
const getDeviceDataTrend = (e: any) => {
    detail.value = {
        devId: deviceId.value,
        lineId: lineId.value,
        ...e
    }
}
const pageChange = (e: number) => {
    formInline.pageNum = e
    handleClick()
}
const handleSizeChange = (val: number) => {
    formInline.pageNum = 1
    formInline.pageSize = val
    handleClick()
}
const { push, options, currentRoute } = useRouter()
//设备补招
const handleaddDevice = () => {
    push({
        path: '/supplementaryRecruitment',
        query: {
            id: '1111'
        }
    })
}
//树节点点击事件
const deviceId: any = ref('')
const lineId: any = ref('')
const nodeClick = async (e: anyObj) => {
    deviceId.value = e?.pid
    lineId.value = e?.id
    if (!e) {
        loading.value = false
        return
    }
    if (e.level == 3) {
        loading.value = true
        formInline.lineId = e.id
        await getDeviceData(e.pid, 'history', e.id).then((res: any) => {
            deviceData.value = res.data
            if (!res.data.dataSetList) {
                dataSet.value = ''
                tableData.value = []
            } else {
                res.data.dataSetList.forEach((item: any) => {
                    //历史
                    if (item.type === 'history') {
                        item.id = item.id + '_history'
                    }
                    //趋势数据
                    if (item.type === 'trenddata') {
                        item.id = item.id + '_trenddata'
                    }
                    //实时数据
                    if (item.type === 'realtimedata') {
                        item.id = item.id + '_realtimedata'
                    }
                    //暂态事件
                    if (item.type === 'event') {
                        item.id = item.id + '_event'
                    }
                })
                dataSet.value = res.data.dataSetList[0].id
                handleClick()
            }
            loading.value = false
        })
    } else {
        loading.value = false
    }
}
const realTimeRef: any = ref()
const intRealTime = async (val: any) => {
    await getTabsDataByType(val).then(res => {
        realTimeRef.value && realTimeRef.value.getRealTimeData(res.data)
    })
    timer.value = window.setInterval(async () => {
        await getTabsDataByType(val).then(res => {
            realTimeRef.value && realTimeRef.value.getRealTimeData(res.data)
        })
    }, 20000)
}
//趋势数据组件
const trendRef: any = ref()
//暂态事件组件
const eventRef: any = ref()
const timer: any = ref()
//tab点击事件
const handleClick = async (tab?: any) => {
    //点击tab时更新dataSet最新值
    if (tab && tab.props && tab.props.name && dataSet.value != tab.props.name) {
        dataSet.value = tab.props.name
    }

    tableLoading.value = true
    //初始化点击tab隐藏实时录波、实时趋势、谐波频谱按钮
    realTimeFlag.value = false
    //初始化点击tab隐藏子页面
    sonTab.value = null
    if (tab) {
        tableData.value = []
        formInline.pageNum = 1
    }
    if (timer.value) {
        window.clearInterval(timer.value)
    }

    // setTimeout(async () => {
    //查询历史指标
    if (dataSet.value.includes('_history')) {
        formInline.startTime = datePickerRef.value && datePickerRef.value.timeValue[0]
        formInline.endTime = datePickerRef.value && datePickerRef.value.timeValue[1]
        formInline.id = dataSet.value.replace('_history', '')
        await deviceHisData(formInline).then((res: any) => {
            tableData.value = res.data.records
            formInline.total = res.data.total
            tableLoading.value = false
        })
    }
    //查询趋势数据
    if (dataSet.value.includes('_trenddata')) {
        let obj = {
            devId: deviceId.value, //e.id
            lineId: lineId.value, //e.pid
            type: 1,
            list: [
                {
                    lineId: lineId.value,
                    devId: dataSet.value.replace('_trenddata', '')
                }
            ]
        }
        trendRef.value && trendRef.value.getTrendRequest(obj)
    }
    //查询实时数据
    if (dataSet.value.includes('_realtimedata')) {
        //查询实时数据显示实时录波、实时趋势、谐波频谱
        realTimeFlag.value = true
        let obj = {
            type: 2,
            devId: deviceId.value, //e.id
            lineId: lineId.value //e.pid
        }
        intRealTime(obj)
    }
    if (!dataSet.value.includes('_realtimedata')) {
        // if(timer.value){
        //      window.clearInterval(timer.value)
        // }
    }
    //查询暂态事件
    if (dataSet.value.includes('_event')) {
        let obj = {
            devId: deviceId.value, //e.id
            lineId: lineId.value, //e.pid
            type: 3,
            list: [
                {
                    lineId: lineId.value,
                    devId: dataSet.value.replace('_event', '')
                }
            ]
        }
        //暂态事件表格请求参数
        eventRef.value && eventRef.value.getTableParams(obj)
    }
    //查询当前指标
    if (!dataSet.value.includes('_')) {
        formInline.id = dataSet.value
        await deviceRtData(formInline).then((res: any) => {
            tableData.value = res.data.records
            formInline.total = res.data.total
            tableLoading.value = false
        })
    }

    // }, 100)
}
//模版下载
const handleDownLoadTemplate = () => {}
//解析列表
// const isAnalysisList = ref(false)
const analysisListRef = ref()
//打开解析列表
const handleAnalysisList = () => {
    // isAnalysisList.value = true
    analysisListRef.value && analysisListRef.value.open()
}
//返回
// const handleBackAnalysisList=()=>{
//     isAnalysisList.value = false
// }
//离线数据导入
const offLineDataImportRef = ref()
const handleImport = () => {
    //设备devId&监测点lineId带入组件
    offLineDataImportRef.value && offLineDataImportRef.value.open(deviceId.value, lineId.value)
}
queryByCode('Device_Type').then(res => {
    queryCsDictTree(res.data.id).then(res => {
        devTypeOptions.value = res.data.map((item: any) => {
            return {
                value: item.id,
                label: item.name,
                ...item
            }
        })
    })
    queryByid(res.data.id).then(res => {
        devModelOptions.value = res.data.map((item: any) => {
            return {
                value: item.id,
                label: item.name,
                ...item
            }
        })
    })
})
const echoName = (value: any, arr: any[]) => {
    return value ? arr.find(item => item.value == value).label : '/'
}
const openGroup = () => {
    if (!dataSet.value) {
        return ElMessage.warning('暂无数据')
    }
    getGroupLoading.value = true
    getGroup(dataSet.value).then((res: any) => {
        const call = (data: any[]) => {
            data.forEach(item => {
                item.label = item.name
                item.isShow = item.isShow == 1
                if (item.children && item.children.length > 0) {
                    call(item.children)
                }
            })
        }
        call(res.data)
        getGroupLoading.value = false
        mangePopup.value.open({
            deviceData: deviceData.value,
            dataSetName: deviceData.value.dataSetList.filter((item: any) => item.id == dataSet.value)[0]?.name,
            dataSet: dataSet.value,
            tree: res.data
        })
    })
}
watch(
    () => dataSet.value,
    (val: any, oldVal: any) => {
        if (val) {
            // handleClick()
        }
    }
)
watch(
    () => tableData.value,
    (val: any, oldVal: any) => {
    }
)
onMounted(() => {})
</script>

<style lang="scss">
.device-control {
    display: flex;

    &-right {
        overflow: hidden;
        flex: 1;
        padding: 10px 10px 10px 0;
        .el-descriptions__header {
            height: 36px;
            margin-bottom: 7px;
            display: flex;
            align-items: center;
        }
        .content {
            box-sizing: border-box;
            overflow: auto;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            grid-template-rows: max-content;
            grid-gap: 10px;
            justify-content: center;

            .box-card {
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                color: var(--el-color-white);
                min-height: 150px;
                font-size: 13px;

                .el-card__header {
                    padding: 0;
                    .clearfix {
                        box-sizing: border-box;
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        height: 35px;
                        padding: 0 10px;
                        background: var(--el-color-primary);
                    }
                }

                .el-card__body {
                    flex: 1;
                    padding: 10px;
                    margin-bottom: 0;
                    background-image: linear-gradient(var(--el-color-primary), var(--el-color-primary-light-3));
                    .box-card-content {
                        height: 100%;
                        display: flex;
                        flex-direction: column;
                        justify-content: space-between;
                    }
                }
            }
        }
    }
}

.view_top_btn {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}
</style>
