<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: null,
            imageObj: null,
        },
        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: ['请上传图片'] },
        ],
    })

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

    async function initDict() {
        pageData.options.classify = dictStore.getDictList.classify.map((item) => {
            return { value: item.value, text: 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]
    }

    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}`
        })
    }

    function getDetails(id) {
        pageData.loading = true
        ChanxiaoAPI.supplyDetails({ id }).then((res) => {
            pageData.form = res
            // 格式化地区显示
            pageData.form.areaText = `${res.province || ''}/${res.city || ''}/${res.country || ''}`.replace(/\/+$/, '')
            
            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.show({ type: 'success', text: '上传成功' })
                    pageData.form.image = data.message
                }
            }
        })
    }
    const formRef = ref()
    function submit() {
        formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                ChanxiaoAPI.supplyAdd(pageData.form).then(() => {
                    toastRef.show({ type: 'success', text: '发布成功' })
                    setTimeout(() => uni.navigateBack(), 1500)
                })
            }
        })
    }
    function handleContact() {
        uni.makePhoneCall({ phoneNumber: '10086' })
    }
</script>

<template>
    <view class="page">
        <!-- 发布/编辑模式 -->
        <view v-if="isSave" class="formBox">
            <fui-form ref="formRef" label-weight="auto" top="60">
                <view class="mt20">
                    <fui-input required label="标题" placeholder="请输入标题" v-model="form.title" labelSize="28" label-width="180" />
                    <fui-input label="规格说明" placeholder="请输入规格说明" v-model="form.productSpecs" labelSize="28" label-width="180" />
                </view>
                <view class="mt20">
                    <view class="form-item required">
                        <text class="label">价格区间</text>
                        <view class="price-range">
                            <input type="number" class="price-input" v-model="form.minPrice" placeholder="最低价" />
                            <text class="sep">-</text>
                            <input type="number" class="price-input" v-model="form.maxPrice" placeholder="最高价" />
                        </view>
                    </view>
                    <fui-input required label="单位" placeholder="请输入" v-model="form.unit" labelSize="28" label-width="180" />
                    <fui-input required type="number" label="供应数量" v-model="form.supplyQuantity" labelSize="28" label-width="180" />
                    <fui-input required type="number" label="起订量" v-model="form.minOrderQuantity" labelSize="28" label-width="180" />
                </view>
                <view class="mt20">
                    <fui-input disabled required label="所在地区" v-model="form.address" @click="show.address = true" labelSize="28" label-width="180" />
                    <fui-input required label="详细地址" v-model="form.detailedAddress" labelSize="28" label-width="180" />
                    <fui-input disabled required label="分类" v-model="form.classifyText" @click="show.classify = true" labelSize="28" label-width="180" />
                </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.imageObj" limit="1" @select="handleUpload" @delete="form.image = null" />
                </view>
                <view class="fui-btn__box">
                    <fui-button text="立即发布" bold radius="100rpx" @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-date-picker :show="show.time1" type="3" @change="handleChangeTime1" @cancel="show.time1 = false" />
        <fui-date-picker :show="show.time2" type="3" @change="handleChangeTime2" @cancel="show.time2 = false" />
        <fui-toast ref="toastRef" />
    </view>
</template>

<style lang="scss" scoped>
    .page { background-color: #f7f8fa; min-height: 100vh; font-family: 'DingTalk Sans', sans-serif; }
    .formBox { padding: 24rpx; .mt20 { background: #fff; border-radius: 20rpx; padding: 10rpx 24rpx; margin-bottom: 24rpx; } }
    .price-range { display: flex; align-items: center; flex: 1; margin-left: 20rpx; .price-input { flex: 1; text-align: center; font-size: 28rpx; } .sep { margin: 0 10rpx; color: #ccc; } }
    .form-item { padding: 30rpx 0; display: flex; align-items: center; border-bottom: 1rpx solid #f8f8f8; .label { font-size: 28rpx; color: #333; width: 180rpx; .red { color: #ff4d4f; } } }
    
    /* 商品详情模式样式 */
    .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; }
</style>
