<template>
    <hc-drawer v-model="isShow" to-id="hc-main-box">
        <div class="hc-tentative-acquisition-humidity-equipment-info">
            <div class="data-statistics">
                <hc-body>
                    <div class="equipment-list-data-item temperature hc-flex">
                        <div class="icon-box">
                            <hc-icon name="temp-hot" />
                        </div>
                        <div class="content">
                            <div class="name">温度</div>
                            <div class="num">{{ deviceDataInfo.temperature }}</div>
                            <div class="time">记录时间：{{ deviceDataInfo.time }}</div>
                        </div>
                    </div>
                    <div class="equipment-list-data-item humidity hc-flex">
                        <div class="icon-box">
                            <hc-icon name="water-percent" />
                        </div>
                        <div class="content">
                            <div class="name">湿度</div>
                            <div class="num">{{ deviceDataInfo.humidity }}</div>
                            <div class="time">记录时间：{{ deviceDataInfo.time }}</div>
                        </div>
                    </div>
                    <div class="equipment-list-data-echart">
                        <hc-charts :option="setChartsOption" />
                    </div>
                </hc-body>
            </div>
            <div class="data-table">
                <hc-card>
                    <template #header>
                        <div class="mr-14px w-410px">
                            <el-date-picker
                                v-model="dateTimeArr" type="datetimerange" :shortcuts="shortcuts" class="w-full!"
                                value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
                                range-separator="至" start-placeholder="开始日期时间" end-placeholder="结束日期时间"
                            />
                        </div>
                        <el-button type="primary" @click="searchClick">搜索</el-button>
                    </template>
                    <template #extra>
                        <el-button @click="toBackClick">
                            <hc-icon name="arrow-go-back" />
                            <span>返回</span>
                        </el-button>
                    </template>
                    <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading" :is-index="false" :is-current-row="false" />
                    <template #action>
                        <hc-pages :pages="searchForm" @change="pageChange" />
                    </template>
                </hc-card>
            </div>
        </div>
    </hc-drawer>
</template>

<script setup>
import { ref, watch } from 'vue'
import { getArrValue, getObjValue, isNullES } from 'js-fast-way'
import { useClick } from 'hc-vue3-ui'
import dayjs from 'dayjs'
import mainApi from '~api/tentative/acquisition/humidity'

const props = defineProps({
    data: {
        type: Object,
        default: () => ({}),
    },
})

//双向绑定
const isShow = defineModel('modelValue', {
    default: false,
})

//监听可否编辑
const dataInfo = ref(props.data)
watch(() => props.data, (data) => {
    dataInfo.value = getObjValue(data)
}, { immediate: true, deep: true })

//监听显示
watch(isShow, (val) => {
    if (val) getInfoData()
})

//获取数据详情
const getInfoData = async () => {
    await getDeviceList()
    setChartsData()
}

//获取设备列表
const deviceDataInfo = ref({})
const getDeviceList = async () => {
    const { token, deviceAddr } = getObjValue(dataInfo.value)
    if (isNullES(token) || isNullES(deviceAddr)) {
        deviceDataInfo.value = {}
        return
    }
    let temperature = '0℃', humidity = '0%'
    const { data } = await mainApi.getRealTimeDataByDeviceAddr(token, deviceAddr)
    //数据是否存在
    const arr = getArrValue(data)
    if (arr.length <= 0) {
        setDeviceData({ temperature, humidity })
        return
    }
    //子级数据是否存在
    const dataItem = getArrValue(arr[0].dataItem)
    if (dataItem.length <= 0) {
        setDeviceData({ temperature, humidity })
        return
    }
    //最子级数据判断
    const registerItem = getArrValue(dataItem[0].registerItem)
    if (registerItem.length <= 0) {
        setDeviceData({ temperature, humidity })
        return
    }
    //最子级数据
    for (let i = 0; i < registerItem.length; i++) {
        if (registerItem[i].registerName === '温度') {
            temperature = registerItem[i].data + registerItem[i].unit
        }
        if (registerItem[i].registerName === '湿度') {
            humidity = registerItem[i].data + registerItem[i].unit
        }
    }
    //设置数据
    setDeviceData({ temperature, humidity })
}

//设置空数据
const setDeviceData = ({ temperature, humidity }) => {
    const currentDateTime = new dayjs().format('YYYY年MM月DD日 HH:mm:ss')
    deviceDataInfo.value = {
        temperature: temperature,
        humidity: humidity,
        time: currentDateTime,
    }
}

