<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) {
                    // 找人干活 - villageFullName 或 villageName
                    let areaText = item.villageFullName || item.villageName || '未知地区'
                    // 处理多种分隔符：/ 或 空格
                    let parts = areaText.split('/')
                    if (parts.length === 1) {
                        parts = areaText.split(' ')
                    }
                    if (parts.length > 1) {
                        // 去掉第一部分（省份）
                        areaText = parts.slice(1).join('/')
                    }
                    // 如果还有"省"字开头，再去掉
                    if (areaText.includes('省')) {
                        const idx = areaText.indexOf('省')
                        if (idx >= 0 && idx < 6) {
                            areaText = areaText.substring(idx + 1)
                        }
                    }
                    item.areaLabel = areaText
                } else {
                    // 出工赚钱 - area 或 scope
                    const rawArea = item.area || item.scope
                    let areaText = getText(rawArea, ' / ') || rawArea || '未知地区'
                    // 处理分隔符
                    let parts = areaText.split(' / ')
                    if (parts.length === 1) {
                        parts = areaText.split('/')
                    }
                    if (parts.length > 1) {
                        // 去掉第一部分（省份）
                        areaText = parts.slice(1).join(' / ')
                    }
                    // 如果还有"省"字开头，再去掉
                    if (areaText.includes('省')) {
                        const idx = areaText.indexOf('省')
                        if (idx >= 0 && idx < 6) {
                            areaText = areaText.substring(idx + 1)
                        }
                    }
                    item.areaLabel = areaText
                }
                
                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 openMapNavigation(item: any) {
        const lat = item.latitude || item.lat
        const lon = item.longitude || item.lon || item.lng
        const name = item.name || item.villageName || '目的地'
        const address = item.areaLabel || item.address || ''

        if (!lat || !lon) {
            uni.showToast({ title: '暂无位置信息', icon: 'none' })
            return
        }

        // 打开系统地图导航
        uni.openLocation({
            latitude: parseFloat(lat),
            longitude: parseFloat(lon),
            name: name,
            address: address,
            scale: 16
        })
    }

    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="header-section">
            <view class="search-bar">
                <view class="search-input-wrap">
                    <fui-icon name="search" :size="28" color="#bbb"></fui-icon>
                    <input class="search-input" v-model="searchValue" placeholder="搜索标题、地点或技能" placeholder-class="search-placeholder" @confirm="onSearch" @input="searchValue = $event.detail.value" />
                </view>
                <view class="search-btn" @click="onSearch({ value: searchValue })">
                    <text>搜索</text>
                </view>
            </view>
        </view>

        <!-- Tab切换 -->
        <view class="tab-section">
            <view class="tab-list">
                <view v-for="tab in employmentTabs" :key="tab.id" class="tab-item" :class="{ active: tab.id === currentEmploymentId }" @click="onEmploymentTabClick(tab)">
                    <view class="tab-avatar farmer" v-if="tab.id === 2">
                        <text class="avatar-icon">👨‍🌾</text>
                    </view>
                    <view class="tab-avatar worker" v-else>
                        <text class="avatar-icon">👷</text>
                    </view>
                    <text class="tab-text">{{ tab.id === 2 ? '找人干活' : '出工赚钱' }}</text>
                </view>
            </view>
        </view>

        <!-- 列表区域 -->
        <scroll-view scroll-y class="list-scroll" @scrolltolower="loadMoreData">
            <view class="list-container">
                <!-- 空状态 -->
                <view v-if="!employmentList.length && !pageData.loading" class="empty-section">
                    <image class="empty-img" src="/static/images/no-data.png" mode="aspectFit" />
                    <text class="empty-title">暂无相关信息</text>
                    <text class="empty-desc">{{ currentEmploymentId === 2 ? '还没有发布招聘，快去发布吧' : '还没有求职信息' }}</text>
                </view>

                <!-- 列表卡片 -->
                <view v-for="item in employmentList" :key="item.id" class="job-card" @click="onEmploymentItemClick(item)">
                    <view class="card-header">
                        <view class="company-logo">
                            <image :src="item.picture || item.enterpriseLogoUrl || '/static/images/linghuoyonggong/default.png'" mode="aspectFill" />
                            <view class="urgent-badge" v-if="item.urgentdegree > 3">急招</view>
                        </view>
                        <view class="card-title-area">
                            <text class="job-title">{{ item.name || item.villageName }}</text>
                            <view class="job-meta">
                                <text class="meta-item" v-if="item.workers">
                                    <text class="meta-num">{{ item.workers }}</text>人
                                </text>
                                <text class="meta-divider" v-if="item.workers && item.daysDiff">|</text>
                                <text class="meta-item" v-if="item.daysDiff">
                                    <text class="meta-num">{{ item.daysDiff }}</text>天
                                </text>
                            </view>
                        </view>
                        <view class="price-area">
                            <text class="price-symbol">¥</text>
                            <text class="price-num">{{ item.price || '面议' }}</text>
                            <text class="price-unit" v-if="item.price">/天</text>
                        </view>
                    </view>

                    <view class="card-tags" v-if="item.skillList && item.skillList.length">
                        <text class="skill-tag" v-for="(skill, sIdx) in item.skillList.slice(0, 3)" :key="sIdx">{{ skill }}</text>
                    </view>

                    <view class="card-footer">
                        <view class="location-info" @click.stop="openMapNavigation(item)">
                            <fui-icon name="location" :size="24" color="#5db66f"></fui-icon>
                            <text class="location-text">{{ item.areaLabel }}</text>
                            <text class="distance-tag" v-if="getDistanceText(item)">{{ getDistanceText(item) }}</text>
                        </view>
                        <view class="action-btn" :class="{ 'btn-orange': currentEmploymentId === 2, 'btn-green': currentEmploymentId === 1 }" @click.stop="onQuoteClick(item)">
                            {{ currentEmploymentId === 1 ? '我要报名' : '查看详情' }}
                        </view>
                    </view>
                </view>

                <fui-loadmore v-if="pageData.loading" />
                <view v-if="pageData.hasMore === 'noMore' && employmentList.length > 0" class="no-more-tip">
                    <view class="line"></view>
                    <text>已经到底了</text>
                    <view class="line"></view>
                </view>
            </view>

            <!-- 底部安全区占位 -->
            <view class="safe-bottom"></view>
        </scroll-view>

        <!-- 悬浮操作区 -->
        <view class="float-actions">
            <!-- 发布按钮 -->
            <view class="fab-btn" @click="handlePublish">
                <view class="fab-ripple"></view>
                <view class="fab-ripple delay"></view>
                <view class="fab-inner">
                    <fui-icon name="plus" :size="40" color="#fff"></fui-icon>
                    <text>发布</text>
                </view>
            </view>

            <!-- 地图模式 -->
            <view class="map-btn" @click="onMapModeClick">
                <view class="map-pulse"></view>
                <fui-icon name="map" :size="32" color="#fff"></fui-icon>
                <text>地图</text>
            </view>
        </view>

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

