<template>
    <div>
        <el-card class="!border-none" shadow="never">
            <el-page-header content="设备详情" @back="$router.back()" />
        </el-card>
        <el-card class="!border-none mt-4 flex-1" shadow="never">
            <template #header>
                <div>
                    <span class="card-title">设备资料</span>
                </div>
            </template>
            <div class="flex flex-wrap">
                <div v-if="deviceData.device.land_id != ''" class="w-1/2 mb-4 md:w-1/3">
                    <div class="leading-10">所属土地：</div>
                    <div class="text-3xl text-tx-gray">ID：{{ deviceData.device.land_id }} / 名称：{{
                        deviceData.device.land_title }}</div>
                </div>
                <div v-if="deviceData.device.product_id != ''" class="w-1/2 mb-4 md:w-1/3">
                    <div class="leading-10">所属产品：</div>
                    <div class="text-3xl text-tx-gray">ID：{{ deviceData.device.product_id }} / 名称：{{
                        deviceData.device.product_name }}</div>
                </div>
            </div>
            <div class="flex flex-wrap">
                <div class="w-1/2 mb-4 md:w-1/6">
                    <div class="leading-10">设备名称：</div>
                    <div class="text-3xl text-tx-gray">{{ deviceData.device.name }}</div>
                </div>
                <div class="w-1/2 mb-4 md:w-1/6">
                    <div class="leading-10">设备编码：</div>
                    <div class="text-3xl text-tx-gray">{{ deviceData.device.code }}</div>
                </div>
                <div class="w-1/2 mb-4 md:w-1/6">
                    <div class="leading-10">设备类型：</div>
                    <div class="text-3xl text-tx-gray">
                        <dict-value :options="dictData.device_type" :value="deviceData.device.type" />
                    </div>
                </div>
                <div class="w-1/2 mb-4 md:w-1/6">
                    <div class="leading-10">设备状态：</div>
                    <div class="text-3xl text-tx-gray">
                        <dict-value :options="dictData.device_status" :value="deviceData.device.status" />
                    </div>
                </div>
                <div class="w-1/2 mb-4 md:w-1/6">
                    <div class="leading-10">是否在线：</div>
                    <div class="text-3xl text-tx-gray">
                        <dict-value :options="dictData.device_online_status" :value="deviceData.device.is_online" />
                    </div>
                </div>
            </div>
        </el-card>

        <el-card class="!border-none mt-4 flex-1" shadow="never">
            <el-tabs v-model="activeName" class="">
                <!-- <el-tab-pane v-if="deviceData.device.type==3" label="监控视频" name="monitor_video"> -->
                <el-tab-pane label="监控视频" name="monitor_video" style="width:100vw;padding-left: 15vw;">
                    <Jessibuca v-if="deviceData.device.video_url != '' && showVideo " :video_url="deviceData.device.video_url"></Jessibuca>
                    <!-- <Jessibuca
                        :video_url="'http://rtsp.lihaink.cn/live/lihai_lot_walnutpi_dev_6.live.flv?secret=ywdtp2llj80ha19jhmxl4po99nsmaynt'">
                    </Jessibuca> -->

                </el-tab-pane>

                <el-tab-pane label="监控数据" name="monitor_item">
                    <el-row :gutter="12">
                        <el-col :span="6" v-for="item in deviceData.monitor_item" :key="item">
                            <el-card shadow="always" class="mb-4">
                                <div class="flex justify-between mb-2">
                                    <div class="mt-2 text-sm text-tx-secondary">{{ item.name }}</div>
                                    <div class="mt-2 text-sm text-tx-secondary" style="cursor: pointer;"
                                        @click="handleClick(item.device_id, item.value)">
                                        历史数据
                                    </div>
                                </div>

                                <div class="my-6 text-3xl">{{ item.monitor_value }}</div>
                                <div class="mt-2 text-sm text-tx-secondary"><el-tag class="mr-2" type="info">只读</el-tag>{{
                                    item.last_time }}</div>
                            </el-card>
                        </el-col>
                    </el-row>
                </el-tab-pane>

            </el-tabs>
        </el-card>
    </div>

    <el-dialog v-model="dialogTableVisible" title="历史数据">
        <el-table :data="monitorData.gridData">
            <el-table-column property="id" label="ID" width="80" />
            <el-table-column property="date" label="时间" width="250" />
            <el-table-column property="value" label="数据" />
        </el-table>
        <el-pagination small background layout="prev, pager, next" :page-size="queryMonitorData.page_size"
            :total="queryMonitorData.total" class="mt-4" @current-change="handleCurrentChange" />
    </el-dialog>
