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

    const userStore = useUserStore()
    onLoad((option) => {
        pageData.currentEmploymentId = Number(option.type) || 2
        // 预加载地区字典数据
        getDictData()
    })

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

    onPullDownRefresh(() => {
        resetGetEmploymentList().finally(() => {
            uni.stopPullDownRefresh()
        })
    })

    const pageData = reactive({
        loading: false,
        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,
        longitude: null,
        latitude: null,
        isShowConfirmDialog: false,
        dialogContent: '',
        delLaborId: null,
    })

    const { currentEmploymentId, employmentList, employmentTabs, searchValue } = toRefs(pageData)

    async function getEmploymentList() {
        if (pageData.loading || pageData.hasMore == 'noMore') return
        pageData.loading = true
        
        try {
            let res = null
            if (pageData.currentEmploymentId == 2) {
                res = await LinghuoyonggongAPI.getLaborAppList(pageData.search)
            } else {
                res = await LinghuoyonggongAPI.employmentList(pageData.search)
            }

            const { records, total } = res
            const processedRecords = records.map((item) => {
                // 统一地区展示逻辑：[区县/乡镇/村]
                if (pageData.currentEmploymentId == 2) {
                    item.areaLabel = item.villageFullName || item.villageName || '未知地区'
                } else {
                    const rawArea = item.area || item.scope
                    item.areaLabel = getText(rawArea, ' / ') || rawArea || '未知地区'
                }
                
                if (item.starttime && item.estimatedendtime) {
                    item.daysDiff = getDaysDiff(item.starttime, item.estimatedendtime)
                }
                
                if (typeof item.skills === 'string') {
                    item.skillList = item.skills.split(/[,，、/]/)
                } else if (Array.isArray(item.skills)) {
                    item.skillList = item.skills
                } else {
                    item.skillList = []
                }
                return item
            })
            
            if (pageData.search.pageNo === 1) {
                pageData.employmentList = processedRecords
            } else {
                pageData.employmentList = [...pageData.employmentList, ...processedRecords]
            }
            pageData.total = total
            pageData.hasMore = pageData.employmentList.length >= total ? 'noMore' : 'more'
        } finally {
            pageData.loading = false
        }
    }

    function onEmploymentTabClick(tab: any) {
        pageData.currentEmploymentId = tab.id
        resetGetEmploymentList()
    }

    function onEmploymentItemClick(item: any) {
        if (pageData.currentEmploymentId === 1) {
            Navigate.to(`/pages/linghuoyonggong/form?id=${item.id}`)
        } else {
            onDetailsClick(item)
        }
    }

    const registerDialogRef = ref()
    function onQuoteClick(item: any) {
        if (pageData.currentEmploymentId === 1) {
            registerDialogRef.value.open(item)
        } else {
            onDetailsClick(item)
        }
    }

    function handlePublish() {
        if (pageData.currentEmploymentId === 2) {
            Navigate.to('/pages/linghuoyonggong/publishEmployment')
        } else {
            Navigate.to('/pages/linghuoyonggong/form')
        }
    }

    function getDaysDiff(date1, date2) {
        const d1 = new Date(date1), d2 = new Date(date2)
        if (isNaN(d1.getTime()) || isNaN(d2.getTime())) return 0
        return Math.ceil(Math.abs(d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24))
    }

    function onSearch(res: any) {
        pageData.search.pageNo = 1
        if (pageData.currentEmploymentId === 1) pageData.search.createBy = res.value
        else pageData.search.keyword = res.value
        pageData.employmentList = []
        getEmploymentList()
    }

    async function resetGetEmploymentList() {
        pageData.employmentList = []
        pageData.search.pageNo = 1
        pageData.hasMore = 'more'
        pageData.search.keyword = ''
        pageData.search.createBy = ''
        return getEmploymentList()
    }

    function loadMoreData() {
        if (pageData.hasMore === 'noMore' || pageData.loading) return
        pageData.search.pageNo++
        getEmploymentList()
    }

    function onDetailsClick(item: any) {
        const param = encodeURIComponent(JSON.stringify({ id: item.id, villageName: item.villageName || item.name }))
        Navigate.to(`/pages/linghuoyonggong/details?param=${param}`)
    }

    function onMapModeClick() {
        Navigate.to(`/pages/linghuoyonggong/components/yonggongmap?currentEmploymentId=${pageData.currentEmploymentId}`)
    }

    function getUserLocation() {
        uni.getLocation({
            type: 'wgs84',
            success: (res) => {
                if (res.longitude !== 0) {
                    pageData.longitude = res.longitude
                    pageData.latitude = res.latitude
                }
            }
        })
    }

    function getDistanceText(item) {
        if (!item || !item.lon || !pageData.longitude) return ''
        const distance = turf.distance(turf.point([pageData.longitude, pageData.latitude]), turf.point([item.lon, item.lat]), { units: 'kilometers' })
        return distance < 1 ? `${Math.round(distance * 1000)}m` : `${distance.toFixed(1)}km`
    }
