<script setup lang="ts">
    import { reactive, toRefs, ref } from 'vue'
    import { onLoad, onShow } from '@dcloudio/uni-app'
    import { useUserStore } from '@/store/modules/user'
    import { useGlobSetting } from '/@/hooks/setting'
    import * as ChanxiaoAPI from '@/api/model/chanxiao'
    import * as UserInfoAPI from '@/api/model/userInfo'
    import { getDictData, getText } from '@/utils/dict/area'
    import AreaPicker from '@/components/AreaPicker/index.vue'
    import { useDictStore } from '@/store/modules/dict'

    const dictStore = useDictStore()
    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    const isSave = ref(false)
    const pageText = ref('供应')

    onLoad((option) => {
        if (option.id) {
            isSave.value = false
            getDetails(option.id)
            uni.setNavigationBarTitle({ title: '供应详情' })
            pageText.value = '供应'
        } else {
            isSave.value = true
            getCurrentAddressInfo()
            uni.setNavigationBarTitle({ title: '发布供应需求' })
            pageText.value = '供应'
        }
    })

    onShow(() => {
        initDict()
    })

    const pageData = reactive({
        loading: false,
        show: {
            time1: false,
            time2: false,
            address: false,
            classify: false,
        },
        options: {
            classify: [],
        },
        form: {
            id: '',
            title: '',
            productSpecs: '',
            minPrice: '',
            maxPrice: '',
            unit: '',
            supplyQuantity: '',
            minOrderQuantity: '',
            address: '',
            detailedAddress: '',
            supplyStartDate: '',
            supplyEndDate: '',
            classifyText: '',
            classify: '',
            province: '',
            city: '',
            country: '',
            image: '',
            imageObj: null as any,
        },
        rules: [
            { name: 'classify', rule: ['required'], msg: ['请选择分类'] },
            { name: 'title', rule: ['required'], msg: [`请输入标题`] },
            { name: 'minPrice', rule: ['required'], msg: ['请输入最低价'] },
            { name: 'maxPrice', rule: ['required'], msg: ['请输入最高价'] },
            { name: 'unit', rule: ['required'], msg: ['请输入单位'] },
            { name: 'supplyQuantity', rule: ['required'], msg: [`请输入数量`] },
            { name: 'minOrderQuantity', rule: ['required'], msg: ['请输入最小起订量'] },
            { name: 'address', rule: ['required'], msg: ['请选择区域'] },
            { name: 'detailedAddress', rule: ['required'], msg: ['请输入详细地址'] },
            { name: 'image', rule: ['required'], msg: ['请上传图片'] },
        ],
        agree: true
    })

    const { show, options, form } = toRefs(pageData)

    async function initDict() {
        pageData.options.classify = [
            { value: 1, text: '蔬菜' },
            { value: 2, text: '水果' },
            { value: 3, text: '粮食' },
            { value: 4, text: '畜牧' },
            { value: 0, text: '其他' },
        ]
        
        // 如果有已选分类，需要回显文字
        if (pageData.form.classify && pageData.options.classify.length) {
            const item = pageData.options.classify.find(i => i.value == pageData.form.classify)
            if (item) pageData.form.classifyText = item.text
        }
    }

    function handleAreaConfirm(e) {
        pageData.form.address = e.fullCode
        pageData.form.province = e.text[0]
        pageData.form.city = e.text[1]
        pageData.form.country = e.text[2]
        // @ts-ignore
        pageData.form.areaText = e.fullText
    }

    function getCurrentAddressInfo() {
        const loc = uni.getStorageSync('location')
        if (!loc) return
        UserInfoAPI.location({ lon: loc.lon, lat: loc.lat }).then((res) => {
            pageData.form.province = res.province
            pageData.form.city = res.city
            pageData.form.country = res.country
            pageData.form.address = `${res.province},${res.city},${res.country}`
            // @ts-ignore
            const areaCodes = [res.province, res.city, res.country].filter(Boolean).join(',')
            pageData.form.areaText = getText(areaCodes, ' / ')
        })
    }

    function getDetails(id) {
        pageData.loading = true
        ChanxiaoAPI.supplyDetails({ id }).then(async (res) => {
            pageData.form = res
            
            // 确保字典已加载
            if (!pageData.options.classify.length) {
                await initDict()
            }
            
            // 格式化地区显示
            const areaCodes = [res.province, res.city, res.country].filter(Boolean).join(',')
            // @ts-ignore
            pageData.form.areaText = getText(areaCodes, ' / ')
            
            if (res.classify) {
                const item = pageData.options.classify.find(i => i.value == res.classify)
                pageData.form.classifyText = item ? item.text : ''
            }
            if (pageData.form.detailedAddress) {
                const parts = pageData.form.detailedAddress.split('||')
                if (parts.length > 1) pageData.form.detailedAddress = parts[1]
            }
            pageData.form.imageObj = res.image && parseUrlInfo(res.image)
        }).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.supplyStartDate = e.result; pageData.show.time1 = false; }
    function handleChangeTime2(e) { pageData.form.supplyEndDate = e.result; pageData.show.time2 = false; }
    function handleChangeClassify(e) { pageData.form.classify = e.value; pageData.form.classifyText = e.text; pageData.show.classify = 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.image = data.message
                }
            }
        })
    }
    const formRef = ref()
    function submit() {
        if (!pageData.agree) {
            toastRef.value.show({ text: '请先同意发布协议' })
            return
        }
        formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                ChanxiaoAPI.supplyAdd(pageData.form).then(() => {
                    toastRef.value.show({ type: 'success', text: '发布成功' })
                    setTimeout(() => uni.navigateBack(), 1500)
                })
            }
        })
    }
    function handleContact() {
        uni.makePhoneCall({ phoneNumber: '10086' })
    }
