<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 { useDictStore } from '@/store/modules/dict'
    import { getText } from '@/utils/dict/area'
    import AreaPicker from '@/components/AreaPicker/index.vue'

    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: {
            time: false,
            classify: false,
            address: false,
        },
        options: {
            classify: [],
        },
        form: {
            id: '',
            title: '',
            count: '',
            unit: '',
            deadLine: '',
            priceStart: '',
            priceEnd: '',
            address: '',
            province: '',
            city: '',
            country: '',
            classify: '',
            classifyText: '',
            inputTextArea: '',
            image: '',
            imageObj: null as any,
        },
        rules: [
            { name: 'classify', rule: ['required'], msg: ['请选择采购类别'] },
            { name: 'title', rule: ['required'], msg: ['请输入采购标题'] },
            { name: 'count', rule: ['required'], msg: ['请输入数量'] },
            { name: 'unit', rule: ['required'], msg: ['请输入单位'] },
            { name: 'deadLine', rule: ['required'], msg: ['请选择截至时间'] },
            { name: 'priceStart', rule: ['required'], msg: ['请输入最低价'] },
            { name: 'priceEnd', rule: ['required'], msg: ['请输入最高价'] },
            { name: 'address', 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.purchaseSellDetails({ id }).then(async (res) => {
            pageData.form = res
            
            // 确保字典已加载
            if (!pageData.options.classify.length) {
                await initDict()
            }
            
            // 优先用接口返回的中文名，getText 作为兜底
            const nameParts = [res.cityName, res.countryName].filter(Boolean)
            if (nameParts.length > 0) {
                // @ts-ignore
                pageData.form.areaText = nameParts.join('')
            } else {
                const areaCodes = [res.city, res.country].filter(Boolean).join(',')
                // @ts-ignore
                pageData.form.areaText = getText(areaCodes, '')
            }
            
            if (res.classify && pageData.options.classify.length) {
                const item = pageData.options.classify.find(i => i.value == res.classify)
                pageData.form.classifyText = item ? item.text : ''
            }
            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 handleChangeTime(e) { pageData.form.deadLine = e.result; pageData.show.time = 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.purchaseSellAdd(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/device2.png" mode="aspectFit" />
            </view>

            <fui-form ref="formRef" label-weight="auto">
                <view class="form-group">
                    <view class="group-title">基本信息</view>
                    <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>
                    <fui-input required label="采购标题" placeholder="例如：长期大量采购红富士苹果" v-model="form.title" labelSize="28" label-width="160" size="28" :padding="['16rpx', '0']" />
                </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.priceStart" placeholder="最低价" placeholder-class="ph-style" />
                            <text class="sep">至</text>
                            <input type="number" class="price-input" v-model="form.priceEnd" placeholder="最高价" placeholder-class="ph-style" />
                            <text class="unit-text">元</text>
                        </view>
                    </view>
                    <fui-input required type="number" label="采购数量" placeholder="请输入计划采购数量" v-model="form.count" labelSize="28" label-width="160" size="28" :padding="['16rpx', '0']" />
                    <fui-input required label="计价单位" placeholder="如：斤、箱、吨" v-model="form.unit" 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="截止日期" v-model="form.deadLine" @click="show.time = true" disabled 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="upload-section">
                        <view class="upload-tip"><span class="required-star">*</span> 上传参考图片，帮助供货商更准确报价</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="#fa8c16" 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="#fa8c16" @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 class="status-tag">采购中</view>
            </view>

            <view class="info-card">
                <view class="price-section">
                    <text class="price-label">预算：</text>
                    <text class="currency">¥</text>
                    <text class="price">{{ form.priceStart }} - {{ form.priceEnd }}</text>
                    <text class="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.count }}{{ form.unit }}</text>
                    </view>
                    <view class="grid-item">
                        <text class="grid-label">截止日期</text>
                        <text class="grid-value danger">{{ form.deadLine }}</text>
                    </view>
                </view>
                <view class="info-list">
                    <view class="info-item">
                        <text class="info-label">收货地区</text>
                        <text class="info-value">{{ form.areaText || getText(form.address, ' / ') }}</text>
                    </view>
                    <view class="info-item" v-if="form.inputTextArea">
                        <text class="info-label">具体要求</text>
                        <text class="info-value">{{ form.inputTextArea }}</text>
                    </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-date-picker :show="show.time" type="3" @change="handleChangeTime" @cancel="show.time = 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(250, 140, 22, 0.9) 0%, rgba(255, 187, 150, 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: #fa8c16;
                        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: #fa8c16;
                    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: #fa8c16; }
    }

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

    /* 采购详情样式 */
    .product-detail {
        .detail-banner { width: 750rpx; height: 500rpx; background-color: #fff; position: relative; .banner-img { width: 100%; height: 100%; } .banner-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background-color: #f1f1f1; } .status-tag { position: absolute; right: 30rpx; top: 30rpx; background-color: rgba(93, 182, 111, 0.9); color: #fff; padding: 8rpx 20rpx; border-radius: 30rpx; font-size: 24rpx; } }
        .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; .price-label { font-size: 28rpx; color: #666; } .currency { font-size: 32rpx; color: #ff4d4f; font-weight: bold; } .price { font-size: 48rpx; color: #ff4d4f; font-weight: bold; } .unit { font-size: 26rpx; color: #ff4d4f; 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: #fff2e8; color: #fa8c16; 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 #fa8c16; } .info-grid { display: flex; background-color: #fff7f2; 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; &.danger { color: #ff4d4f; } } } } .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; } } } }
        .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: #fa8c16; 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>
