<!-- 农场详情 -->
<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'
    import * as farmbaseApi from '@/api/model/farmbase'

    // 页面参数
    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: '',
                },
            ],
        },
        // 预报日期
        forecasts: ['29日', '30日', '1日', '2日', '3日'],
        clicked: 0,
        farmbaseInfo: {},
        farmbaseInfoList: [],
        deviceTypeCount: [],
    })

    async function getFarmbaseInfoList() {
        farmbaseApi
            .list({
                farmId: model.id,
            })
            .then((res) => {
                const { records } = res
                model.farmbaseInfoList = records

                if (records.length > 0) {
                    getFarmbaseInfoById(records[0].id)
                }
            })
    }

    async function getFarmbaseInfoById(id) {
        farmbaseApi.getFarmbaseInfoById({ id }).then((res) => {
            model.farmbaseInfo = res
            getDeviceTypeCount()
        })
    }

    async function getDeviceTypeCount() {
        farmbaseApi.getDeviceTypeCount({ farmId: model.id, farmBaseId: model.farmbaseInfo?.id }).then((res) => {
            model.deviceTypeCount = res
        })
    }

    // 地图组件
    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,
                },
            })

            // 查询农场信息
            getFarmbaseInfoList()
        },
        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?farmId=${model.id}`)
        }
    })
</script>

<template>
    <view class="page bg-white">
        <!-- 地图组件 -->
        <!-- <view class="h-730 overflow-hidden map-box"> -->
        <view class="h-810 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 class="card !top-810">
            <view class="w-full absolute top--70rpx">
                <view class="box-1">
                    <view class="relative w-full flex flex-row">
                        <view class="box-1-left"
                            ><image class="image_1" src="/static/images/nongchang/play.png"
                        /></view>
                        <view class="box-1-right">
                            <view class="box-1-right-top">
                                <view class="text_1">预报</view>
                            </view>
                            <view class="box-1-right-bottom"
                                ><text
                                    v-for="(forecast, index) in model.forecasts"
                                    :class="model.clicked === index ? 'active' : ''"
                                    :key="index"
                                    >{{ forecast }}</text
                                ></view
                            >
                        </view>
                    </view>
                </view>
                <view class="box-2">
                    <view class="box-2-left">
                        <view class="box-2-left-top">
                            <text class="box-2-left-top-text1">12°</text>
                            <text class="box-2-left-top-text2">多云</text>
                        </view>
                        <view class="box-2-left-bottom">
                            <text class="box-2-left-bottom-text1">北风2级 | 湿度62%</text>
                        </view>
                    </view>
                    <view class="box-2-right">
                        <view class="box-2-right-item">
                            <text class="box-2-right-text1">15°-19°</text>
                            <text class="box-2-right-text2">今天 阴</text>
                        </view>
                        <view class="box-2-right-interval" />
                        <view class="box-2-right-item">
                            <text class="box-2-right-text1">17°-21°</text>
                            <text class="box-2-right-text2">明天 多云</text>
                        </view>
                    </view>
                </view>
                <view class="box-3">
                    <view class="box-3-tags">
                        <view
                            class="box-3-tags-item"
                            :class="model.farmbaseInfo.id === farmbase.id ? 'box-3-tags-item-active' : ''"
                            v-for="farmbase in model.farmbaseInfoList"
                            :key="farmbase.id"
                        >
                            <view @click="getFarmbaseInfoById(farmbase.id)">
                                <text>{{ farmbase.baseName }}</text>
                            </view>
                        </view>
                    </view>
                    <view class="box-3-info">
                        <view class="box-3-info-item">
                            <view class="box-3-info-item-text-box">
                                <text class="box-3-info-item-text1">总面积: </text>
                                <text class="box-3-info-item-text2">{{ model.farmbaseInfo.scale }} 亩</text>
                            </view>
                        </view>
                        <view class="box-3-info-item justify-between">
                            <view class="box-3-info-item-text-box">
                                <text class="box-3-info-item-text1">种植: </text>
                                <text class="box-3-info-item-text2">{{ model.farmbaseInfo.plantedCrops }}</text>
                            </view>
                            <view class="box-3-info-item-text-box">
                                <text class="box-3-info-item-text1">预计产量: </text>
                                <text class="box-3-info-item-text2" />
                            </view>
                        </view>
                        <view class="box-3-info-item justify-between">
                            <view class="box-3-info-item-text-box">
                                <text class="box-3-info-item-text1">负责人: </text>
                                <text class="box-3-info-item-text2">{{ model.farmbaseInfo.managerName }}</text>
                            </view>
                            <view class="box-3-info-item-text-box">
                                <text class="box-3-info-item-text1">联系电话: </text>
                                <text class="box-3-info-item-text2">{{ model.farmbaseInfo.contactPhone }}</text>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="box-4">
                    <view class="box-4-title">
                        <view class="box-4-title-text1"><text>基地设备</text></view>
                        <view class="box-4-title-text2"><text>＋ 添加设备</text></view>
                    </view>
                    <view class="box-4-device">
                        <view class="box-4-device-item" v-for="(device, index) in model.deviceTypeCount" :key="index">
                            <view class="box-4-item-icon">
                                <image class="box-4-item-icon-image" src="/static/images/nongchang/jiankong.png" />
                            </view>
                            <view class="box-4-item-content">
                                <text class="box-4-item-text1">{{ device.deviceName }}</text>
                                <text class="box-4-item-text2">{{ device.deviceCount }}台</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<style lang="scss" scoped>
    //
    page {
        background-color: #e6f5e8;
    }
    .page {
        position: relative;
        background-color: #e6f5e8;

        .map-box {
            // #ifdef APP-PLUS
            position: relative;
            top: 0;
            // #endif
            // #ifdef H5
            position: relative;
            top: 0;
            // #endif
        }

        .card {
            width: 100%;
            background-color: #e6f5e8;
            position: absolute;
            font-weight: 400;
            font-family: '思源黑体';

            .box-1 {
                width: 95%;
                height: 80rpx;
                background-color: #fff;
                margin: 20rpx;
                border-radius: 18rpx;
                display: flex;
                flex-direction: row;

                .box-1-left {
                    width: 50rpx;
                    height: 100%;
                    margin-left: 20rpx;
                    display: flex;
                    align-items: center;

                    .image_1 {
                        width: 50rpx;
                        height: 50rpx;
                    }
                }

                .box-1-right {
                    width: calc(100% - 80rpx);
                    height: 100%;
                    margin-left: 20rpx;
                    display: flex;
                    flex-direction: column;

                    .box-1-right-top {
                        // height: 50%;
                        background-image: url('/static/images/nongchang/yubaobeijing.png');
                        background-size: 100% 100%;
                        background-repeat: no-repeat;

                        .text_1 {
                            font-size: 25rpx;
                            color: #5db66f;
                            text-align: center;
                        }
                    }

                    .box-1-right-bottom {
                        // height: 50%;
                        display: flex;
                        flex-direction: row;
                        justify-content: space-around;
                        color: #999999;
                        font-size: 24rpx;

                        .active {
                            color: #cccccc;
                        }
                    }
                }
            }

            .box-2 {
                width: 95%;
                height: 150rpx;
                margin: 20rpx;
                display: flex;
                flex-direction: row;

                .box-2-left {
                    width: 35%;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-around;
                    padding: 10rpx;
                    margin-right: 20rpx;
                    background-color: #fff;
                    border-radius: 18rpx;
                    line-height: 100%;

                    .box-2-left-top {
                        display: flex;
                        flex-direction: row;
                        justify-content: space-around;
                        .box-2-left-top-text1 {
                            font-size: 50rpx;
                            font-weight: bold;
                            color: #333333;
                        }

                        .box-2-left-top-text2 {
                            font-size: 32rpx;
                            color: #555555;
                        }
                    }

                    .box-2-left-bottom {
                        display: flex;
                        flex-direction: row;
                        justify-content: space-around;
                        line-height: 100%;
                        .box-2-left-bottom-text1 {
                            font-size: 24rpx;
                            color: #555555;
                        }
                    }
                }

                .box-2-right {
                    width: 62%;
                    display: flex;
                    flex-direction: row;
                    justify-content: space-around;
                    margin-right: 20rpx;
                    background-color: #fff;
                    border-radius: 18rpx;
                    line-height: 100%;

                    .box-2-right-item {
                        width: 50%;
                        display: flex;
                        flex-direction: column;
                        justify-content: space-around;
                        text-align: center;
                        .box-2-right-text1 {
                            font-size: 42rpx;
                            font-weight: bold;
                            color: #333333;
                        }

                        .box-2-right-text2 {
                            font-size: 24rpx;
                            color: #555555;
                        }
                    }

                    .box-2-right-interval {
                        width: 1px;
                        height: 80%;
                        margin: auto;
                        background-color: #eeeeee;
                    }
                }
            }

            .box-3 {
                width: 95%;
                height: 280rpx;
                margin: 20rpx;
                padding: 0 20rpx;
                background-color: #fff;
                border-radius: 18rpx;
                display: flex;
                flex-direction: column;
                justify-content: space-around;

                .box-3-tags {
                    width: 100%;
                    height: 70rpx;
                    display: flex;
                    flex-direction: row;
                    font-size: 28rpx;

                    .box-3-tags-item {
                        width: 31%;
                        height: 100%;
                        margin-right: 20rpx;
                        text-align: center;
                        line-height: 70rpx;
                        border-radius: 48rpx;
                        background-color: rgba($color: #5db66f, $alpha: 0.1);
                        color: #5db66f;
                        font-weight: 300;
                    }

                    .box-3-tags-item-active {
                        background-color: #5db66f !important;
                        color: #fff !important;
                    }
                }

                .box-3-info {
                    width: 100%;
                    height: calc(100% - 120rpx);
                    display: flex;
                    flex-direction: column;
                    justify-content: space-around;

                    .box-3-info-item {
                        display: flex;
                        flex-direction: row;

                        .box-3-info-item-text-box {
                            width: 50%;

                            .box-3-info-item-text1 {
                                font-size: 26rpx;
                                color: #999999;
                                margin-right: 10rpx;
                            }

                            .box-3-info-item-text2 {
                                font-size: 30rpx;
                                color: #333333;
                            }
                        }
                    }
                }
            }

            .box-4 {
                width: 95%;
                margin: 30rpx 20rpx 0 20rpx;
                border-radius: 18rpx;

                .box-4-title {
                    width: 100%;
                    height: 50rpx;
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;

                    .box-4-title-text1 {
                        font-size: 30rpx;
                        color: #333333;
                        font-weight: bold;
                    }

                    .box-4-title-text2 {
                        font-size: 28rpx;
                        color: #5db66f;
                    }
                }

                .box-4-device {
                    width: 100%;
                    height: calc(100% - 50rpx);
                    margin-top: 10rpx;
                    display: flex;
                    flex-wrap: wrap;
                    justify-content: space-between;

                    .box-4-device-item {
                        width: 49%;
                        height: 48%;
                        display: flex;
                        flex-direction: row;
                        border-radius: 24rpx;
                        background-color: #fff;
                        margin-bottom: 10rpx;

                        .box-4-item-icon {
                            width: 80rpx;
                            height: 100%;
                            margin: 0 25rpx;
                            display: flex;
                            align-items: center;

                            .box-4-item-icon-image {
                                width: 100%;
                                height: 80rpx;
                            }
                        }

                        .box-4-item-content {
                            width: 100%;
                            height: 100%;
                            display: flex;
                            justify-content: center;
                            flex-direction: column;

                            .box-4-item-text1 {
                                font-size: 30rpx;
                                color: #333333;
                            }

                            .box-4-item-text2 {
                                font-size: 26rpx;
                                color: #5db66f;
                            }
                        }
                    }
                }
            }
        }
    }
</style>