</script>

<template>
    <view class="page">
        <!-- 发布/编辑模式 -->
        <view v-if="isSave" class="form-container">
            <view class="header-card">
                <image class="header-bg" src="/static/images/login/farm_base_bg.png" mode="aspectFill" />
                <view class="header-overlay"></view>
                
                <view class="header-content">
                    <view class="title">发布供应需求</view>
                    <view class="subtitle">让精准买家更快速地找到您的优质货源</view>

                    <view class="stepper-box">
                        <view class="step-item active">
                            <view class="step-num">1</view>
                            <view class="step-text">提交信息</view>
                        </view>
                        <view class="step-line"></view>
                        <view class="step-item">
                            <view class="step-num">2</view>
                            <view class="step-text">后台审核</view>
                        </view>
                        <view class="step-line"></view>
                        <view class="step-item">
                            <view class="step-num">3</view>
                            <view class="step-text">完成</view>
                        </view>
                    </view>
                </view>
                
                <!-- 装饰图标 -->
                <image class="deco-icon" src="/static/images/nongchang/device1.png" mode="aspectFit" />
            </view>

            <fui-form ref="formRef" label-weight="auto">
                <view class="form-group">
                    <view class="group-title">基本信息</view>
                    <fui-input required label="供应标题" placeholder="例如：优质红富士苹果" v-model="form.title" labelSize="28" label-width="160" size="28" :padding="['16rpx', '0']" />
                    <fui-input label="规格说明" placeholder="例如：一级果，直径80mm以上" v-model="form.productSpecs" labelSize="28" label-width="160" size="28" :padding="['16rpx', '0']" />
                    <fui-input disabled required label="所属分类" v-model="form.classifyText" @click="show.classify = true" placeholder="请选择分类" labelSize="28" label-width="160" size="28" :padding="['16rpx', '0']">
                        <template #right>
                            <fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon>
                        </template>
                    </fui-input>
                </view>

                <view class="form-group">
                    <view class="group-title">价格与库存</view>
                    <view class="form-item required">
                        <text class="label">价格区间</text>
                        <view class="price-range-box">
                            <input type="number" class="price-input" v-model="form.minPrice" placeholder="最低价" placeholder-class="ph-style" />
                            <text class="sep">至</text>
                            <input type="number" class="price-input" v-model="form.maxPrice" placeholder="最高价" placeholder-class="ph-style" />
                            <text class="unit-text">元</text>
                        </view>
                    </view>
                    <fui-input required label="计价单位" placeholder="如：斤、箱、吨" v-model="form.unit" labelSize="28" label-width="160" size="28" :padding="['16rpx', '0']" />
                    <fui-input required type="number" label="供应总量" placeholder="输入可供总量" v-model="form.supplyQuantity" labelSize="28" label-width="160" size="28" :padding="['16rpx', '0']" />
                    <fui-input required type="number" label="起订量" placeholder="输入最低起订数量" v-model="form.minOrderQuantity" labelSize="28" label-width="160" size="28" :padding="['16rpx', '0']" />
                </view>

                <view class="form-group">
                    <view class="group-title">发货信息</view>
                    <fui-input disabled required label="所在地区" v-model="form.areaText" @click="show.address = true" placeholder="请选择发货地" labelSize="28" label-width="160" size="28" :padding="['16rpx', '0']">
                        <template #right>
                            <fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon>
                        </template>
                    </fui-input>
                    <fui-input required label="详细地址" placeholder="街道、门牌号等" v-model="form.detailedAddress" labelSize="28" label-width="160" size="28" :padding="['16rpx', '0']" />
                </view>

                <view class="form-group">
                    <view class="group-title">图片展示</view>
                    <view class="upload-section">
                        <view class="upload-tip"><span class="required-star">*</span> 上传实拍图片，成交率提升3倍</view>
                        <uni-file-picker :value="form.imageObj" limit="1" @select="handleUpload" @delete="form.image = ''" />
                    </view>
                </view>

                <view class="agreement-row">
                    <checkbox-group @change="pageData.agree = !pageData.agree">
                        <label class="checkbox-label">
                            <checkbox :checked="pageData.agree" color="#5db66f" style="transform:scale(0.7)" />
                            <text class="agreement-text">我已阅读并同意 <text class="link">《湘农数智农服发布协议》</text></text>
                        </label>
                    </checkbox-group>
                </view>

                <view class="submit-btn-box">
                    <fui-button text="立即发布" bold radius="100rpx" background="#5db66f" @click="submit" />
                </view>
            </fui-form>
        </view>

        <!-- 商品详情模式 -->
        <view v-else class="product-detail">
            <view class="detail-banner">
                <image v-if="form.image" :src="form.image" mode="aspectFill" class="banner-img" />
                <view v-else class="banner-placeholder"><fui-icon name="picture" :size="100" color="#ddd"></fui-icon></view>
            </view>

            <view class="info-card">
                <view class="price-section">
                    <text class="currency">¥</text>
                    <text class="price">{{ form.minPrice }} - {{ form.maxPrice }}</text>
                    <text class="unit">/ {{ form.unit }}</text>
                </view>
                <text class="product-title">{{ form.title }}</text>
                <view class="tags-row" v-if="form.classifyText"><view class="tag">{{ form.classifyText }}</view></view>
            </view>

            <view class="detail-section">
                <view class="section-title">供应信息</view>
                <view class="info-grid">
                    <view class="grid-item">
                        <text class="grid-label">供应总量</text>
                        <text class="grid-value">{{ form.supplyQuantity }}{{ form.unit }}</text>
                    </view>
                    <view class="grid-item">
                        <text class="grid-label">起订量</text>
                        <text class="grid-value">{{ form.minOrderQuantity }}{{ form.unit }}</text>
                    </view>
                </view>
                <view class="info-list">
                    <view class="info-item" v-if="form.supplyStartDate">
                        <text class="info-label">供应周期</text>
                        <text class="info-value">{{ form.supplyStartDate }} 至 {{ form.supplyEndDate }}</text>
                    </view>
                    <view class="info-item" v-if="form.productSpecs">
                        <text class="info-label">规格说明</text>
                        <text class="info-value">{{ form.productSpecs }}</text>
                    </view>
                </view>
            </view>

            <view class="detail-section">
                <view class="section-title">产地及详细地址</view>
                <view class="location-box">
                    <view class="location-top">
                        <fui-icon name="location" :size="28" color="#5db66f"></fui-icon>
                        <text class="address-main">{{ form.areaText || form.address }}</text>
                    </view>
                    <view class="address-detail" v-if="form.detailedAddress">{{ form.detailedAddress }}</view>
                </view>
            </view>

            <view class="bottom-bar">
                <view class="action-btns">
                    <view class="contact-btn" @click="handleContact">立即沟通</view>
                </view>
            </view>
            <view style="height: 140rpx"></view>
        </view>

        <AreaPicker v-model:show="show.address" :layer="3" @confirm="handleAreaConfirm" />
        <fui-picker :show="show.classify" :options="options.classify" @change="handleChangeClassify" @cancel="show.classify = false" />
        <fui-toast ref="toastRef" />
    </view>
