<!-- 农场详情 -->
<script setup lang="ts">
import RegisterDialog from './register-dialog.vue'
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: [],
	
	employmentId:null,
	showConfirmDialog:false,
	contactName:"",
	contactMobile:"",
	
    // 分类标签
    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,
    },
    // 选中的用工信息
    selectedEmployment: null,
    showEmploymentPopup: false,
    searchText: '',
    // 标记点击事件是否已绑定
    clickEventBound: false,
	// 用于区分是哪个模块进的
	currentEmploymentId:1,
})

onLoad((options) => {
    model.id = options.id;
	model.currentEmploymentId = options.currentEmploymentId;
    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 registerDialogRef = ref()
const [registerMap, map] = useMapbox({
    style: { center, zoom: 10 },
    onLoaded: (data) => {
        // 渲染用户当前位置
        renderUserLocation()
    },
    onSourceRequestHandle: () => {
        page.requests--
        if (page.requests === 0) {
            Message.hideLoading()
        }
    },
    onSourceRequestErrorHandle: () => {
        Message.hideLoading()
    },
    onMapEvent: (event) => {
        // 处理来自 renderjs 层的自定义事件
        if (event.type === 'custom' && event.name === 'navigateToDetail') {
            console.log('接收到导航事件，id:', event)
            // Navigate.to(`/pages/linghuoyonggong/detail/index?id=${event.data}`)
			if(model.currentEmploymentId == 2){
				model.employmentId = event.data;
				getLaborAppDetail();
			}else{
				registerDialogRef.value.open({ id: event.data })
			}
        }
    }
})
async function getLaborAppDetail() {
	await LinghuoyonggongAPI.getLaborAppDetail({ id: model.employmentId }).then((res) => {
		model.contactMobile = res.contactMobile;
		model.contactName = res.contactName.substring(0,1) + new Array(res.contactName.length).join('*');
		model.showConfirmDialog = true;
	})
}
function makePhoneCall(){
	uni.makePhoneCall({
		phoneNumber: model.contactMobile
	});
}

// 创建弹框HTML内容
function createPopupHTML(employment) {
    if (!employment) return ''
	
	if(model.currentEmploymentId == 2){
		return `
			<div style="width: 220px;background:#FFFFFF;padding: 12px;display: flex;flex-direction: column;">
				<div style="display: flex;justify-content: space-between;line-height: 20px;">
					<div style="font-size: 16px;color: #333333;">${employment.villageName}</div>
					<div style="color: #5DB66F;font-size: 12px;display: flex;align-items: center;">
						<image style="width:11px;height:13px;margin-right:7px;" src="./static/images/linghuoyonggong/distance.png" />
						<div>${getDistanceText2(employment)}</div>
					</div>
				</div>
				<div style="color: #5DB66F;margin-top: 6px;line-height: 18px;font-size: 12px;display: flex;align-items: center;">
					<image style="width:12px;height:12px;margin-right:7px;" src="./static/images/linghuoyonggong/avatar.png" />
					<div>待工人数${employment.workers}名</div>
				</div>
				<div style="color: #999999;margin-top: 4px;line-height: 18px;font-size: 12px;display: flex;align-items: center;">
					<image style="width:11px;height:13px;margin-right:7px;" src="./static/images/linghuoyonggong/skill.png" />
					<div>技能：${employment.skills.length ? employment.skills.join("、") : '未填写'}</div>
				</div>
				<div style="color: #999999;margin-top: 4px;line-height: 18px;font-size: 12px;display: flex;align-items: center;">
					<image style="width:11px;height:13px;margin-right:7px;" src="./static/images/linghuoyonggong/address.png" />
					<div>地址：${employment.villageFullName}</div>
				</div>
				<a href="#" onclick="window.navigateToDetail('${employment.id}'); return false;" style="margin-top:8px;background: #5DB66F;text-decoration: none;border-radius: 200px;padding: 10px;text-align: center;color: #FFFFFF;font-size: 12px;display: flex;justify-content: center;align-items: center;">电话沟通</a>
			</div>
		`;
	}else{
		const distance = getDistanceText(employment)
		const stars = getStarsHTML(employment)
		return `
		     <div style="
		         max-width: 280px;
		         font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
		     ">
		         <div style="display: flex; gap: 6px; margin-bottom: 12px;">
		             <!-- 左侧图标 -->
		             <div style="
		                 width: 48px;
		                 height: 48px;
		                 border-radius: 50%;
		                 display: flex;
		                 align-items: center;
		                 justify-content: center;
		                 flex-shrink: 0;
		             ">
		                <img src="${employment.picture}" style="width: 48px; height: 48px; border-radius: 50%;" />
		             </div>
		             
		             <!-- 右侧内容 -->
		             <div style="flex: 1; min-width: 0;">
		                 <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
		                     <div style="
		                         font-size: 16px;
		                         font-weight: 600;
		                         color: #333333;
		                         overflow: hidden;
		                         text-overflow: ellipsis;
		                         white-space: nowrap;
		                         flex: 1;
		                     ">${employment.name}</div>
		                     <div style="
		                         background: #E8F5E9;
		                         color: #4CAF50;
		                         padding: 2px 8px;
		                         border-radius: 12px;
		                         font-size: 12px;
		                         white-space: nowrap;
		                         margin-left: 8px;
		                     ">📍 ${distance}</div>
		                 </div>
		                 
		                 <div style="display: flex; gap: 12px; font-size: 13px; color: #666666; margin-bottom: 8px;">
		                     <span>⏱ 时长${
		                         employment.daysDiff || getDaysDiff(employment.starttime, employment.estimatedendtime)
		                     }天</span>
		                     <span>👥 需${employment.workers || 0}人</span>
		                     <span>💰 ${employment.price || 0}元/天</span>
		                 </div>
		             </div>
		         </div>
		         
		         <div style="display: flex; align-items: center; justify-content: space-between;">
		             <div style="display: flex; align-items: center; gap: 4px;">
		                 ${stars.html}
		                 <span style="font-size: 13px; color: #666666; margin-left: 4px;">${stars.rating}</span>
		             </div>
		             <a href="#" onclick="window.navigateToDetail('${employment.id}'); return false;" style="
		                 display: inline-block;
		                 padding: 6px 20px;
		                 background: linear-gradient(135deg, #5DB66F 0%, #4CAF50 100%);
		                 color: white;
		                 text-decoration: none;
		                 border-radius: 16px;
		                 font-size: 14px;
		                 font-weight: 500;
		                 outline: none;
		                 border: none;
		                 transition: opacity 0.2s;">
		                 我想去
		             </a>
		         </div>
		     </div>
		 `
	}

}

// 渲染用户位置
function renderUserLocation() {
    const markerId = `my-local`
    // 修复 App 端图片路径问题
    const imageUrl = '/static/images/local-map.png'
    let finalImageUrl = imageUrl

    // #ifdef APP-PLUS
    // 在 App 端使用绝对路径
    finalImageUrl = `./static/images/local-map.png`
    // #endif

    const iconSize: [number, number] = [40, 40] // 图标大小

    // 使用 addMarker 添加到地图，带上 popup 和自定义图标
    map.addMarker(
        markerId,
        [model.userLocation.longitude, model.userLocation.latitude],
        '',
        false, // 不默认打开
        finalImageUrl, // 自定义图标图片URL
        iconSize, // 图标大小
    )
}

// 渲染用工标记
function renderEmploymentMarkers() {
    if (!map) {
        console.warn('地图未初始化')
        return
    }

    console.log('渲染用工标记数量:', model.employmentList.length)
    console.log('用工数据:', model.employmentList)

	let longitude = null,latitude = null;
    // 使用 Marker 方式渲染带自定义图标的标记
    model.employmentList.forEach((item) => {
		if(model.currentEmploymentId == 2){
			longitude = item.lon;
			latitude = item.lat;
		}else{
			longitude = item.longitude;
			latitude = item.latitude;
		}
        if (longitude && latitude) {
            const markerId = `employment-marker-${item.id}`
			let imageUrl = item.picture || '/static/images/linghuoyonggong/default-icon.png'
            // let imageUrl = '/static/images/linghuoyonggong/default-icon.png'
            const iconSize: [number, number] = [40, 40] // 图标大小

            // #ifdef APP-PLUS
            // 处理 App 端图片路径
            if (imageUrl.startsWith('/static/')) {
                imageUrl = `.${imageUrl}`
            }
            // #endif

            // 使用 addMarker 添加到地图，带上 popup 和自定义图标
            map.addMarker(
                markerId,
                [longitude, latitude],
                createPopupHTML(item),
                false, // 不默认打开
                imageUrl, // 自定义图标图片URL
                iconSize, // 图标大小
            )
        }
    })

    // 绑定点击事件标记
    if (!model.clickEventBound) {
        console.log('标记点击事件已绑定')
        model.clickEventBound = true
    }
}
// 分类标签点击事件
function onCategoryTabClick(tab: any) {
    model.search.type = tab.id
    model.search.pageNo = 1
    model.employmentList = []
    getEmploymentList()
    // 在这里添加具体的分类标签点击逻辑
}

async function getEmploymentList() {
    // 如果正在加载或没有更多数据，直接返回
    if (model.loading || (model.total > 0 && model.employmentList.length >= model.total)) {
        return
    }
    model.loading = true
    try {
		if(model.currentEmploymentId == 2){
		   await LinghuoyonggongAPI.getLaborAppList(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
			    // 数据加载完成后渲染地图标记
				setTimeout(()=>{
					renderEmploymentMarkers();
				},600)
			    /* nextTick(() => {
			        renderEmploymentMarkers()
			    }) */
			})
		}else{
			await 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
			
			    // 数据加载完成后渲染地图标记
				setTimeout(()=>{
					renderEmploymentMarkers();
				},600)
			    /* nextTick(() => {
			        renderEmploymentMarkers()
			    }) */
			})
		}
    } 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,
                    })

                    // 飞到用户位置
                    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,
                })
            },
        })
    }
}

