<!-- 农场详情 -->
<script setup lang="ts">
    import * as turf from '@turf/turf'
    import type { Page } from './config'
    import PlayWidget from './components/PlayWidget.vue'
    import Navigate from '@/utils/page/navigate'
    import {
        addDefaultGeoJSONSource,
        addDefaultSplotLayer,
        addDefaultSymbolLayer,
        useMapbox,
    } from '@/components/Map/Mapbox/hook'
    import type { ToolBoxButtonHandleEvent } from '@/components/Map/Widgets/ToolBox'
    import { ToolBoxWidget, useToolBoxWidget } from '@/components/Map/Widgets/ToolBox'
    import * as NongchangAPI from '@/api/model/nongchang'

    // 页面参数
    const page = reactive<Page>({
        id: 'example-mapbox',
        init: false,
        requests: 0,
        latest: null,
        query: {},
    })

    const model = reactive({
        id: '',
        name: '',
        lonlat: '',
        address: '',
        description: '',
        // 地块、位置信息 GeoJSON
        plots: [],
        // 设备信息
        devices: [],

        // 天气信息
        weather: {
            live: {
                tem: '12°',
                phenomena: '',
                wind: '',
                humidity: '',
            },
            forecast: [
                {
                    phenomena: '',
                    date: '',
                    maxTem: '',
                    minTem: '',
                },
            ],
        },
    })

    // 地图组件
    const [registerMap, map] = useMapbox({
        style: { zoom: 15 },
        onLoaded: async (data) => {
            console.log('✨✨✨ Map Loaded', data)

            // 查询农场数据
            const res = await NongchangAPI.farmsList()
            console.log('农场列表', res.records)

            // 获取第一个农场信息
            const item = res.records?.[0]
            model.id = item.id
            model.name = item.farmName
            model.description = item.description
            if (item.longitude && item.latitude) {
                model.lonlat = `${item.longitude},${item.latitude}`
            } else {
                // 模拟位置数据
                model.lonlat = '111.024108, 29.554847'
                Message.toast('未设置农场坐标位置，已使用模拟位置数据')
            }

            // 设置页面标题
            uni.setNavigationBarTitle({
                title: item.farmName,
            })
            // 设置地图中心点
            map.flyTo({
                center: model.lonlat.split(',').map(Number) as [number, number],
                duration: 0,
            })

            // 渲染地块数据
            model.plots = [
                turf.polygon(
                    [
                        [
                            [111.0235, 29.5562],
                            [111.0255, 29.5562],
                            [111.0255, 29.5558],
                            [111.0235, 29.5558],
                            [111.0235, 29.5562],
                        ],
                    ],
                    {
                        color: 'yellow',
                        name: '基地 A',
                        popup: `{{name}}`,
                    },
                ),
                turf.polygon(
                    [
                        [
                            [111.0225, 29.5565],
                            [111.0238, 29.5568],
                            [111.023, 29.5555],
                            [111.022, 29.5558],
                            [111.0225, 29.5565],
                        ],
                    ],
                    {
                        color: 'red',
                        name: '基地 B',
                        popup: `{{name}}`,
                    },
                ),
                turf.polygon(
                    [
                        [
                            [111.0258, 29.555],
                            [111.0262, 29.5542],
                            [111.0252, 29.554],
                            [111.0258, 29.555],
                        ],
                    ],
                    {
                        color: 'blue',
                        name: '基地 C',
                        popup: `{{name}}`,
                    },
                ),
            ]
            addDefaultGeoJSONSource(map, `${page.id}-plot`, model.plots)
            addDefaultSplotLayer(map, `${page.id}-plot`, {
                paint: {
                    'fill-opacity': 0.2,
                    'fill-outline-color': ['get', 'color'],
                },
            })
            map.addLayer({
                type: 'line',
                id: `${page.id}-plot-line`,
                source: `${page.id}-plot`,
                layout: {
                    'line-join': 'round',
                    'line-cap': 'round',
                },
                paint: {
                    'line-color': ['get', 'color'],
                    'line-width': 2,
                },
            })

            // 渲染设备数据
            model.devices = [
                turf.point([111.024108, 29.554847], {
                    name: '设备1',
                    description: '设备1描述',
                    icon: 'GD',
                    popup: `{{name}}`,
                }),
                turf.point([111.023139, 29.55539], {
                    name: '设备2',
                    description: '设备2描述',
                    icon: 'JCD',
                    popup: `{{name}}`,
                }),
                turf.point([111.024989, 29.555435], {
                    name: '设备3',
                    description: '设备3描述',
                    icon: 'BZ',
                    popup: `{{name}}`,
                }),
            ]
            addDefaultGeoJSONSource(map, `${page.id}-symbol`, model.devices)
            addDefaultSymbolLayer(map, `${page.id}-symbol`, {
                layout: {
                    'text-field': '',
                    'icon-image': ['get', 'icon'],
                    'icon-size': 1,
                },
            })
        },
        onSourceRequestHandle: () => {
            page.requests--
            if (page.requests === 0) {
                Message.hideLoading()
            }
        },
        onSourceRequestErrorHandle: () => {
            Message.hideLoading()
        },
    })

    // 左侧工具栏小部件
    const [registerToolBoxWidget] = useToolBoxWidget({
        show: true,
        expand: true,
        showExpandButton: false,
        top: -90,
        tools: [
            {
                key: 'action',
                align: 'top',
                buttons: [
                    {
                        name: '设备',
                        color: '#75c849',
                        icon: '/static/images/codefun/device.active.png',
                        type: 'toggle',
                        handle: (e: ToolBoxButtonHandleEvent) => {
                            // 切换显示设备数据地图渲染
                            const active = e.button.icon === '/static/images/codefun/device.active.png'
                            if (active) {
                                e.button.color = '#666666'
                                e.button.icon = '/static/images/codefun/device.png'
                                map.setLayoutProperty(`${page.id}-symbol`, 'visibility', 'none')
                            } else {
                                e.button.color = '#75c849'
                                e.button.icon = '/static/images/codefun/device.active.png'
                                map.setLayoutProperty(`${page.id}-symbol`, 'visibility', 'visible')
                            }
                        },
                    },
                ],
            },
            {
                key: 'action',
                align: 'top',
                buttons: [
                    {
                        name: '降雨',
                        icon: '/static/images/codefun/rain.png',
                        type: 'button',
                        handle: () => {
                            Message.toast('暂无降雨数据')
                        },
                    },
                    {
                        name: '温度',
                        icon: '/static/images/codefun/temp.png',
                        type: 'button',
                        handle: () => {
                            Message.toast('暂无温度数据')
                        },
                    },
                    {
                        name: '强对流',
                        icon: '/static/images/codefun/severe.png',
                        type: 'button',
                        handle: () => {
                            Message.toast('暂无强对流数据')
                        },
                    },
                    {
                        name: '大风',
                        icon: '/static/images/codefun/wind.png',
                        type: 'button',
                        handle: () => {
                            Message.toast('暂无大风数据')
                        },
                    },
                    {
                        name: '其他',
                        icon: '/static/images/codefun/other.png',
                        type: 'button',
                        handle: () => {
                            Message.alert('敬请期待~', '温馨提醒')
                        },
                    },
                ],
            },
        ],
    })

    onNavigationBarButtonTap((e) => {
        if (e.index === 0) {
            Navigate.to('/pages/jidiguanli/add')
        }
    })
</script>

<template>
    <view class="page h-100vh bg-white">
        <!-- 地图组件 -->
        <!-- <view class="h-730 overflow-hidden map-box"> -->
        <view class="h-full overflow-hidden map-box">
            <!-- 地图组件 -->
            <Mapbox @register="registerMap" />
        </view>

        <!-- 地图上方所有小部件 -->
        <view class="widgets">
            <!-- 左侧工具栏小部件 -->
            <ToolBoxWidget @register="registerToolBoxWidget" />

            <!-- 播放数据小部件 -->
            <view class="play-wrap hidden">
                <PlayWidget />
            </view>

            <!-- 天气信息 -->
            <view class="weather-info">
                <view>
                    <view />
                </view>
            </view>
        </view>
    </view>
</template>

<style lang="scss" scoped>
    //
    .page {
        .map-box {
            // #ifdef APP-PLUS
            position: relative;
            top: 0;
            // #endif
            // #ifdef H5
            position: relative;
            top: 0;
            // #endif
        }
    }
</style>
