<script setup lang="ts">
    import { reactive, ref, toRefs } from 'vue'
    import { onLoad, onReachBottom, onShow, onPullDownRefresh } from '@dcloudio/uni-app'
    import ApplyDialog from './components/apply-dialog.vue'
    import * as NongjifuwuAPI from '@/api/model/nongjifuwu'
    import * as NongzhiAPI from '@/api/model/nongzhi'
    import Navigate from '@/utils/page/navigate'
    import { getDictData, getText } from '@/utils/dict/area'
    import AreaPicker from '@/components/AreaPicker/index.vue'

    onLoad((option) => {
        pageData.search.serviceType = Number(option.type) || 1
        getDictData()
    })

    onShow(() => {
        resetList()
    })

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

    const pageData = reactive({
        loading: false,
        show: {
            address: false,
        },
        optionsValText: '',
        categoryTabs: [
            { id: 1, name: '找农机' },
            { id: 2, name: '干农活' },
        ],
        search: {
            pageNo: 1,
            pageSize: 10,
            serviceType: 1,
            scope: null,
            bizCategory: 3,
            reviewStatus: 1,
        },
        farmMachineList: [],
        total: 0,
    })

    const { farmMachineList, categoryTabs, search, loading, optionsValText } = toRefs(pageData)

    function handleAreaConfirm(e) {
        pageData.search.scope = e.fullCode
        pageData.optionsValText = e.fullText
        resetList()
    }

    async function fetchList() {
        pageData.loading = true
        try {
            let res
            if (pageData.search.serviceType == 1) {
                res = await NongzhiAPI.getEnterpriseList(pageData.search)
            } else {
                res = await NongjifuwuAPI.farmMachineList(pageData.search)
            }
            const { records, total } = res
            if (pageData.search.pageNo === 1) {
                pageData.farmMachineList = records
            } else {
                pageData.farmMachineList = [...pageData.farmMachineList, ...records]
            }
            pageData.total = total
        } finally {
            pageData.loading = false
        }
    }

    async function resetList() {
        pageData.search.pageNo = 1
        pageData.farmMachineList = []
        return fetchList()
    }

    function onCategoryTabClick(tab: any) {
        pageData.search.serviceType = tab.id
        resetList()
    }

    function handleItemClick(item: any) {
        const path = pageData.search.serviceType === 1 ? 'machine-form' : 'farm-form'
        Navigate.to(`/pages/nongjifuwu/${path}?id=${item.id}&type=${pageData.search.serviceType}`)
    }

    const applyDialogRef = ref()
    function handleApply(item: any) {
        applyDialogRef.value.open(item)
    }

    function toEnterpriseDetail(item) {
        const param = encodeURIComponent(JSON.stringify({ id: item.id, name: item.enterpriseName }))
        Navigate.to(`/pages/nongjifuwu/detail?param=${param}`)
    }

    onReachBottom(() => {
        if (pageData.farmMachineList.length >= pageData.total) return
        pageData.search.pageNo++
        fetchList()
    })
</script>

<template>
    <view class="page">
        <!-- 顶部筛选栏 -->
        <view class="filter-bar">
            <view class="area-picker" @click="pageData.show.address = true">
                <fui-icon name="location" :size="28" color="#5db66f"></fui-icon>
                <text class="area-text">{{ optionsValText || '服务区域' }}</text>
                <fui-icon name="arrowdown" :size="24" color="#ccc"></fui-icon>
            </view>
            <view class="tab-box">
                <view
                    v-for="item in categoryTabs"
                    :key="item.id"
                    class="tab-item"
                    :class="{ active: item.id === search.serviceType }"
                    @click="onCategoryTabClick(item)"
                >
                    {{ item.name }}
                </view>
            </view>
        </view>

        <scroll-view scroll-y class="list-scroll">
            <view class="list-container">
                <view v-if="!farmMachineList.length && !loading" class="empty-box">
                    <fui-empty src="/static/images/no-data.png" title="暂无相关服务" />
                </view>

                <!-- 找农机 (企业/合作社列表) -->
                <template v-if="search.serviceType == 1">
                    <view v-for="item in farmMachineList" :key="item.id" class="enterprise-card" @click="toEnterpriseDetail(item)">
                        <view class="card-main">
                            <image class="logo" :src="item.enterpriseLogoUrl || '/static/images/nongjifuwu/default-corp.png'" mode="aspectFill" />
                            <view class="info">
                                <text class="name">{{ item.enterpriseName }}</text>
                                <text class="scope">主营：{{ item.businessScope || '综合农机服务' }}</text>
                                <view class="tags">
                                    <text class="tag">认证企业</text>
                                    <text class="tag orange">专业团队</text>
                                </view>
                            </view>
                        </view>
                        <view class="card-footer">
                            <view class="addr">
                                <fui-icon name="location" :size="24" color="#999"></fui-icon>
                                <text>{{ item.provinceName }}{{ item.cityName }}{{ item.districtName }}</text>
                            </view>
                            <view class="btn">查看详情</view>
                        </view>
                    </view>
                </template>

                <!-- 干农活 (具体服务列表) -->
                <template v-else>
                    <view v-for="item in farmMachineList" :key="item.id" class="service-card" @click="handleItemClick(item)">
                        <view class="card-main">
                            <image class="thumb" :src="item.picture || '/static/images/nongjifuwu/default-service.png'" mode="aspectFill" />
                            <view class="info">
                                <text class="title">{{ item.name }}</text>
                                <text class="desc">范围：{{ getText(item.scope, ' / ') }}</text>
                                <view class="price-row">
                                    <text class="price">{{ item.price }}</text>
                                    <text class="unit">元/亩</text>
                                </view>
                            </view>
                        </view>
                        <view class="card-footer">
                            <view class="status">服务中</view>
                            <view class="btn orange" @click.stop="handleApply(item)">立即预约</view>
                        </view>
                    </view>
                </template>
                
                <fui-loadmore v-if="loading" />
            </view>
        </scroll-view>

        <!-- 商家入驻悬浮按钮 (增加水波纹动效) -->
        <view class="fab-container" @click="Navigate.to('/pages/nongjifuwu/shenqingruzhu')">
            <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>

        <AreaPicker v-model:show="pageData.show.address" :layer="2" rootCode="43" title="选择服务区域" @confirm="handleAreaConfirm" />

        <ApplyDialog ref="applyDialogRef" />
    </view>