// 关闭弹框
function closeEmploymentPopup() {
    model.showEmploymentPopup = false
    model.selectedEmployment = null
}
// 计算距离显示
function getDistanceText2(item) {
	if (!item || !item.lon || !model.userLocation.longitude) {
		return '未知'
	}
	// 使用turf计算距离
	const from = turf.point([model.userLocation.longitude, model.userLocation.latitude])
	const to = turf.point([item.lon, item.lat])
	const distance = turf.distance(from, to, { units: 'kilometers' })

	if (distance < 1) {
		return `${Math.round(distance * 1000)}m`;
	}
	return `${distance.toFixed(1)}km`;
}
// 计算距离显示
function getDistanceText(employment) {
    if (!employment || !employment.longitude || !employment.latitude) {
        return '未知'
    }
    // 使用turf计算距离
    const from = turf.point([model.userLocation.longitude, model.userLocation.latitude])
    const to = turf.point([employment.longitude, employment.latitude])
    const distance = turf.distance(from, to, { units: 'kilometers' })

    if (distance < 1) {
        return `${Math.round(distance * 1000)}m`
    }
    return `${distance.toFixed(1)}km`
}

// 生成星级HTML
function getStarsHTML(employment) {
    // 获取紧急程度，默认为0
    const urgentdegree = Number(employment.urgentdegree) || 0
    // 确保评级在0-5之间
    const rating = Math.max(0, Math.min(5, urgentdegree))
    
    let html = ''
    for (let i = 1; i <= 5; i++) {
        if (i <= rating) {
            html += '<span style="color: #FF9800; font-size: 16px;">★</span>'
        } else {
            html += '<span style="color: #E0E0E0; font-size: 16px;">★</span>'
        }
    }
    
    return {
        html,
        rating
    }
}
// 发布用工
function handlePublish() {
	if(model.currentEmploymentId == 2){
		Navigate.to('/pages/linghuoyonggong/publishEmployment')
	}else{
		Navigate.to('/pages/linghuoyonggong/form')
	}
}
onNavigationBarButtonTap((e) => {
    console.log(e)
    if (e.index === 0) {
        Navigate.to('/pages/linghuoyonggong/linghuoyonggong')
    }
})
</script>