</template>

<style lang="scss" scoped>
    .page { background-color: #f7f9fb; min-height: 100vh; font-family: 'DingTalk Sans', sans-serif; }
    
    .form-container { 
        padding-bottom: 40rpx; 
        
        .header-card {
            position: relative;
            height: 320rpx;
            overflow: hidden;
            display: flex;
            align-items: center;
            
            .header-bg {
                position: absolute;
                width: 100%;
                height: 100%;
                z-index: 1;
            }
            
            .header-overlay {
                position: absolute;
                width: 100%;
                height: 100%;
                background: linear-gradient(135deg, rgba(93, 182, 111, 0.9) 0%, rgba(76, 175, 80, 0.8) 100%);
                z-index: 2;
            }
            
            .header-content {
                position: relative;
                z-index: 3;
                width: 100%;
                padding: 0 40rpx;
                margin-top: -20rpx;
            }
            
            .title { font-size: 38rpx; font-weight: bold; color: #fff; margin-bottom: 6rpx; text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1); }
            .subtitle { font-size: 24rpx; color: rgba(255, 255, 255, 0.9); }
            
            .deco-icon {
                position: absolute;
                right: -20rpx;
                bottom: 20rpx;
                width: 200rpx;
                height: 200rpx;
                opacity: 0.15;
                z-index: 2;
                transform: rotate(-15deg);
            }
        }

        .stepper-box {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 30rpx;
            padding: 0 20rpx;

            .step-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                opacity: 0.7;
                position: relative;
                z-index: 2;
                
                &.active {
                    opacity: 1;
                    .step-num {
                        background: #fff;
                        color: #5db66f;
                        border-color: #fff;
                        box-shadow: 0 4rpx 10rpx rgba(0,0,0,0.1);
                    }
                    .step-text { font-weight: bold; }
                }
                
                .step-num {
                    width: 36rpx;
                    height: 36rpx;
                    border: 2rpx solid rgba(255, 255, 255, 0.8);
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 22rpx;
                    font-weight: bold;
                    margin-bottom: 8rpx;
                    color: #fff;
                    transition: all 0.3s;
                }
                
                .step-text {
                    font-size: 20rpx;
                    color: #fff;
                }
            }
            
            .step-line {
                flex: 1;
                height: 2rpx;
                background: rgba(255, 255, 255, 0.4);
                margin: 0 15rpx;
                margin-top: -30rpx;
            }
        }

        .form-group {
            background: #fff;
            margin: 20rpx 24rpx 0;
            border-radius: 20rpx;
            padding: 24rpx 28rpx;
            box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.02);

            .group-title {
                font-size: 28rpx;
                font-weight: bold;
                color: #333;
                margin-bottom: 20rpx;
                display: flex;
                align-items: center;
                
                &::before {
                    content: '';
                    width: 6rpx;
                    height: 28rpx;
                    background: #5db66f;
                    border-radius: 4rpx;
                    margin-right: 12rpx;
                }
            }
        }
    }

    .form-item {
        padding: 20rpx 0;
        display: flex;
        align-items: center;
        border-bottom: 1rpx solid #f8f8f8;
        
        .label { 
            font-size: 28rpx; 
            color: #333; 
            width: 160rpx; 
        }
    }

    .required-star { color: #ff4d4f; margin-right: 4rpx; }

    .price-range-box {
        display: flex;
        align-items: center;
        flex: 1;
        
        .price-input {
            flex: 1;
            height: 72rpx;
            background: #f5f7f9;
            border-radius: 12rpx;
            padding: 0 20rpx;
            font-size: 28rpx;
            text-align: center;
        }
        
        .sep { margin: 0 16rpx; color: #999; font-size: 24rpx; }
        .unit-text { margin-left: 12rpx; color: #666; font-size: 28rpx; }
    }

    .upload-section {
        .upload-tip { font-size: 24rpx; color: #666; margin-bottom: 24rpx; }
    }

    .agreement-row {
        padding: 20rpx 40rpx;
        .agreement-text { font-size: 24rpx; color: #999; }
        .link { color: #5db66f; }
    }

    .submit-btn-box {
        padding: 40rpx;
    }

    /* 商品详情模式样式 */
    .product-detail {
        .detail-banner { width: 750rpx; height: 600rpx; background-color: #fff; .banner-img { width: 100%; height: 100%; } .banner-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background-color: #f1f1f1; } }
        .info-card { background-color: #fff; margin: -40rpx 24rpx 20rpx; padding: 32rpx; border-radius: 24rpx; box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05); position: relative; .price-section { display: flex; align-items: baseline; margin-bottom: 16rpx; .currency { font-size: 32rpx; color: #ff4d4f; font-weight: bold; } .price { font-size: 48rpx; color: #ff4d4f; font-weight: bold; } .unit { font-size: 24rpx; color: #999; margin-left: 10rpx; } } .product-title { font-size: 36rpx; color: #333; font-weight: bold; line-height: 1.4; display: block; } .tags-row { margin-top: 20rpx; .tag { padding: 4rpx 16rpx; background-color: #e6f5e8; color: #5db66f; font-size: 22rpx; border-radius: 6rpx; } } }
        .detail-section { background-color: #fff; margin: 0 24rpx 20rpx; padding: 32rpx; border-radius: 24rpx; .section-title { font-size: 30rpx; color: #333; font-weight: bold; margin-bottom: 24rpx; padding-left: 16rpx; border-left: 8rpx solid #5db66f; } .info-grid { display: flex; background-color: #f9f9f9; padding: 20rpx; border-radius: 12rpx; margin-bottom: 24rpx; .grid-item { flex: 1; display: flex; flex-direction: column; align-items: center; .grid-label { font-size: 22rpx; color: #999; margin-bottom: 8rpx; } .grid-value { font-size: 28rpx; color: #333; font-weight: bold; } } } .info-list { .info-item { display: flex; padding: 20rpx 0; border-bottom: 1rpx solid #f5f5f5; &:last-child { border-bottom: none; } .info-label { width: 160rpx; font-size: 26rpx; color: #999; } .info-value { flex: 1; font-size: 26rpx; color: #333; } } } .location-box { .location-top { display: flex; align-items: center; .address-main { font-size: 28rpx; color: #333; font-weight: bold; margin-left: 12rpx; } } .address-detail { font-size: 26rpx; color: #666; margin-top: 16rpx; padding-left: 40rpx; } } }
        .bottom-bar { position: fixed; bottom: 0; left: 0; right: 0; height: 110rpx; background-color: #fff; padding: 0 30rpx; display: flex; align-items: center; box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05); z-index: 100; .action-btns { flex: 1; .contact-btn { height: 80rpx; background-color: #5db66f; color: #fff; display: flex; align-items: center; justify-content: center; border-radius: 40rpx; font-size: 28rpx; font-weight: bold; } } }
    }

    :deep(.fui-input__label) { font-family: 'DingTalk Sans' !important; font-size: 28rpx !important; }
    :deep(.fui-input__content) { font-size: 28rpx !important; }
    :deep(.fui-input__placeholder) { font-size: 26rpx !important; }
    .ph-style { font-size: 26rpx !important; color: #ccc; }
</style>
