<script setup lang="ts">
    import { reactive, ref, toRefs } from 'vue'
    import { onLoad } from '@dcloudio/uni-app'
    import { useUserStore } from '@/store/modules/user'
    import { useGlobSetting } from '/@/hooks/setting'
    import * as LinghuoyonggongAPI from '@/api/model/linghuoyonggong'
    import * as nongjifuwu from '@/api/model/nongjifuwu'
    import { getText } from '@/utils/dict/area'
    import AreaPicker from '@/components/AreaPicker/index.vue'
    import ApplyDialog from '@/pages/nongjifuwu/components/apply-dialog.vue'

    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    onLoad((option) => {
        pageData.form.type = option.type
        if (option.id) {
            pageData.title = '干农活详情'
            getDetails(option.id)
        } else {
            pageData.title = '新增农活作业'
        }
        uni.setNavigationBarTitle({ title: pageData.title })
    })

    const pageData = reactive({
        title: '农活表单',
        loading: false,
        show: {
            time1: false,
            time2: false,
            address: false,
        },
        optionsValText: '',
        form: {
            id: '',
            name: '',
            type: '',
            scope: '',
            address: '',
            phone: '',
            demand: '',
            startTime: '',
            endTime: '',
            picture: '',
            pictureObj: null,
        },
        rules: [
            { name: 'name', rule: ['required'], msg: ['请填写服务名称'] },
            { name: 'scope', rule: ['required'], msg: ['请选择服务范围'] },
            { name: 'address', rule: ['required'], msg: ['请填写详细地址'] },
            { name: 'phone', rule: ['required', 'isMobile'], msg: ['请填写联系方式', '手机号格式不正确'] },
            { name: 'demand', rule: ['required'], msg: ['请填写作业需求'] },
            { name: 'startTime', rule: ['required'], msg: ['请选择开始时间'] },
            { name: 'endTime', rule: ['required'], msg: ['请选择结束时间'] },
        ],
    })

    const { show, form } = toRefs(pageData)

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

    function getDetails(id) {
        pageData.loading = true
        nongjifuwu.farmMachineDetails({ id }).then((res) => {
            pageData.form = res
            pageData.form.pictureObj = res.picture && parseUrlInfo(res.picture)
            // 优先用接口返回的中文名拼接，getText 作为兜底
            const nameParts = [res.cityName, res.districtName].filter(Boolean)
            if (nameParts.length > 0) {
                pageData.optionsValText = nameParts.join('')
            } else if (res.scope) {
                pageData.optionsValText = getText(res.scope, '')
            }
        }).finally(() => pageData.loading = false)
    }

    function parseUrlInfo(url) {
        const fileName = url.split('/').pop()
        return { name: fileName, extname: fileName.split('.').pop(), url }
    }

    function handleChangeTime1(e) { pageData.form.startTime = e.result; pageData.show.time1 = false; }
    function handleChangeTime2(e) { pageData.form.endTime = e.result; pageData.show.time2 = false; }

    const toastRef = ref()
    const uploadRef = ref()
    function handleUpload(file) {
        uni.uploadFile({
            url: `${globSetting.apiUrl + globSetting.urlPrefix}/sys/common/upload`,
            filePath: file.tempFiles[0].path,
            name: 'file',
            formData: { biz: 'temp' },
            header: { 'X-Access-Token': userStore.getToken },
            success: (res) => {
                const data = JSON.parse(res.data)
                if (data.code === 200 || data.code === 0) {
                    toastRef.value.show({ type: 'success', text: '上传成功' })
                    pageData.form.picture = data.message
                }
            }
        })
    }
    const formRef = ref()
    function submit() {
        formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                nongjifuwu.farmMachineAddFarm(pageData.form).then(() => {
                    toastRef.value.show({ type: 'success', text: '发布成功' })
                    setTimeout(() => uni.navigateBack(), 1500)
                })
            }
        })
    }

    function getCurrentDate() {
        const d = new Date()
        return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
    }

    const applyDialogRef = ref()
    function handleApply() {
        applyDialogRef.value.open({
            id: pageData.form.id,
            serviceType: pageData.form.type,
        })
    }
</script>

