<!-- 农场详情 -->
<script setup lang="ts">
import * as turf from '@turf/turf'
import type { Page } from './config'
import Navigate from '@/utils/page/navigate'
import {
    addDefaultGeoJSONSource,
    addDefaultSplotLayer,
    addDefaultSymbolLayer,
    useMapbox,
    flyTo,
} from '@/components/Map/Mapbox/hook'
import { getText } from '@/utils/dict/area'
import * as LinghuoyonggongAPI from '@/api/model/linghuoyonggong'

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

const model = reactive({
    id: '',
    name: '',
    lonlat: `${uni.getStorageSync('location').lon},${uni.getStorageSync('location').lat}`,
    address: '',
    description: '',
    // 地块、位置信息 GeoJSON
    plots: [],
    // 设备信息
    devices: [],
    // 分类标签
    categoryTabs: [
        { id: null, name: '全部' },
        { id: 1, name: '种植' },
        { id: 2, name: '养殖' },
        { id: 3, name: '采摘' },
        { id: 4, name: '其他' },
    ],
    search: {
        pageNo: 1,
        pageSize: 10,
        publishstatu: 1,
        type: null,
        createBy: '',
    },
    employmentList: [],
    loading: false,
    total: 0,
    requestDebounce: null,
    // 用户当前位置
    userLocation: {
        longitude: uni.getStorageSync('location').lon,
        latitude: uni.getStorageSync('location').lat,
    },
})

onLoad((options) => {
    model.id = options.id
    model.name = decodeURIComponent(options.name)
    model.search.pageNo = 1
    model.search.publishstatu = 1
    model.search.createBy = ''
    model.employmentList = []
    getEmploymentList()
})

// 地图组件
const center: [number, number] = [uni.getStorageSync('location').lon, uni.getStorageSync('location').lat]
const [registerMap, map] = useMapbox({
    style: { center, zoom: 12 },
    onLoaded: (data) => {
        // 渲染用户当前位置
        const userLocationPoint = turf.point([
            model.userLocation.longitude,
            model.userLocation.latitude
        ], {
            name: '我的位置',
            description: '当前位置',
            icon: 'GD',
            popup: `我的位置`,
        })
        addDefaultGeoJSONSource(map, `${page.id}-user-location`, [userLocationPoint])
        addDefaultSymbolLayer(map, `${page.id}-user-location`, {
            layout: {
                'text-field': '',
                'icon-image': ['get', 'icon'],
                'icon-size': 1.2,
                'icon-allow-overlap': true,
            },
            paint: {
                'icon-color': '#FF4444',
            },
        })

        const employments = []
        // 渲染设备数据
        model.employmentList.forEach((item) => {
            employments.push(
                turf.point([item.longitude, item.latitude], {
                    name: item.name,
                    description: item.content,
                    icon: 'GD',
                    popup: `{{name}}`,
                }),
            )
        })
        addDefaultGeoJSONSource(map, `${page.id}-text`, employments)
        addDefaultSymbolLayer(map, `${page.id}-text`, {
            layout: {
                'text-field': '',
                'icon-image': ['get', 'icon'],
                'icon-size': 1,
            },
        })
    },
    onSourceRequestHandle: () => {
        page.requests--
        if (page.requests === 0) {
            Message.hideLoading()
        }
    },
    onSourceRequestErrorHandle: () => {
        Message.hideLoading()
    },
})
// 分类标签点击事件
function onCategoryTabClick(tab: any) {
    model.search.type = tab.id
    model.search.pageNo = 1
    model.employmentList = []
    getEmploymentList()
    // 在这里添加具体的分类标签点击逻辑
}

function getEmploymentList() {
    // 如果正在加载或没有更多数据，直接返回
    if (model.loading || (model.total > 0 && model.employmentList.length >= model.total)) {
        return
    }
    model.loading = true
    try {
        LinghuoyonggongAPI.employmentList(model.search).then(async (res) => {
            const { records, total } = res
            // 批量处理数据，避免多次DOM操作
            const processedRecords = records.map((item) => {
                // 缓存区域处理结果
                item.area = getText(item.area, ' / ')

                // 计算天数并缓存结果
                if (item.starttime && item.estimatedendtime) {
                    item.daysDiff = getDaysDiff(item.starttime, item.estimatedendtime)
                }

                return item
            })

            // 一次性更新数据，避免多次响应式更新
            if (model.search.pageNo === 1) {
                model.employmentList = processedRecords
            } else {
                // 避免重复数据加载
                const existingIds = new Set(model.employmentList.map((item) => item.id))
                const newRecords = processedRecords.filter((item) => !existingIds.has(item.id))
                model.employmentList = [...model.employmentList, ...newRecords]
            }

            model.total = total
        })
    } catch (error) {
        console.error('获取用工列表失败:', error)
        // 这里可以添加用户友好的错误提示
        // uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' })
    } finally {
        model.loading = false
        model.requestDebounce = null
    }
}

// 获取时间差
function getDaysDiff(date1: Date | number | string, date2: Date | number | string): number {
    // 将输入转换为Date对象
    const d1 = new Date(date1)
    const d2 = new Date(date2)

    // 检查日期是否有效
    if (Number.isNaN(d1.getTime()) || Number.isNaN(d2.getTime())) {
        throw new TypeError('无效的日期格式')
    }

    // 设置时间部分为00:00:00，只比较日期部分
    d1.setHours(0, 0, 0, 0)
    d2.setHours(0, 0, 0, 0)

    // 计算两个日期之间的毫秒差
    const diffTime = Math.abs(d2.getTime() - d1.getTime())

    // 转换为天数
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    return diffDays
}

