<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 { getCodeByText } from '@/utils/areaData'
    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: null,
            imageObj: null,
        },
        position: [],
        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: ['请上传参考图片'] },
        ],
    })

    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]
        pageData.form.areaText = e.fullText
    }

    function getCurrentAddressInfo() {
        const loc = uni.getStorageSync('location')
        if (!loc) return
        pageData.position = [loc.lon, loc.lat]
        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}`
            pageData.form.areaText = `${res.province}/${res.city}/${res.country}`
        })
    }

    function getDetails(id) {
        pageData.loading = true
        ChanxiaoAPI.purchaseSellDetails({ id }).then((res) => {
            pageData.form = res
            // 格式化地区显示
            pageData.form.areaText = `${res.province || ''}/${res.city || ''}/${res.country || ''}`.replace(/\/+$/, '')
            
            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() {
        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="formBox">
            <fui-form ref="formRef" label-weight="auto" top="60">
                <view class="mt20">
                    <fui-input disabled required label="采购类别" v-model="form.classifyText" @click="show.classify = true" labelSize="28" label-width="180" />
                    <fui-input required label="招聘标题" placeholder="请输入标题" v-model="form.title" 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.priceStart" placeholder="最低价" />
                            <text class="sep">-</text>
                            <input type="number" class="price-input" v-model="form.priceEnd" placeholder="最高价" />
                        </view>
                    </view>
                    <fui-input required type="number" label="采购数量" v-model="form.count" labelSize="28" label-width="180" />
                    <fui-input required label="单位" v-model="form.unit" labelSize="28" label-width="180" />
                </view>
                <view class="mt20">
                    <fui-input disabled required label="收货地区" v-model="form.areaText" @click="show.address = true" labelSize="28" label-width="180" />
                    <fui-input required label="截止日期" v-model="form.deadLine" @click="show.time = true" disabled 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 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: #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: 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; }
</style>