//搜索表单
const searchForm = ref({ nodeId: -1, startTime: '', endTime: '', deviceAddr: null, current: 1, size: 20, total: 0 })
const searchClick = () => {
    console.log(searchForm.value)
    console.log(dateTimeArr.value)
}

//分页被点击
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//历史记录表格
const tableColumn = [
    { key: 'name', name: '设备地址' },
    { key: 'text', name: '温度' },
    { key: 'color', name: '湿度' },
    { key: 'time', name: '记录时间' },
]
const tableData = ref([])

//获取历史记录数据
const tableLoading = ref(false)
const getTableData = async () => {

}

//日期时间选择
const dateTimeArr = ref('')
const shortcuts = [
    {
        text: '最近1小时',
        value: () => {
            const end = new Date()
            const start = new Date(end - 3600 * 1000) // 1小时前
            return [start, end]
        },
    },
    {
        text: '今天',
        value: () => {
            const end = new Date()
            const start = new Date(end.setHours(0, 0, 0, 0))
            return [start, new Date()]
        },
    },
    {
        text: '昨天',
        value: () => {
            const end = new Date()
            end.setDate(end.getDate() - 1)
            const start = new Date(end.setHours(0, 0, 0, 0))
            return [start, new Date(start.getTime() + 24 * 3600 * 1000 - 1)]
        },
    },
    {
        text: '最近7天',
        value: () => {
            const end = new Date()
            const start = new Date(end - 7 * 24 * 3600 * 1000)
            return [start, end]
        },
    },
    {
        text: '最近30天',
        value: () => {
            const end = new Date()
            const start = new Date(end - 30 * 24 * 3600 * 1000)
            return [start, end]
        },
    },
    {
        text: '本月',
        value: () => {
            const end = new Date()
            const start = new Date(end.getFullYear(), end.getMonth(), 1)
            return [start, end]
        },
    },
    {
        text: '上个月',
        value: () => {
            const end = new Date()
            const start = new Date(end.getFullYear(), end.getMonth() - 1, 1)
            const lastDayOfLastMonth = new Date(end.getFullYear(), end.getMonth(), 0)
            return [start, lastDayOfLastMonth]
        },
    },
]



//图表数据
const setChartsOption = ref({})
const setChartsData = () => {
    const data = [
        { time: '00:00:00', temperature: 27, humidity: 50 },
        { time: '00:30:00', temperature: 28.5, humidity: 41 },
        { time: '01:00:00', temperature: 32, humidity: 60 },
        { time: '01:30:00', temperature: 27, humidity: 48 },
        { time: '02:00:00', temperature: 28, humidity: 40 },
        { time: '02:30:00', temperature: 29.5, humidity: 55 },
        { time: '03:00:00', temperature: 30.5, humidity: 48 },
        { time: '03:30:00', temperature: 30, humidity: 61 },
        { time: '04:00:00', temperature: 27.2, humidity: 54 },
    ]
    setChartsOption.value = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
            },
            formatter: function (params) {
                let result = params[0].axisValue + '<br/>'
                params.forEach(function (item) {
                    let unit = item.seriesName === '温度' ? '°C' : '%'
                    result += item.marker + '  ' + item.seriesName + ': ' + item.value + unit + '<br/>'
                })
                return result
            },
        },
        legend: {
            data: ['温度', '湿度'],
        },
        xAxis: {
            type: 'category',
            data: data.map(item => item.time),
            axisLine: {
                onZero: false,
            },
        },
        yAxis: [
            {
                type: 'value',
                name: '温度(°C)',
                min: 23,
                max: 33,
                interval: 2,
                position: 'left',
                axisLabel: {
                    formatter: '{value}°C',
                },
            },
            {
                type: 'value',
                name: '湿度(%)',
                min: 20,
                max: 70,
                interval: 10,
                position: 'right',
                axisLabel: {
                    formatter: '{value}%',
                },
            },
        ],
        series: [
            {
                name: '温度',
                type: 'line',
                yAxisIndex: 0,
                data: data.map(item => item.temperature),
                smooth: true,
                lineStyle: {
                    color: '#1D4590',
                },
                itemStyle: {
                    color: '#1D4590',
                },
            },
            {
                name: '湿度',
                type: 'line',
                yAxisIndex: 1,
                data: data.map(item => item.humidity),
                smooth: true,
                lineStyle: {
                    color: '#91CC75',
                },
                itemStyle: {
                    color: '#91CC75',
                },
            },
        ],
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
        },
    }
}

//返回
const toBackClick = () => {
    isShow.value = false
    tableData.value = []
    dateTimeArr.value = ''
    setChartsOption.value = {}
}
</script>

<style lang="scss">
@import "~src/styles/tentative/acquisition/equipment";
</style>