// 回到当前位置
function backToUserLocation() {
    if (map && model.userLocation.longitude && model.userLocation.latitude) {
        flyTo(map, [model.userLocation.longitude, model.userLocation.latitude], 15, 0.5)
        uni.showToast({
            title: '已回到当前位置',
            icon: 'none',
            duration: 1500
        })
    } else {
        // 重新获取用户位置
        uni.getLocation({
            type: 'wgs84',
            success: (res) => {
                if (res.longitude !== 0 && res.latitude !== 0) {
                    model.userLocation.longitude = res.longitude
                    model.userLocation.latitude = res.latitude

                    // 更新缓存位置
                    uni.setStorageSync('location', {
                        lon: res.longitude,
                        lat: res.latitude,
                    })

                    // 更新地图上的用户位置标记
                    const userLocationPoint = turf.point([res.longitude, res.latitude], {
                        name: '我的位置',
                        description: '当前位置',
                        icon: 'user-location-icon',
                        popup: `我的位置`,
                    })
                    addDefaultGeoJSONSource(map, `${page.id}-user-location`, [userLocationPoint])
                    addDefaultSymbolLayer(map, `${page.id}-user-location`, {
                        layout: {
                            'text-field': '',
                            'icon-image': ['get', 'icon'],
                            'icon-size': 1.2,
                            'icon-allow-overlap': true,
                        },
                        paint: {
                            'icon-color': '#FF4444',
                        },
                    })

                    // 飞到用户位置
                    flyTo(map, [res.longitude, res.latitude], 15, 0.5)

                    uni.showToast({
                        title: '已获取并回到当前位置',
                        icon: 'none',
                        duration: 1500
                    })
                }
            },
            fail: (err) => {
                console.error('获取位置失败:', err)
                uni.showToast({
                    title: '获取位置失败，请检查定位权限',
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    }
}

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

<template>
    <view class="page h-95_dl_5vh bg-#E6F5E8 flex flex-col justify-between">
        <view class="h-200rpx p-3">
            <view class="w-full h-60rpx border-rd-3xl!">
                <fui-input :bottomLeft="0" class="w-full h-full border-rd-3xl!" borderTop placeholder="请输入搜索内容"
                    placeholderStyle="color: #CCCCCC; font-weight: 400; font-family: PingFangSC-Regular;"
                    v-model="text">
                    <template #left>
                        <view class="fui-left__icon">
                            <fui-icon name="search" color="#CCCCCC" :size="36" />
                        </view>
                    </template>
                </fui-input>
            </view>
            <view class="codefun-mt-14 codefun-flex-row group_2 gap-2">
                <view v-for="tab in model.categoryTabs" :key="tab.id"
                    class="codefun-flex-col codefun-justify-start codefun-items-center"
                    :class="[tab.id === model.search.type ? 'text-wrapper' : 'text-wrapper_2']"
                    @click="onCategoryTabClick(tab)">
                    <text class="font_2 text_2">
                        {{ tab.name }}
                    </text>
                </view>
            </view>
        </view>
        <!-- 地图组件 -->
        <!-- <view class="h-730 overflow-hidden map-box"> -->
        <view class="overflow-hidden map-box" style="height: calc(100vh - 200rpx)">
            <!-- 地图组件 -->
            <Mapbox @register="registerMap" />

            <!-- 回到当前位置按钮 -->
            <view class="location-control" @click="backToUserLocation">
                <view class="location-button">
                    <fui-icon name="location" color="#5DB66F" :size="36" />
                </view>
            </view>
        </view>
    </view>
</template>

<style lang="scss" scoped>
//
.page {
    min-height: 100vh;
    background: #E6F5E8;

    .map-box {
        // #ifdef APP-PLUS
        position: relative;
        top: 0;
        // #endif
        // #ifdef H5
        position: relative;
        top: 0;
        // #endif
        width: 690rpx;
        left: 30rpx;
        border-radius: 20rpx;
        background: #E6F5E8;
    }

    .group_2 {
        .text-wrapper {
            flex: 1 1 120rpx;
            background-color: #5db66f;
            border-radius: 19998rpx;
            line-height: 60rpx;
            height: 60rpx;

            .text_2 {
                color: #ffffff;
            }
        }

        .text-wrapper_2 {
            flex: 1 1 120rpx;
            line-height: 60rpx;
            background-color: #ffffff;
            border-radius: 19998rpx;
            height: 60rpx;

            .text_3 {
                line-height: 25.88rpx;
            }

            .text_4 {
                line-height: 26.16rpx;
            }

            .text_5 {
                line-height: 25.96rpx;
            }

            .text_6 {
                line-height: 25.68rpx;
            }
        }
    }

    // 回到当前位置控制按钮样式
    .location-control {
        position: absolute;
        bottom: 100rpx;
        right: 30rpx;
        z-index: 1000;

        .location-button {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 80rpx;
            height: 80rpx;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 50%;
            box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
            backdrop-filter: blur(10rpx);
            border: 2rpx solid #5DB66F;
            transition: all 0.3s ease;

            &:active {
                transform: scale(0.95);
                background: linear-gradient(135deg, #5DB66F 0%, #4CAF50 100%);

                :deep(.fui-icon) {
                    color: #FFFFFF !important;
                }
            }

            &:hover {
                transform: scale(1.05);
                box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.2);
            }
        }
    }
}
</style>