<template>
    <view class="page h-95_dl_5vh bg-#E6F5E8 flex flex-col">
        <view class="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="model.searchText"
                >
                    <template #left>
                        <view class="fui-left__icon">
                            <fui-icon name="search" color="#CCCCCC" :size="36" />
                        </view>
                    </template>
                </fui-input>
            </view>
            <view v-if="model.currentEmploymentId != 2" 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">
                    <image src="/static/images/toLocal.png" style="width: 58rpx; height: 58rpx"></image>
                    <!-- <fui-icon name="location" color="#5DB66F" :size="36" /> -->
                </view>
            </view>
        </view>
        <fui-fab position="right" distance="30" bottom="240" width="96" @click="handlePublish">
            <view class="text-white text-center">
                <view class="fab-icon" />
                <view style="font-size: 24rpx">发布</view>
            </view>
        </fui-fab>
        <RegisterDialog ref="registerDialogRef" />
		<!-- 确认对话框 -->
		<ConfirmDialog
		    v-model:show="model.showConfirmDialog"
		    title="温馨提示"
		    :content="`你将与${model.contactName}进行电话沟通，若继续，请点击确认按钮！`"
		    cancelText="取消"
		    confirmText="确认"
		    @confirm="makePhoneCall"
		/>
    </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: 10rpx;
        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);
            }
        }
    }
}
::v-deep .mapboxgl-popup {
    max-width: 568rpx !important;
}
::v-deep .fui-fab__btn-main {
    background: linear-gradient(124.25deg, #a5d63f 0%, #5db66f 100%) !important;
    box-shadow: 0px 1px 8px #5db66f;
}
::v-deep .mapboxgl-popup a {
    outline: none !important;
    -webkit-tap-highlight-color: transparent !important;
    -webkit-touch-callout: none !important;
}
</style>
