<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'

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

    onShow(() => {
        pageData.search.pageNo = 1
        if (pageData.currentEmploymentId === 1) {
            pageData.search.publishstatu = 1
            pageData.search.createBy = ''
        }
        if (pageData.currentEmploymentId === 2) {
            pageData.search.createBy = userStore.getUserInfo.username
        }
        pageData.employmentList = []
        getEmploymentList()
    })

    // 页面数据
    const pageData = reactive({
        loading: false,
        // 分类标签
        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: '',
        },
        // 用工类型标签
        employmentTabs: [
            { id: 1, name: '出工赚钱' },
            { id: 2, name: '找人干活' },
        ],
        currentEmploymentId: 1,

        // 用工列表
        employmentList: [],
        total: 0,
    })

    // 缓存已处理的区域数据，避免重复计算
    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.total > 0 && pageData.employmentList.length >= pageData.total)) {
            return
        }

        pageData.loading = true

        // 添加请求防抖，避免快速连续请求
        if (pageData.requestDebounce) {
            clearTimeout(pageData.requestDebounce)
        }

        pageData.requestDebounce = setTimeout(async () => {
            try {
                const 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
                })

                // 一次性更新数据，避免多次响应式更新
                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, ...newRecords]
                }

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

    // 分类标签点击事件
    function onCategoryTabClick(tab: any) {
        console.log('点击分类标签:', tab)
        pageData.search.type = tab.id
        pageData.search.pageNo = 1
        pageData.employmentList = []
        getEmploymentList()
        // 在这里添加具体的分类标签点击逻辑
    }

    // 用工类型标签点击事件
    function onEmploymentTabClick(tab: any) {
        pageData.currentEmploymentId = tab.id
        pageData.search.pageNo = 1
        pageData.employmentList = []
        if (pageData.currentEmploymentId === 1) {
            pageData.search.publishstatu = 1
            pageData.search.createBy = ''
        }
        if (pageData.currentEmploymentId === 2) {
            pageData.search.createBy = userStore.getUserInfo.username
        }
        getEmploymentList()
        // 在这里添加具体的用工类型标签点击逻辑
    }

    // 用工项点击事件
    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() {
        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
    }
    onReachBottom(() => {
        console.log('触底了')
        if (pageData.total <= pageData.employmentList.length) return
        pageData.search.pageNo++
        getEmploymentList()
    })
</script>

<template>
    <view class="codefun-flex-col page">
        <view class="codefun-flex-col codefun-self-stretch">
            <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="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>
                        <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>
                </view>
            </view>
        </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);
        .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;
            .section_2 {
                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;
    }
</style>