<style scoped lang="scss">
    .page {
        background-color: #f5f6f8;
        min-height: 100vh;
        display: flex;
        flex-direction: column;
    }

    /* 头部搜索 */
    .header-section {
        background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
        padding: 16rpx 24rpx 20rpx;
    }

    .search-bar {
        display: flex;
        align-items: center;
        gap: 12rpx;

        .search-input-wrap {
            flex: 1;
            display: flex;
            align-items: center;
            height: 64rpx;
            background-color: #fff;
            border-radius: 32rpx;
            padding: 0 20rpx;

            .search-input {
                flex: 1;
                font-size: 26rpx;
                color: #333;
                margin-left: 10rpx;
            }
        }

        .search-btn {
            padding: 0 24rpx;
            height: 64rpx;
            background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
            border-radius: 32rpx;
            display: flex;
            align-items: center;
            justify-content: center;

            text {
                font-size: 26rpx;
                color: #fff;
                font-weight: 500;
            }
        }
    }

    .search-placeholder {
        color: #bbb;
        font-size: 26rpx;
    }

    /* Tab切换 */
    .tab-section {
        background-color: #fff;
        padding: 12rpx 24rpx;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

        .tab-list {
            display: flex;
            gap: 16rpx;
        }

        .tab-item {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 12rpx 0;
            background-color: #f7f8fa;
            border-radius: 12rpx;
            transition: all 0.3s;

            .tab-avatar {
                width: 44rpx;
                height: 44rpx;
                border-radius: 50%;
                overflow: hidden;
                margin-right: 10rpx;
                border: 2rpx solid #fff;
                box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #fff;

                .avatar-icon {
                    font-size: 28rpx;
                    line-height: 1;
                }

                &.farmer {
                    background: linear-gradient(135deg, #e6f5e8 0%, #d4edda 100%);
                }

                &.worker {
                    background: linear-gradient(135deg, #fff7e6 0%, #ffe7ba 100%);
                }
            }

            .tab-text {
                font-size: 26rpx;
                color: #333;
                font-weight: 500;
            }

            &.active {
                background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
                box-shadow: 0 4rpx 16rpx rgba(93, 182, 111, 0.35);

                .tab-avatar {
                    border-color: rgba(255, 255, 255, 0.5);
                }

                .tab-text {
                    color: #fff;
                }
            }
        }
    }

    /* 列表区域 */
    .list-scroll {
        flex: 1;
        overflow: hidden;
    }

    .list-container {
        padding: 20rpx 24rpx;
    }

    /* 空状态 */
    .empty-section {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 120rpx 0;

        .empty-img {
            width: 240rpx;
            height: 240rpx;
            opacity: 0.6;
        }

        .empty-title {
            font-size: 30rpx;
            color: #333;
            font-weight: 500;
            margin-top: 24rpx;
        }

        .empty-desc {
            font-size: 24rpx;
            color: #999;
            margin-top: 8rpx;
        }
    }

    /* 职位卡片 */
    .job-card {
        background-color: #fff;
        border-radius: 20rpx;
        padding: 24rpx;
        margin-bottom: 20rpx;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

        .card-header {
            display: flex;
            align-items: flex-start;

            .company-logo {
                width: 96rpx;
                height: 96rpx;
                border-radius: 16rpx;
                overflow: hidden;
                background-color: rgba(243, 255, 227, 1);
                flex-shrink: 0;
                position: relative;

                image {
                    width: 100%;
                    height: 100%;
                }

                .urgent-badge {
                    position: absolute;
                    top: 0;
                    left: 0;
                    background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
                    color: #fff;
                    font-size: 18rpx;
                    padding: 4rpx 10rpx;
                    border-bottom-right-radius: 12rpx;
                    font-weight: 500;
                }
            }

            .card-title-area {
                flex: 1;
                margin-left: 16rpx;

                .job-title {
                    font-size: 30rpx;
                    color: #333;
                    font-weight: 600;
                    display: block;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                .job-meta {
                    display: flex;
                    align-items: center;
                    margin-top: 10rpx;

                    .meta-item {
                        font-size: 24rpx;
                        color: #666;

                        .meta-num {
                            color: #5db66f;
                            font-weight: 600;
                            font-size: 26rpx;
                        }
                    }

                    .meta-divider {
                        margin: 0 12rpx;
                        color: #ddd;
                    }
                }
            }

            .price-area {
                text-align: right;
                flex-shrink: 0;

                .price-symbol {
                    font-size: 24rpx;
                    color: #ff4d4f;
                    font-weight: 500;
                }

                .price-num {
                    font-size: 36rpx;
                    color: #ff4d4f;
                    font-weight: 700;
                    margin-left: 2rpx;
                }

                .price-unit {
                    font-size: 22rpx;
                    color: #999;
                    margin-left: 2rpx;
                }
            }
        }

        .card-tags {
            display: flex;
            flex-wrap: wrap;
            margin-top: 16rpx;

            .skill-tag {
                padding: 6rpx 16rpx;
                background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
                color: #1890ff;
                font-size: 22rpx;
                border-radius: 8rpx;
                margin-right: 12rpx;
                margin-bottom: 8rpx;
                font-weight: 500;
            }
        }

        .card-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 20rpx;
            padding-top: 20rpx;
            border-top: 1rpx solid #f5f5f5;

            .location-info {
                display: flex;
                align-items: center;
                flex: 1;
                min-width: 0;
                cursor: pointer;

                .location-text {
                    font-size: 24rpx;
                    color: #5db66f;
                    margin-left: 6rpx;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    max-width: 280rpx;
                }

                .distance-tag {
                    font-size: 22rpx;
                    color: #5db66f;
                    background-color: #e6f5e8;
                    padding: 4rpx 12rpx;
                    border-radius: 6rpx;
                    margin-left: 12rpx;
                    font-weight: 500;
                    flex-shrink: 0;
                }
            }

            .action-btn {
                padding: 12rpx 28rpx;
                border-radius: 24rpx;
                font-size: 24rpx;
                font-weight: 500;
                flex-shrink: 0;
                margin-left: 16rpx;

                &.btn-green {
                    background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
					box-shadow: 0 4rpx 12rpx rgba(93, 182, 111, 0.3);
                    color: #fff;
                }

                &.btn-orange {
                    /* background: linear-gradient(135deg, #fa8c16 0%, #fa541c 100%);
					box-shadow: 0 4rpx 12rpx rgba(250, 140, 22, 0.3); */
					background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
					box-shadow: 0 4rpx 12rpx rgba(93, 182, 111, 0.3);
                    color: #fff;
                    
                }
            }
        }
    }

    /* 底部提示 */
    .no-more-tip {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 40rpx 0;

        .line {
            width: 60rpx;
            height: 1rpx;
            background-color: #ddd;
        }

        text {
            font-size: 24rpx;
            color: #bbb;
            margin: 0 20rpx;
        }
    }

    .safe-bottom {
        height: 180rpx;
    }

    /* 悬浮操作区 */
    .float-actions {
        position: fixed;
        right: 24rpx;
        bottom: 120rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 16rpx;
        z-index: 100;

        .fab-btn {
            position: relative;
            width: 100rpx;
            height: 100rpx;

            .fab-ripple {
                position: absolute;
                width: 100%;
                height: 100%;
                background-color: #5db66f;
                border-radius: 50%;
                opacity: 0.3;
                animation: fabRipple 2s infinite ease-out;
            }

            .fab-ripple.delay {
                animation-delay: 1s;
            }

            .fab-inner {
                position: relative;
                width: 100rpx;
                height: 100rpx;
                background: linear-gradient(135deg, #5db66f 0%, #3da553 100%);
                border-radius: 50%;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                box-shadow: 0 8rpx 24rpx rgba(93, 182, 111, 0.5);
                z-index: 2;
                animation: fabBreathe 2.5s infinite ease-in-out;

                text {
                    font-size: 18rpx;
                    color: #fff;
                    font-weight: 600;
                    margin-top: 2rpx;
                }
            }
        }

        .map-btn {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 88rpx;
            height: 88rpx;
            background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
            border-radius: 50%;
            box-shadow: 0 6rpx 20rpx rgba(24, 144, 255, 0.4);

            text {
                font-size: 20rpx;
                color: #fff;
                font-weight: 500;
                margin-top: 2rpx;
            }

            .map-pulse {
                position: absolute;
                width: 100%;
                height: 100%;
                border-radius: 50%;
                border: 2rpx solid #1890ff;
                animation: mapPulse 2s infinite ease-out;
            }
        }
    }

    @keyframes fabRipple {
        0% { transform: scale(1); opacity: 0.3; }
        100% { transform: scale(1.8); opacity: 0; }
    }

    @keyframes fabBreathe {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.05); }
    }

    @keyframes mapPulse {
        0% { transform: scale(1); opacity: 0.6; }
        100% { transform: scale(1.5); opacity: 0; }
    }
</style>
