<script setup lang="ts">
    import { reactive } from 'vue'
    import { onLoad, onReachBottom, onShow } from '@dcloudio/uni-app'
    import RegisterDialog from './components/register-dialog.vue'
    import { getTextByCode } from '@/utils/areaData'
    import * as LinghuoyonggongAPI from '@/api/model/linghuoyonggong'
    import Navigate from '@/utils/page/navigate'
    import { getText } from '@/utils/dict/area'
    import { useUserStore } from '@/store/modules/user'
	import * as turf from '@turf/turf'

    const userStore = useUserStore()
    onLoad((option) => {
        pageData.currentEmploymentId = Number(option.type) || 2;
    })

    onShow(() => {
		getUserLocation();
        resetGetEmploymentList();
    })

    // 页面数据
    const pageData = reactive({
        loading: false,
		requestDebounce:null,
		searchValue:"",
        search: {
            pageNo: 1,
            pageSize: 10,
            publishstatu: 1,
            type: null,
            createBy: '',
			keyword:""
        },
		hasMore:'more',
        // 用工类型标签
        employmentTabs: [
			{ id: 2, name: '找人干活（找人）' },
            { id: 1, name: '出工赚钱（找事）' },
        ],
        currentEmploymentId: 2,

        // 用工列表
        employmentList: [],
        total: 0,
		dataTotal: 0,
		longitude:null,
		latitude:null,
    })

    // 缓存已处理的区域数据，避免重复计算
    const areaCache = new Map()

    // 请求重试配置
    const requestConfig = {
        maxRetries: 2,
        retryDelay: 1000,
    }
	
    // 带重试机制的API调用
    async function fetchWithRetry(apiCall, maxRetries = requestConfig.maxRetries) {
        const startTime = Date.now()

        for (let attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                const result = await apiCall()
                const endTime = Date.now()

                // 记录API性能数据（仅在开发环境）
                if (import.meta.env.DEV) {
                    console.log(`API请求成功，耗时: ${endTime - startTime}ms`)
                }

                return result
            } catch (error) {
                console.warn(`API请求失败 (尝试 ${attempt}/${maxRetries}):`, error)

                if (attempt === maxRetries) {
                    const endTime = Date.now()
                    if (import.meta.env.DEV) {
                        console.error(`API请求最终失败，总耗时: ${endTime - startTime}ms`)
                    }
                    throw error
                }

                // 指数退避策略
                await new Promise((resolve) => setTimeout(resolve, requestConfig.retryDelay * attempt))
            }
        }
    }

    function getEmploymentList() {
        // 如果正在加载或没有更多数据，直接返回
        if (pageData.loading || pageData.hasMore == 'noMore') {
            return;
        }
        pageData.loading = true;
        // 添加请求防抖，避免快速连续请求
        if (pageData.requestDebounce) {
            clearTimeout(pageData.requestDebounce)
        }
        pageData.requestDebounce = setTimeout(async () => {
            try {
                let res = null;
				if(pageData.currentEmploymentId == 2){
					res = await fetchWithRetry(() => LinghuoyonggongAPI.getLaborAppList(pageData.search))
				}else{
					res = await fetchWithRetry(() => LinghuoyonggongAPI.employmentList(pageData.search))
				}
				
				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
                })
				pageData.dataTotal += processedRecords.length;
                // 一次性更新数据，避免多次响应式更新
                if (pageData.search.pageNo === 1) {
                    pageData.employmentList = processedRecords;
                } else {
                    // 避免重复数据加载 感觉有坑
                    /* const existingIds = new Set(pageData.employmentList.map((item) => item.id))
                    const newRecords = processedRecords.filter((item) => !existingIds.has(item.id)) */
                    pageData.employmentList = [...pageData.employmentList, ...processedRecords]
                }
                pageData.total = total;
				if (pageData.dataTotal >= total) {
					pageData.hasMore = 'noMore'
				}
					  
            } catch (error) {
                console.error('获取用工列表失败:', error)
                // 这里可以添加用户友好的错误提示
                // uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' })
            } finally {
                pageData.loading = false
                pageData.requestDebounce = null
            }
        }, 150)
    }

    // 用工类型标签点击事件
    function onEmploymentTabClick(tab: any) {
        pageData.currentEmploymentId = tab.id
        resetGetEmploymentList()
    }

    // 用工项点击事件
    function onEmploymentItemClick(item: any) {
        console.log('点击用工项:', item)
        // 在这里添加具体的用工项点击逻辑
        Navigate.to(`/pages/linghuoyonggong/form?id=${item.id}`)
    }

    // "我想去"按钮点击事件
    const registerDialogRef = ref()
    function onQuoteClick(item: any) {
        console.log('点击立即报价:', item)
        // 在这里添加具体的立即报价点击逻辑
        registerDialogRef.value.open(item)
    }
    // 发布用工
    function handlePublish() {
		if(pageData.currentEmploymentId === 2){
			Navigate.to('/pages/linghuoyonggong/publishEmployment')
		}else{
			Navigate.to('/pages/linghuoyonggong/form')
		}
    }
    // 获取时间差
    function getDaysDiff(date1: Date | number | string, date2: Date | number | string): number {
        // 将输入转换为Date对象
        const d1 = new Date(date1)
        const d2 = new Date(date2)

        // 检查日期是否有效
        if (isNaN(d1.getTime()) || 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 onSearch(res:any){
		pageData.employmentList = [];
		pageData.search.pageNo = 1;
		pageData.dataTotal = 0;
		pageData.hasMore = 'more';
		if (pageData.currentEmploymentId === 1) {
		    pageData.search.publishstatu = 1
		    pageData.search.createBy = res.value
		}
		if (pageData.currentEmploymentId === 2) {
			pageData.search.keyword = res.value;
		}
		getEmploymentList()
	}
	// 取消搜索了
	function onSearchCancel(){
		resetGetEmploymentList();
	}
	function resetGetEmploymentList(){
		pageData.employmentList = []
		pageData.searchValue = "";
		pageData.search.pageNo = 1;
		pageData.dataTotal = 0;
		pageData.hasMore = 'more';
		if (pageData.currentEmploymentId === 1) {
		    pageData.search.publishstatu = 1
		    pageData.search.createBy = ''
		}
		pageData.search.keyword = "";
		getEmploymentList()
	}
	function loadMoreData(){
		pageData.search.pageNo++
		getEmploymentList()
	}
/*    onReachBottom(() => {
        console.log('触底了')
        if (pageData.total <= pageData.employmentList.length) {
            return
        }
		pageData.search.pageNo++
        getEmploymentList()
    }) */

    onNavigationBarButtonTap(() => {
        Navigate.to('/pages/linghuoyonggong/components/yonggongmap?currentEmploymentId='+pageData.currentEmploymentId);
    })
	
	// 查看找人干活详情
	function onDetailsClick(item: any) {
		let param = encodeURIComponent(JSON.stringify({id:item.id,villageName:item.villageName}));
	    Navigate.to('/pages/linghuoyonggong/details?param='+param);
	}
	// 获取用户位置
	function getUserLocation(){
		uni.getLocation({
		    type: 'wgs84',
		    success: (res) => {
		        if (res.longitude !== 0 && res.latitude !== 0) {
		            pageData.longitude = res.longitude
		            pageData.latitude = res.latitude
		        }
		    },
		    fail: (err) => {
		        console.error('获取位置失败:', err)
		        uni.showToast({
		            title: '获取位置失败，请检查定位权限',
		            icon: 'none',
		            duration: 2000,
		        })
		    },
		})
	}
	// 计算距离显示
	function getDistanceText(item) {
	    if (!item || !item.lon || !pageData.longitude) {
	        return '未知'
	    }
		// 使用turf计算距离
	    const from = turf.point([pageData.longitude, pageData.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`;
	}
</script>

<template>
    <view class="page">
        <scroll-view scroll-y="true" style="height: 100%;" class="codefun-flex-col" @scrolltolower="loadMoreData">
            <!-- <view class="codefun-mt-14 codefun-flex-row group_2 gap-2">
                <view
                    v-for="tab in pageData.categoryTabs"
                    :key="tab.id"
                    class="codefun-flex-col codefun-justify-start codefun-items-center"
                    :class="[tab.id === pageData.search.type ? 'text-wrapper' : 'text-wrapper_2']"
                    @click="onCategoryTabClick(tab)"
                >
                    <text class="font_2 text_2">
                        {{ tab.name }}
                    </text>
                </view>
            </view> -->

            <view class="codefun-mt-14 codefun-flex-col group_3">
				<view class="top-search-view">
					<uni-search-bar radius="100" v-model="pageData.searchValue" placeholder="请输入搜索内容" clearButton="auto" cancelButton="none" @confirm="onSearch"  @cancel="onSearchCancel" @clear="onSearchCancel"/>
				</view>
                <view class="codefun-flex-row section_2">
                    <view
                        v-for="tab in pageData.employmentTabs"
                        :key="tab.id"
                        class="codefun-flex-col codefun-justify-start codefun-items-center text-50p"
                        :class="[tab.id === pageData.currentEmploymentId ? 'text-wrapper_3' : 'codefun-self-start']"
                        @click="onEmploymentTabClick(tab)"
                    >
                        <text class="font_2">
                            {{ tab.name }}
                        </text>
                    </view>
                </view>
                <view class="codefun-flex-col codefun-relative list">
                    <view v-if="!pageData.employmentList || pageData.employmentList.length == 0" style="height: 700rpx">
                        <fui-empty marginTop="100" src="/static/images/no-data.png" title="暂无数据" />
                    </view>
                    <template v-else>
						<template v-if="pageData.currentEmploymentId == 1">
							<view
							    class="codefun-flex-col list-item"
							    v-for="item in pageData.employmentList"
							    :key="item.id"
							    @click="onEmploymentItemClick(item)"
							>
							    <view class="codefun-flex-row">
							        <image class="image_7" :src="item.picture" lazy-load />
							        <view class="codefun-flex-col codefun-flex-1 codefun-self-center group_4">
							            <view class="codefun-flex-row codefun-justify-between codefun-items-center">
							                <text class="codefun-self-start font">{{ item.name }}</text>
							                <view>
							                    <image
							                        class="codefun-self-start image_8"
							                        src="/static/images/codefun/c98744e63719b5413f260ec6a899ee20.png"
							                    />
							                    <text class="codefun-self-start font_3 text_9">{{ item.area }}</text>
							                </view>
							            </view>
							            <view
							                class="codefun-flex-row codefun-justify-between codefun-items-center codefun-self-stretch mt-11"
							            >
							                <view class="flex codefun-items-center gap-1">
							                    <image class="image_9" src="/static/images/time.svg" />
							                    <text class="font_4"
							                        >预计{{
							                            item.daysDiff || getDaysDiff(item.starttime, item.estimatedendtime)
							                        }}天</text
							                    >
							                </view>
							                <view class="flex codefun-items-center gap-1">
							                    <image class="image_9" src="/static/images/person.svg" />
							                    <text class="font_4">需要{{ item.workers }}人</text>
							                </view>
							                <view class="flex codefun-items-center gap-1">
							                    <image class="image_9" src="/static/images/money.svg" />
							                    <text class="font_4 text_10">{{ item.price }}元</text>
							                </view>
							            </view>
							        </view>
							    </view>
							    <view class="codefun-mt-8 codefun-flex-row codefun-justify-between codefun-items-center">
							        <view class="flex-center">
							            <fui-rate :score="item.urgentdegree" :size="36" />
							            <text class="font_5 ml-1">{{ item.urgentdegree }}</text>
							        </view>
							        <view
							            v-if="pageData.currentEmploymentId !== 2"
							            class="codefun-flex-col codefun-justify-start codefun-items-center text-wrapper_4"
							            @click.stop="onQuoteClick(item)"
							        >
							            <text class="font_6 text_12">我想去</text>
							        </view>
							    </view>
							</view>
						</template>
						<template v-else>
							<view class="work_list_view" v-for="item in pageData.employmentList" :key="item.id">
								<view class="d-flex j-sb">
									<view class="left-width village_number_view">
										<view class="village_view text_overflow_ellipsis">{{ item.villageName }}</view>
										<view class="d-flex align-center"><image class="avatar_icon" src="/static/images/linghuoyonggong/avatar.png" /><text class="text-color">待工人数{{item.workers}}名</text></view>
									</view>
									<view class="d-flex align-center justify-center right-width village_distance">
										<image class="distance_icon" src="/static/images/linghuoyonggong/distance.png" />
										<text class="distance_val text-color">{{getDistanceText(item)}}</text>
									</view>
								</view>
								<view class="d-flex j-sb skill_details_view" style="padding-bottom: 0px;">
									<view class="left-width d-flex j-sb align-center">
										<image class="skill_icon" src="/static/images/linghuoyonggong/skill.png" />
										<view class="skill_view text_overflow_ellipsis">技能：{{item.skills.length ? item.skills.join("、") : '未填写'}}</view>
									</view>
								</view>
								<view class="d-flex j-sb skill_details_view">
									<view class="left-width d-flex j-sb align-center">
										<image class="skill_icon" src="/static/images/linghuoyonggong/address.png" />
										<view class="skill_view text_overflow_ellipsis">地址：{{item.villageFullName}}</view>
									</view>
									<view class="right-width see_details_btn" @click="onDetailsClick(item)">查看详情</view>
								</view>
							</view>
						</template>
					</template>
                </view>
            </view>
			<view v-if="pageData.hasMore == 'noMore'" class="no-more">没有更多数据了</view>
        </scroll-view>
    </view>

    <fui-fab position="right" distance="10" 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" />
    <fui-loading isFixed v-if="pageData.loading" backgroundColor="rgba(0, 0, 0, 0.4)" />
</template>

<style scoped lang="scss">
    body {
        background-color: #e6f5e8;
    }
    .mt-19 {
        margin-top: 38rpx;
    }
    .ml-55 {
        margin-left: 110rpx;
    }
    .mt-11 {
        margin-top: 22rpx;
    }
    .ml-5 {
        margin-left: 10rpx;
    }
    .mt-269 {
        margin-top: 538rpx;
    }
    .page {
        // padding-bottom: 128rpx;
        background-color: #e6f5e8;
        mix-blend-mode: NOTTHROUGH;
        width: 100%;
        overflow-y: auto;
        overflow-x: hidden;
        height: calc(100vh - 88rpx);
		.top-search-view{
			height: 64rpx;
			
		}
        .section {
            padding: 26rpx 28rpx 26rpx 36rpx;
            background-color: #5db66f;
            mix-blend-mode: NOTTHROUGH;
            .image {
                border-radius: 64rpx;
                width: 108rpx;
                height: 42rpx;
            }
            .image_2 {
                mix-blend-mode: NOTTHROUGH;
                width: 34rpx;
                height: 22rpx;
            }
            .image_3 {
                mix-blend-mode: NOTTHROUGH;
                width: 30rpx;
                height: 22rpx;
            }
            .image_4 {
                width: 48rpx;
                height: 22rpx;
            }
            .group {
                padding: 8rpx 0 8rpx 6rpx;
                .image_6 {
                    mix-blend-mode: NOTTHROUGH;
                    width: 14rpx;
                    height: 26rpx;
                }
                .pos_2 {
                    position: absolute;
                    left: 6rpx;
                    top: 50%;
                    transform: translateY(-50%);
                }
                .text {
                    color: #ffffffe6;
                    line-height: 29.5rpx;
                }
                .image_5 {
                    width: 44rpx;
                    height: 44rpx;
                }
                .pos {
                    position: absolute;
                    right: 0.66rpx;
                    top: 50%;
                    transform: translateY(-50%);
                }
            }
        }
        .group_2 {
            padding: 0 28rpx;
            .text-wrapper {
                padding: 24rpx 0;
                flex: 1 1 120rpx;
                background-color: #5db66f;
                border-radius: 19998rpx;
                mix-blend-mode: NOTTHROUGH;
                height: 72rpx;
                .text_2 {
                    color: #ffffff;
                }
            }
            .text-wrapper_2 {
                flex: 1 1 120rpx;
                padding: 24rpx 0;
                background-color: #ffffff;
                border-radius: 19998rpx;
                mix-blend-mode: NOTTHROUGH;
                height: 72rpx;
                .text_3 {
                    line-height: 25.88rpx;
                }
                .text_4 {
                    line-height: 26.16rpx;
                }
                .text_5 {
                    line-height: 25.96rpx;
                }
                .text_6 {
                    line-height: 25.68rpx;
                }
            }
        }
        .group_3 {
            padding: 0 28rpx;
            // height: 685rpx;
			.top-search-view{
				.uni-searchbar{
					padding: 0rpx !important;
				}
			}
            .section_2 {
				margin-top: 48rpx;
                padding-bottom: 8rpx;
                background-color: #ffffff66;
                border-radius: 32rpx;
                border-left: solid 2rpx #ffffffcc;
                border-right: solid 2rpx #ffffffcc;
                border-top: solid 2rpx #ffffffcc;
                border-bottom: solid 2rpx #ffffffcc;
                .text-50p {
                    width: 50%;
                    padding: 0.75rem 0 1.625rem;
                }
                .text-wrapper_3 {
                    background-color: #ffffff;
                    border-radius: 32rpx;
                    .text_7 {
                        color: #333333;
                        line-height: 26.16rpx;
                    }
                    .font_2 {
                        color: #1f2937;
                    }
                }
                .codefun-self-start {
                    .font_2 {
                        color: #5db66f;
                    }
                }
                .text_8 {
                    margin-top: 20rpx;
                    color: #5db66f;
                }
            }
            .list {
                margin-top: -44rpx;
                padding: 0 24rpx;
                background-color: #ffffff;
                border-radius: 12.76rpx;
                mix-blend-mode: NOTTHROUGH;
                .list-item {
                    padding: 20rpx 0;
                    border-bottom: solid 2rpx #eeeeee;
                    .group_4 {
                        margin-left: 16rpx;
                        .image_9 {
                            width: 24rpx;
                            height: 24rpx;
                        }
                        .font_4 {
                            font-size: 24rpx;
                            font-family: DingTalk Sans;
                            // line-height: 22rpx;
                            color: #999999;
                        }
                        .text_10 {
                            // line-height: 23.36rpx;
                        }
                    }
                    .image_8 {
                        margin-left: 8rpx;
                        margin-top: 16rpx;
                        width: 22rpx;
                        height: 26rpx;
                    }
                    .font_3 {
                        font-size: 24rpx;
                        font-family: DingTalk Sans;
                        line-height: 17.6rpx;
                        color: #5db66f;
                    }
                    .text_9 {
                        margin: 20rpx 16rpx 0 8rpx;
                        line-height: 19.42rpx;
                    }
                    .font_5 {
                        font-size: 28rpx;
                        font-family: DingTalk Sans;
                        color: #999999;
                    }
                    .text_11 {
                        margin-left: 172rpx;
                    }
                    .text-wrapper_4 {
                        padding: 12rpx 0;
                        background-color: #5db66f;
                        border-radius: 400rpx;
                        mix-blend-mode: NOTTHROUGH;
                        width: 136rpx;
                        height: 48rpx;
                        .font_6 {
                            font-size: 24rpx;
                            font-family: DingTalk Sans;
                            line-height: 22rpx;
                            color: #ffffff;
                        }
                        .text_12 {
                            line-height: 22.18rpx;
                        }
                    }
                }
            }
        }
        .font_2 {
            font-size: 28rpx;
            font-family: DingTalk Sans;
            line-height: 26.02rpx;
            color: #1f2937;
        }
        .font {
            font-size: 32rpx;
            font-family: DingTalk Sans;
            line-height: 29.82rpx;
            color: #333333;
        }
        .image_7 {
            width: 96rpx;
            height: 96rpx;
            border-radius: 50%;
        }
        .image_12 {
            margin-right: 58rpx;
        }
    }
    ::v-deep .fui-fab__btn-main {
        background: linear-gradient(124.25deg, #a5d63f 0%, #5db66f 100%) !important;
        box-shadow: 0px 1px 8px #5db66f;
    }
	
	.work_list_view{
		border-bottom: 2rpx solid #EEEEEE;
		padding-top: 24rpx;
		.text-color{color: #5DB66F;font-size: 24rpx;}
		.d-flex{display: flex;}
		.j-sb{justify-content:space-between;}
		.text_overflow_ellipsis{
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
		.left-width{
			width:440rpx;
		}
		.right-width{
			width:140rpx;
		}
		.village_number_view{
			.village_view{
				height: 40rpx;
				line-height: 40rpx;
				margin-bottom: 12rpx;
				font-size: 32rpx;
				color: #333333;
			}
			.avatar_icon{
				width: 24rpx;
				height: 24rpx;
				margin-right: 10rpx;
			}
		}
		.village_distance{
			height: 26rpx;
			margin-top: 16rpx;
			.distance_icon{
				width: 24rpx;
				height: 28rpx;
			}
			.distance_val{
				margin-left: 6rpx;
			}
		}
		
		.skill_details_view{
			margin-top: 10rpx;
			padding-bottom: 24rpx;
			.skill_icon{
				width: 24rpx;
				height: 26rpx;
			}
			.skill_view{
				width:440rpx;
				font-size: 24rpx;
				height: 40rpx;
				line-height: 40rpx;
				color: #999999;
				margin-left: 10rpx;
			}
			.see_details_btn{
				height: 48rpx;
				border-radius: 200rpx;
				background: #5DB66F;
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 20rpx;
				font-size: 24rpx;
				color: #FFFFFF;
			}
		}
	}
	.no-more{
		padding-top: 40rpx;
		padding-bottom: 60rpx;
		width: 750rpx;
		text-align: center;
		font-size: 28rpx;
		color:#999999;
	}
</style>