</script>

<template>
    <view class="page">
        <view class="top-search-view">
            <uni-search-bar radius="100" v-model="searchValue" placeholder="搜索标题、地点或技能" cancelButton="none" @confirm="onSearch" @clear="resetGetEmploymentList" />
        </view>
        
        <view class="tab-box">
            <view v-for="tab in employmentTabs" :key="tab.id" class="tab-item" :class="{ active: tab.id === currentEmploymentId }" @click="onEmploymentTabClick(tab)">
                <text class="tab-text">{{ tab.name }}</text>
            </view>
        </view>

        <scroll-view scroll-y class="list-scroll" @scrolltolower="loadMoreData">
            <view class="list-container">
                <view v-if="!employmentList.length && !pageData.loading" class="empty-box">
                    <fui-empty src="/static/images/no-data.png" title="暂无相关招聘信息" />
                </view>
                
                <view v-for="item in employmentList" :key="item.id" class="service-card" @click="onEmploymentItemClick(item)">
                    <view class="service-main">
                        <view class="service-img-box">
                            <image class="service-img" :src="item.picture || item.enterpriseLogoUrl || '/static/images/linghuoyonggong/avatar.png'" mode="aspectFill" lazy-load />
                            <view class="urgent-tag" v-if="item.urgentdegree > 3">急</view>
                        </view>
                        <view class="service-info">
                            <text class="service-title">{{ item.name || item.villageName }}</text>
                            <view class="service-tags">
                                <text class="s-tag" v-if="item.workers">需{{ item.workers }}人</text>
                                <text class="s-tag" v-if="item.daysDiff">约{{ item.daysDiff }}天</text>
                                <text class="s-tag skills" v-for="(skill, sIdx) in (item.skillList || []).slice(0, 2)" :key="sIdx">{{ skill }}</text>
                            </view>
                            <view class="service-price-row">
                                <text class="price-value">{{ item.price || '面议' }}</text>
                                <text class="price-unit" v-if="item.price">元/天</text>
                            </view>
                        </view>
                    </view>
                    <view class="service-footer">
                        <view class="footer-left">
                            <fui-icon name="location" :size="24" color="#999"></fui-icon>
                            <text class="footer-text">{{ item.areaLabel }}</text>
                            <text class="distance-text" v-if="getDistanceText(item)">{{ getDistanceText(item) }}</text>
                        </view>
                        <view class="action-btn" :class="{ 'bg-orange': currentEmploymentId == 2 }">
                            {{ currentEmploymentId == 1 ? '我也去' : '查看详情' }}
                        </view>
                    </view>
                </view>
                
                <fui-loadmore v-if="pageData.loading" />
                <view v-if="pageData.hasMore === 'noMore' && employmentList.length > 0" class="no-more">- 已经到底了 -</view>
            </view>
        </scroll-view>

        <!-- 统一的动效发布按钮 -->
        <view class="fab-container" @click="handlePublish">
            <view class="ripple"></view>
            <view class="ripple ripple-2"></view>
            <view class="fab-entry">
                <fui-icon name="plus" :size="48" color="#fff"></fui-icon>
                <text>发布</text>
            </view>
        </view>

        <!-- 地图模式切换 (悬浮胶囊) -->
        <view class="view-toggle-pill" @click="onMapModeClick">
            <fui-icon name="map" :size="32" color="#5db66f"></fui-icon>
            <text class="toggle-text">地图模式</text>
        </view>

        <RegisterDialog ref="registerDialogRef" />
    </view>
</template>