</template>

<script lang="ts" setup name="deviceDetail">
import { ref } from 'vue'
import Jessibuca from '@/components/jessibuca/Jessibuca.vue'
import { useDictData } from '@/hooks/useDictOptions'
import { apiDeviceDetail, apiDeviceMonitorData } from '@/api/device'
import { timeFormat } from '@/utils/util'
import {useRoute} from "vue-router"


const activeName = ref('monitor_video')
const deviceData: any = reactive({
    device: {},
    monitor_item: []
})

const queryMonitorData: any = reactive({
    device_id: '',
    monitor_type: '',
    page_no: 1,
    page_size: 15,
    total: ''
})

const { dictData } = useDictData('device_type,device_status,device_online_status,device_bind_status,monitor_item')

const route = useRoute()
const getDetails = async () => {
    apiDeviceDetail({
        id: route.query.device_id
    })
        .then((res: any) => {
            scoketData.username = res.account
            scoketData.device = res.id
            // pullStream(scoketData)
            deviceData.device.name = res.name
            deviceData.device.code = res.code
            deviceData.device.type = res.type
            deviceData.device.status = res.status
            deviceData.device.is_online = res.is_online
            deviceData.device.is_bind = res.is_bind
            deviceData.device.land_id = res.land_id == null ? '' : res.land_id
            deviceData.device.land_title = res.land_title == null ? '' : res.land_title
            deviceData.device.product_id = res.product_id == null ? '' : res.product_id
            deviceData.device.product_name = res.product_name == null ? '' : res.product_name
            deviceData.monitor_item = res.monitor_item
            deviceData.device.video_url = res.video_url
        })
        .catch((err: any) => {
            console.log('err', err)
        })
}
getDetails()

const dialogTableVisible = ref(false)
const monitorData = reactive({
    gridData: [{}]
})

const handleClick = (id: any, type: any) => {
    monitorData.gridData = [{}]
    queryMonitorData.device_id = id
    queryMonitorData.monitor_type = type
    apiDeviceMonitorData({
        id: id,
        monitor_type: type,
        page_no: queryMonitorData.page_no,
        page_size: queryMonitorData.page_size
    })
        .then((res: any) => {
            dialogTableVisible.value = true
            queryMonitorData.total = res.count
            res.lists.map((data: any) => {
                queryMonitorData.total = res.count
                monitorData.gridData.push({
                    id: data.id,
                    date: data.create_time
                        ? timeFormat(data.create_time, 'yyyy-mm-dd hh:MM:ss')
                        : '',
                    value: data.monitor_value
                })
            })
        })
        .catch((err: any) => {
            console.log('err', err)
        })
}

const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    monitorData.gridData = [{}]
    apiDeviceMonitorData({
        id: queryMonitorData.device_id,
        monitor_type: queryMonitorData.monitor_type,
        page_no: val,
        page_size: queryMonitorData.page_size
    })
        .then((res: any) => {
            dialogTableVisible.value = true
            queryMonitorData.total = res.count
            res.lists.map((data: any) => {
                monitorData.gridData.push({
                    id: data.id,
                    date: data.create_time
                        ? timeFormat(data.create_time, 'yyyy-mm-dd hh:MM:ss')
                        : '',
                    value: data.monitor_value
                })
            })
        })
        .catch((err: any) => {
            console.log('err', err)
        })
}

// scoket拉流地址
const scoketData = reactive({
    username: '',
    device: '',
    scence: 2,

})
const showVideo=ref(false)
const socket = new WebSocket('wss://iot.lihaink.cn/test');
const pullStream = (data: object) => {
    const onSocketOpen = (event: any) => {
        console.log("scoket打开")
        socket.send(JSON.stringify(data));
        showVideo.value=true
    }
    const onSocketClose = (event: any) => {
        console.log('WebSocket连接已关闭');
    }
    const onSocketError = (event: any) => {
        console.error('WebSocket连接发生错误');
    }
    socket.addEventListener('open', onSocketOpen);
    socket.addEventListener('close', onSocketClose);
    socket.addEventListener('error', onSocketError);
}
pullStream( {
    username:route.query.userName,
    device: 'lihai_lot_walnutpi_dev_' + route.query.device_id,
    scence:'web'
})
onBeforeUnmount(() => {
    socket.close()
})
</script>