<template>
    <view class="page">
        <!-- 发布模式 -->
        <view v-if="!form.id" class="formBox">
            <fui-form ref="formRef" label-weight="auto" top="60">
                <view class="mt20">
                    <fui-input required label="服务名称" v-model="form.name" labelSize="28" label-width="180" />
                    <view class="form-item required flex align-center" style="padding: 20rpx 10rpx">
                        <text class="label">服务范围</text>
                        <view class="time-input" @click="show.address = true">
                            <text class="select-text" :class="{ placeholder: !pageData.form.scope }">{{ pageData.optionsValText || '请选择' }}</text>
                        </view>
                    </view>
                    <fui-input required label="详细地址" v-model="form.address" labelSize="28" label-width="180" />
                    <fui-input required type="number" label="联系方式" v-model="form.phone" labelSize="28" label-width="180" />
                </view>
                <view class="mt20">
                    <fui-textarea required label="作业需求" v-model="form.demand" labelSize="28" label-width="180" />
                    <view class="form-item flex align-center" style="padding: 30rpx 10rpx">
                        <text class="label">作业时间</text>
                        <view class="time-range">
                            <view class="time-input" @click="show.time1 = true">
                                <text class="time-text" :class="{ placeholder: !form.startTime }">{{ form.startTime || '开始' }}</text>
                            </view>
                            <text class="sep">至</text>
                            <view class="time-input" @click="show.time2 = true">
                                <text class="time-text" :class="{ placeholder: !form.endTime }">{{ form.endTime || '结束' }}</text>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="bg-white mt20" style="padding: 30rpx">
                    <view class="mb-1" style="font-size: 28rpx"><span style="color: red">*&nbsp;</span>图片</view>
                    <uni-file-picker :value="form.pictureObj" limit="1" @select="handleUpload" @delete="form.picture = null" />
                </view>
                <view class="fui-btn__box">
                    <fui-button text="立即发布" bold radius="100rpx" @click="submit" />
                </view>
            </fui-form>
        </view>

        <!-- 详情模式 -->
        <view v-else class="detail-page">
            <!-- 顶部封面图区域 -->
            <view class="detail-hero">
                <image
                    v-if="form.picture"
                    :src="form.picture"
                    mode="aspectFill"
                    class="hero-img"
                />
                <view v-else class="hero-placeholder">
                    <fui-icon name="picture" :size="120" color="rgba(255,255,255,0.4)"></fui-icon>
                    <text class="hero-placeholder-text">暂无图片</text>
                </view>
                <!-- 顶部渐变遮罩 -->
                <view class="hero-overlay"></view>
                <!-- 状态标签 -->
                <view class="hero-badge">
                    <view class="badge-dot"></view>
                    <text class="badge-text">招募中</text>
                </view>
            </view>

            <!-- 主信息卡片 -->
            <view class="main-card">
                <text class="service-title">{{ form.name }}</text>

                <!-- 价格/关键信息行 -->
                <view class="key-info-row">
                    <view class="key-tag">
                        <fui-icon name="time" :size="26" color="#5db66f"></fui-icon>
                        <text class="key-tag-text">{{ form.startTime || '--' }} 至 {{ form.endTime || '--' }}</text>
                    </view>
                </view>
            </view>

            <!-- 详细信息 section -->
            <view class="info-section">
                <view class="section-header">
                    <view class="section-bar"></view>
                    <text class="section-title">作业信息</text>
                </view>

                <view class="info-grid">
                    <view class="info-row">
                        <view class="info-icon-wrap">
                            <fui-icon name="location" :size="32" color="#5db66f"></fui-icon>
                        </view>
                        <view class="info-content">
                            <text class="info-label">服务范围</text>
                            <text class="info-value">{{ pageData.optionsValText || form.scope || '暂未填写' }}</text>
                        </view>
                    </view>

                    <view class="info-divider"></view>

                    <view class="info-row">
                        <view class="info-icon-wrap">
                            <fui-icon name="map" :size="32" color="#5db66f"></fui-icon>
                        </view>
                        <view class="info-content">
                            <text class="info-label">详细地址</text>
                            <text class="info-value">{{ form.address || '暂未填写' }}</text>
                        </view>
                    </view>

                    <view class="info-divider"></view>

                    <view class="info-row">
                        <view class="info-icon-wrap">
                            <fui-icon name="mobile" :size="32" color="#5db66f"></fui-icon>
                        </view>
                        <view class="info-content">
                            <text class="info-label">联系方式</text>
                            <text class="info-value">{{ form.phone || '暂未填写' }}</text>
                        </view>
                    </view>

                    <view v-if="form.startTime || form.endTime" class="info-divider"></view>

                    <view v-if="form.startTime || form.endTime" class="info-row">
                        <view class="info-icon-wrap">
                            <fui-icon name="time" :size="32" color="#5db66f"></fui-icon>
                        </view>
                        <view class="info-content">
                            <text class="info-label">作业时间</text>
                            <text class="info-value">{{ form.startTime }} 至 {{ form.endTime }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 作业需求 section -->
            <view class="info-section" v-if="form.demand">
                <view class="section-header">
                    <view class="section-bar"></view>
                    <text class="section-title">作业需求</text>
                </view>
                <view class="demand-box">
                    <text class="demand-text">{{ form.demand }}</text>
                </view>
            </view>

            <!-- 底部安全高度 -->
            <view style="height: 180rpx;"></view>

            <!-- 固定底部栏 -->
            <view class="detail-footer">
                <view class="footer-hint">
                    <text class="hint-title">有意接单？立即报名</text>
                    <text class="hint-sub">平台将为您推送给发布方</text>
                </view>
                <view class="footer-apply-btn" @tap="handleApply">
                    <text class="apply-btn-text">立即报名</text>
                </view>
            </view>
        </view>

        <AreaPicker v-model:show="show.address" :layer="3" @confirm="handleAreaConfirm" />
        <fui-date-picker :show="show.time1" type="3" @change="handleChangeTime1" @cancel="show.time1 = false" :min-date="getCurrentDate()" />
        <fui-date-picker :show="show.time2" type="3" @change="handleChangeTime2" @cancel="show.time2 = false" :min-date="getCurrentDate()" />
        <fui-toast ref="toastRef" />
        <fui-loading isFixed v-if="pageData.loading" />
        <ApplyDialog ref="applyDialogRef" />
    </view>
</template>

<style lang="scss" scoped>
    .page {
        background-color: #f8fafc;
        min-height: 100vh;
        font-family: 'DingTalk Sans', sans-serif;
    }

    /* ===== 发布模式 ===== */
    .formBox {
        padding: 24rpx;
        .mt20 {
            background: #fff;
            border-radius: 20rpx;
            padding: 10rpx 24rpx;
            margin-bottom: 24rpx;
        }
    }
    .form-item {
        padding: 30rpx 0;
        display: flex;
        align-items: center;
        border-bottom: 1rpx solid #f8f8f8;
        .label { font-size: 28rpx; color: #333; width: 180rpx; }
    }
    .time-range {
        display: flex;
        align-items: center;
        flex: 1;
        margin-left: 20rpx;
        .time-input { flex: 1; text-align: center; }
        .sep { margin: 0 10rpx; color: #ccc; }
    }
    .select-text { font-size: 28rpx; &.placeholder { color: #ccc; } }
    :deep(.fui-input__label) { font-family: 'DingTalk Sans' !important; }

    /* ===== 详情模式 ===== */
    .detail-page {
        background-color: #f8fafc;
    }

    .detail-hero {
        position: relative;
        width: 100%;
        height: 520rpx;
        background: linear-gradient(135deg, #3a944c 0%, #5db66f 100%);
        overflow: hidden;

        .hero-img {
            width: 100%;
            height: 100%;
            display: block;
        }

        .hero-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            .hero-placeholder-text {
                font-size: 26rpx;
                color: rgba(255,255,255,0.5);
                margin-top: 20rpx;
            }
        }

        .hero-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 240rpx;
            background: linear-gradient(to top, rgba(0,0,0,0.45) 0%, transparent 100%);
        }

        .hero-badge {
            position: absolute;
            top: 30rpx;
            right: 30rpx;
            display: flex;
            align-items: center;
            background-color: rgba(255,255,255,0.18);
            backdrop-filter: blur(8px);
            border: 1rpx solid rgba(255,255,255,0.3);
            padding: 10rpx 22rpx;
            border-radius: 40rpx;

            .badge-dot {
                width: 14rpx;
                height: 14rpx;
                border-radius: 50%;
                background-color: #52c41a;
                margin-right: 10rpx;
                box-shadow: 0 0 0 4rpx rgba(82,196,26,0.3);
            }
            .badge-text {
                font-size: 24rpx;
                color: #fff;
                font-weight: 500;
            }
        }
    }

    .main-card {
        background-color: #fff;
        margin: -40rpx 24rpx 20rpx;
        border-radius: 28rpx;
        padding: 36rpx 32rpx 28rpx;
        box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.08);
        position: relative;
        z-index: 10;

        .service-title {
            font-size: 40rpx;
            font-weight: bold;
            color: #1a1a1a;
            line-height: 1.35;
            display: block;
            margin-bottom: 24rpx;
            letter-spacing: 1rpx;
        }

        .key-info-row {
            display: flex;
            flex-wrap: wrap;
            gap: 16rpx;

            .key-tag {
                display: flex;
                align-items: center;
                background-color: #f0faf2;
                border-radius: 10rpx;
                padding: 10rpx 20rpx;

                .key-tag-text {
                    font-size: 26rpx;
                    color: #3a944c;
                    margin-left: 8rpx;
                    font-weight: 500;
                }
            }
        }
    }

    .info-section {
        background-color: #fff;
        margin: 0 24rpx 20rpx;
        border-radius: 24rpx;
        padding: 32rpx;
        box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.04);

        .section-header {
            display: flex;
            align-items: center;
            margin-bottom: 28rpx;

            .section-bar {
                width: 8rpx;
                height: 36rpx;
                background: linear-gradient(to bottom, #5db66f, #3a944c);
                border-radius: 4rpx;
                margin-right: 16rpx;
            }

            .section-title {
                font-size: 32rpx;
                font-weight: bold;
                color: #1a1a1a;
            }
        }

        .info-grid {
            .info-row {
                display: flex;
                align-items: flex-start;
                padding: 4rpx 0;

                .info-icon-wrap {
                    width: 56rpx;
                    height: 56rpx;
                    background-color: #f0faf2;
                    border-radius: 14rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    flex-shrink: 0;
                }

                .info-content {
                    flex: 1;
                    margin-left: 20rpx;
                    padding: 4rpx 0;

                    .info-label {
                        font-size: 24rpx;
                        color: #94a3b8;
                        display: block;
                        margin-bottom: 6rpx;
                    }
                    .info-value {
                        font-size: 30rpx;
                        color: #1e293b;
                        line-height: 1.4;
                        font-weight: 500;
                    }
                }
            }

            .info-divider {
                height: 1rpx;
                background-color: #f1f5f9;
                margin: 24rpx 0;
            }
        }

        .demand-box {
            background-color: #f8fafc;
            border-radius: 16rpx;
            padding: 28rpx;
            border-left: 6rpx solid #5db66f;

            .demand-text {
                font-size: 28rpx;
                color: #475569;
                line-height: 1.7;
            }
        }
    }

    /* ===== 底部操作栏 ===== */
    .detail-footer {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: rgba(255,255,255,0.97);
        backdrop-filter: blur(10px);
        padding: 20rpx 32rpx calc(20rpx + env(safe-area-inset-bottom));
        box-shadow: 0 -8rpx 32rpx rgba(0,0,0,0.06);
        z-index: 100;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .footer-hint {
            display: flex;
            flex-direction: column;

            .hint-title {
                font-size: 30rpx;
                font-weight: bold;
                color: #1e293b;
            }
            .hint-sub {
                font-size: 22rpx;
                color: #94a3b8;
                margin-top: 4rpx;
            }
        }

        .footer-apply-btn {
            background: linear-gradient(135deg, #5db66f 0%, #3a944c 100%);
            height: 88rpx;
            padding: 0 52rpx;
            border-radius: 44rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 8rpx 24rpx rgba(93,182,111,0.35);

            &:active {
                opacity: 0.9;
                transform: scale(0.97);
            }

            .apply-btn-text {
                font-size: 30rpx;
                color: #fff;
                font-weight: bold;
                letter-spacing: 2rpx;
            }
        }
    }
</style>