<style scoped lang="scss">
    .page { background-color: #f7f8fa; height: 100vh; display: flex; flex-direction: column; font-family: 'DingTalk Sans', sans-serif; }
    .top-search-view { background-color: #fff; padding: 10rpx 20rpx; }
    .tab-box {
        display: flex; background-color: #fff; padding: 0 30rpx 20rpx;
        .tab-item {
            flex: 1; height: 70rpx; display: flex; align-items: center; justify-content: center; font-size: 28rpx; color: #666; position: relative;
            &.active {
                color: #5db66f; font-weight: bold;
                &::after { content: ''; position: absolute; bottom: 0; width: 40rpx; height: 6rpx; background-color: #5db66f; border-radius: 3rpx; }
            }
        }
    }
    .list-scroll { flex: 1; overflow: hidden; }
    .list-container { padding: 20rpx; }

    .service-card {
        background-color: #fff; border-radius: 24rpx; padding: 24rpx; margin-bottom: 24rpx; box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
        .service-main { display: flex; }
        .service-img-box {
            width: 160rpx; height: 160rpx; border-radius: 12rpx; overflow: hidden; background-color: #f8f8f8; position: relative; flex-shrink: 0;
            .service-img { width: 100%; height: 100%; }
            .urgent-tag { position: absolute; left: 0; top: 0; background: #ff4d4f; color: #fff; font-size: 20rpx; padding: 4rpx 12rpx; border-bottom-right-radius: 12rpx; }
        }
        .service-info {
            flex: 1; margin-left: 20rpx; display: flex; flex-direction: column;
            .service-title { font-size: 30rpx; color: #333; font-weight: bold; line-height: 1.4; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 1; overflow: hidden; }
            .service-tags {
                display: flex; flex-wrap: wrap; margin-top: 12rpx;
                .s-tag { padding: 4rpx 12rpx; background-color: #f5f5f5; color: #666; font-size: 22rpx; border-radius: 4rpx; margin-right: 12rpx; margin-bottom: 8rpx; &.skills { background-color: #e6f7ff; color: #1890ff; } }
            }
            .service-price-row { margin-top: auto; display: flex; align-items: baseline; .price-value { font-size: 36rpx; color: #ff4d4f; font-weight: bold; } .price-unit { font-size: 24rpx; color: #999; margin-left: 4rpx; } }
        }
        .service-footer {
            margin-top: 24rpx; display: flex; justify-content: space-between; align-items: center; padding-top: 20rpx; border-top: 1rpx dashed #eee;
            .footer-left {
                display: flex; align-items: center; flex: 1; overflow: hidden;
                .footer-text { font-size: 22rpx; color: #999; margin-left: 4rpx; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
                .distance-text { font-size: 22rpx; color: #5db66f; margin-left: 12rpx; font-weight: bold; flex-shrink: 0; }
            }
            .action-btn { padding: 10rpx 28rpx; background-color: #5db66f; color: #fff; font-size: 24rpx; border-radius: 30rpx; margin-left: 20rpx; &.bg-orange { background-color: #fa8c16; } }
        }
    }

    /* 动态发布按钮 */
    .fab-container {
        position: fixed; right: 30rpx; bottom: 150rpx; width: 110rpx; height: 110rpx; z-index: 100; display: flex; align-items: center; justify-content: center;
        .ripple { position: absolute; width: 100%; height: 100%; background-color: #5db66f; border-radius: 50%; opacity: 0.4; animation: ripple 2s infinite ease-out; }
        .ripple-2 { animation-delay: 1s; }
        .fab-entry {
            position: relative; width: 110rpx; height: 110rpx; background: linear-gradient(135deg, #a5d63f 0%, #2e8b57 100%); border-radius: 50%; display: flex; flex-direction: column; align-items: center; justify-content: center; box-shadow: 0 8rpx 30rpx rgba(46, 139, 87, 0.5); animation: breathe 2.5s infinite ease-in-out; z-index: 2;
            text { font-size: 18rpx; color: #fff; margin-top: -4rpx; font-weight: bold; }
        }
    }

    @keyframes ripple { 0% { transform: scale(1); opacity: 0.4; } 100% { transform: scale(1.8); opacity: 0; } }
    @keyframes breathe { 0%, 100% { transform: scale(1); box-shadow: 0 8rpx 30rpx rgba(46, 139, 87, 0.5); } 50% { transform: scale(1.08); box-shadow: 0 12rpx 45rpx rgba(46, 139, 87, 0.7); } }

    /* 地图切换胶囊 */
    .view-toggle-pill {
        position: fixed;
        left: 50%;
        transform: translateX(-50%);
        bottom: 60rpx;
        background-color: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
        padding: 16rpx 40rpx;
        border-radius: 100rpx;
        display: flex;
        align-items: center;
        box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
        border: 1rpx solid #eee;
        z-index: 110;
        transition: all 0.3s;

        &:active {
            transform: translateX(-50%) scale(0.95);
            background-color: #fff;
        }

        .toggle-text {
            font-size: 26rpx;
            color: #333;
            font-weight: bold;
            margin-left: 12rpx;
        }
    }

    .no-more { text-align: center; font-size: 24rpx; color: #ccc; padding: 30rpx 0; }
    .empty-box { padding-top: 100rpx; }
</style>