</template>

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

    .filter-bar {
        background-color: #fff;
        padding: 20rpx 30rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .area-picker {
            display: flex;
            align-items: center;
            background-color: #f5f5f5;
            padding: 10rpx 20rpx;
            border-radius: 30rpx;
            .area-text {
                font-size: 26rpx;
                color: #333;
                margin: 0 10rpx;
                max-width: 200rpx;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }
        .tab-box {
            display: flex;
            background-color: #f5f5f5;
            border-radius: 30rpx;
            padding: 4rpx;
            .tab-item {
                padding: 10rpx 30rpx;
                font-size: 26rpx;
                color: #666;
                border-radius: 26rpx;
                &.active {
                    background-color: #5db66f;
                    color: #fff;
                    font-weight: bold;
                }
            }
        }
    }

    .list-scroll {
        flex: 1;
        overflow: hidden;
    }

    .list-container {
        padding: 20rpx;
    }

    .enterprise-card {
        background-color: #fff;
        border-radius: 20rpx;
        padding: 24rpx;
        margin-bottom: 24rpx;
        .card-main {
            display: flex;
            .logo {
                width: 140rpx;
                height: 140rpx;
                border-radius: 12rpx;
                background-color: #f8f8f8;
            }
            .info {
                flex: 1;
                margin-left: 20rpx;
                display: flex;
                flex-direction: column;
                .name {
                    font-size: 30rpx;
                    font-weight: bold;
                    color: #333;
                }
                .scope {
                    font-size: 24rpx;
                    color: #999;
                    margin-top: 10rpx;
                }
                .tags {
                    display: flex;
                    margin-top: 12rpx;
                    .tag {
                        font-size: 20rpx;
                        padding: 2rpx 12rpx;
                        background-color: #e6f5e8;
                        color: #5db66f;
                        border-radius: 4rpx;
                        margin-right: 10rpx;
                        &.orange {
                            background-color: #fff7e6;
                            color: #fa8c16;
                        }
                    }
                }
            }
        }
        .card-footer {
            margin-top: 20rpx;
            padding-top: 20rpx;
            border-top: 1rpx solid #f5f5f5;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .addr {
                display: flex;
                align-items: center;
                font-size: 22rpx;
                color: #999;
            }
            .btn {
                padding: 8rpx 24rpx;
                background-color: #5db66f;
                color: #fff;
                font-size: 24rpx;
                border-radius: 26rpx;
            }
        }
    }

    .service-card {
        background-color: #fff;
        border-radius: 20rpx;
        padding: 24rpx;
        margin-bottom: 24rpx;
        .card-main {
            display: flex;
            .thumb {
                width: 160rpx;
                height: 160rpx;
                border-radius: 12rpx;
            }
            .info {
                flex: 1;
                margin-left: 20rpx;
                display: flex;
                flex-direction: column;
                .title {
                    font-size: 30rpx;
                    font-weight: bold;
                    color: #333;
                }
                .desc {
                    font-size: 24rpx;
                    color: #999;
                    margin-top: 10rpx;
                }
                .price-row {
                    margin-top: auto;
                    .price {
                        font-size: 36rpx;
                        color: #ff4d4f;
                        font-weight: bold;
                    }
                    .unit {
                        font-size: 22rpx;
                        color: #999;
                        margin-left: 4rpx;
                    }
                }
            }
        }
        .card-footer {
            margin-top: 20rpx;
            padding-top: 20rpx;
            border-top: 1rpx dashed #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .status {
                font-size: 22rpx;
                color: #5db66f;
                background-color: #e6f5e8;
                padding: 4rpx 16rpx;
                border-radius: 4rpx;
            }
            .btn {
                padding: 10rpx 28rpx;
                background-color: #5db66f;
                color: #fff;
                font-size: 24rpx;
                border-radius: 30rpx;
                &.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); }
    }

    .empty-box {
        padding-top: 100rpx;
    }
</style>
