<script setup lang="ts">
    import { reactive, toRefs } 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 { useDictStore } from '@/store/modules/dict'

    const dictStore = useDictStore()
    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    onLoad((option) => {
        uni.setNavigationBarTitle({
            title: '发布供应需求',
        })
        // 获取数据详情
        if (option.id) {
            getDetails(option.id)
        } else {
            // 获取当前位置
            getCurrentAddressInfo()
        }
    })

    onShow(() => {
        // 数据字典赋值
        initDict()
    })

    const pageData = reactive({
        title: '发布供应需求',
        show: {
            time1: false,
            time2: false,
            address: false,
            status: false,
            classify: false,
        },
        options: {
            address: [],
            status: [],
            classify: [],
        },
        form: {
            id: '',
            title: '',
            productSpecs: '',
            minPrice: '',
            maxPrice: '',
            unit: '',
            currency: '',
            supplyQuantity: '',
            minOrderQuantity: '',
            address: '',
            detailedAddress: '',
            supplyStartDate: '',
            supplyEndDate: '',
            status: '',
            classifyText: '',
            classify: '',
            statusText: '',
            province: '',
            city: '',
            country: '',
            image: null,
            imageObj: null,
        },
        rules: [
            {
                name: 'title',
                rule: ['required'],
                msg: ['请输入标题'],
            },
            {
                name: 'minPrice',
                rule: ['required'],
                msg: ['请输入最低价格'],
            },
            {
                name: 'maxPrice',
                rule: ['required'],
                msg: ['请输入最高价格'],
            },
            {
                name: 'unit',
                rule: ['required'],
                msg: ['请输入单位'],
            },
            {
                name: 'currency',
                rule: ['required'],
                msg: ['请选择币种'],
            },
            {
                name: 'supplyQuantity',
                rule: ['required'],
                msg: ['请输入供应数量'],
            },
            {
                name: 'minOrderQuantity',
                rule: ['required'],
                msg: ['请输入最小订单数量'],
            },
            {
                name: 'address',
                rule: ['required'],
                msg: ['请选择省/市/区县'],
            },
            {
                name: 'status',
                rule: ['required'],
                msg: ['请选择状态'],
            },
            {
                name: 'classify',
                rule: ['required'],
                msg: ['请选择分类'],
            },
        ],
    })

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

    async function initDict() {
        pageData.options.address = await getDictData()

        pageData.options.status = dictStore.getDictList.purchase_status.map((item) => {
            return {
                value: item.value,
                text: item.text,
            }
        })
        pageData.options.classify = dictStore.getDictList.classify.map((item) => {
            return {
                value: item.value,
                text: item.text,
            }
        })
    }

    function getCurrentAddressInfo() {
        if (!uni.getStorageSync('location')) return

        const { lon, lat } = uni.getStorageSync('location')
        UserInfoAPI.location({
            lon,
            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) {
        ChanxiaoAPI.purchaseSellDetails({ id }).then((res) => {
            pageData.form = res
            pageData.form.address = `${res.province}/${res.city}/${res.country}`
            pageData.form.statusText = pageData.options.status.find((item) => item.value == res.status).text
            pageData.form.classifyText = pageData.options.classify.find((item) => item.value == res.classify).text
            pageData.form.imageObj = pageData.form.image && parseUrlInfo(pageData.form.image)
        })
    }
    function parseUrlInfo(url) {
        // 从URL中提取文件名
        const pathParts = url.split('/')
        const fileName = pathParts[pathParts.length - 1]

        // 提取扩展名
        const fileParts = fileName.split('.')
        const extname = fileParts[fileParts.length - 1]

        // 返回格式化的对象
        return {
            name: fileName,
            extname,
            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
    }
    function handleChangeAddress(e) {
        pageData.form.address = e.value.join(',')
        pageData.show.address = false
    }
    function handleChangeStatus(e) {
        pageData.form.status = e.value
        pageData.form.statusText = e.text
        pageData.show.status = false
    }

    const toastRef = ref()
    const uploadRef = ref()
    // 文件上传
    function handleUpload(file) {
        uni.uploadFile({
            url: `${globSetting.apiUrl + globSetting.urlPrefix}/sys/common/upload`, // 直接使用上传接口URL
            filePath: file.tempFiles[0].path,
            name: 'file',
            formData: {
                biz: 'temp',
            },
            header: {
                'X-Access-Token': userStore.getToken,
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    const data = JSON.parse(res.data)
                    if (data.code === 200 || data.code === 0) {
                        toastRef.value.show({
                            type: 'success',
                            text: '上传成功',
                        })
                        pageData.form.image = data.message // 保存返回的图片信息
                    }
                }
            },
            fail: (err) => {
                toastRef.value.show({
                    type: 'error',
                    text: '上传失败',
                })
                uploadRef.value.clearFiles()
                pageData.form.image = null
            },
        })
    }
    // 文件删除
    function handleDelete(file) {
        uploadRef.value.clearFiles()
        pageData.form.image = null
    }
    const formRef = ref()
    function submit() {
        formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                changeAddressValue(pageData.form)
                ChanxiaoAPI.supplyAdd(pageData.form).then((res) => {
                    toastRef.value.show({
                        type: 'success',
                        text: '需求发布成功',
                    })
                    uni.switchTab({
                        url: '/pages/chanxiao/chanxiao',
                    })
                })
            }
        })
    }
    /**
     * 处理地区值
     * @param formData 表单数据
     */
    function changeAddressValue(formData) {
        const addressValue = formData.address.split(',')
        if (addressValue.length === 3) {
            formData.province = addressValue[0]
            formData.city = addressValue[1]
            formData.country = addressValue[2]
        }
    }

    function getCurrentDate() {
        const date = new Date()
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
    }
</script>

<template>
    <view class="page">
        <view class="formBox">
            <fui-form ref="formRef" label-weight="auto" top="60">
                <view class="mt20">
                    <fui-input
                        label="供应标题"
                        placeholder="请输入供应标题"
                        placeholderStyle="font-size: 26rpx"
                        v-model="form.title"
                        labelSize="28"
                        label-width="180"
                        required
                    />
                    <fui-input
                        label="规格说明"
                        placeholder="请输入规格说明"
                        placeholderStyle="font-size: 26rpx"
                        v-model="form.productSpecs"
                        labelSize="28"
                        label-width="180"
                    />
                </view>
                <view class="mt20">
                    <!-- 价格区间 -->
                    <view class="form-section" style="padding: 0 10rpx">
                        <view class="form-item required flex align-center">
                            <text class="label" style="font-size: 28rpx">价格区间</text>
                            <view class="price-range">
                                <input
                                    type="number"
                                    class="price-input"
                                    v-model="form.minPrice"
                                    placeholder="最低价"
                                    placeholderStyle="font-size: 26rpx"
                                    :min="0"
                                />
                                <text class="price-separator">-</text>
                                <input
                                    type="number"
                                    class="price-input"
                                    v-model="form.maxPrice"
                                    placeholder="最高价"
                                    placeholderStyle="font-size: 26rpx"
                                    :min="0"
                                />
                            </view>
                        </view>
                    </view>
                    <fui-input
                        required
                        label="计量单位"
                        placeholder="请输入计量单位"
                        placeholderStyle="font-size: 26rpx"
                        v-model="form.unit"
                        labelSize="28"
                        label-width="180"
                    />
                    <fui-input
                        required
                        label="币种"
                        placeholder="请输入币种"
                        placeholderStyle="font-size: 26rpx"
                        v-model="form.currency"
                        labelSize="28"
                        label-width="180"
                    />
                    <fui-input
                        required
                        label="供应数量"
                        placeholder="请输入供应数量"
                        placeholderStyle="font-size: 26rpx"
                        v-model="form.supplyQuantity"
                        labelSize="28"
                        label-width="180"
                        type="number"
                    />
                    <fui-input
                        required
                        label="最小起订量"
                        placeholder="请输入最小起订量"
                        placeholderStyle="font-size: 26rpx"
                        v-model="form.minOrderQuantity"
                        labelSize="28"
                        label-width="180"
                        type="number"
                    />
                </view>
                <view class="mt20">
                    <view class="form-item required flex align-center" style="padding: 20rpx 10rpx">
                        <text class="label" style="font-size: 28rpx">请选择区域</text>
                        <view class="select-input" @click="show.address = true">
                            <text class="time-text" :class="{ placeholder: !form.address }">
                                {{ getText(form.address, ' / ') || '请选择省/市/区县' }}
                            </text>
                        </view>
                    </view>
                    <fui-input
                        required
                        label="详细地址"
                        placeholder="请输入详细地址"
                        placeholderStyle="font-size: 26rpx"
                        v-model="form.detailedAddress"
                        labelSize="28"
                        label-width="180"
                    />

                    <!-- 供应时间 -->
                    <view class="form-section" style="padding: 0 30rpx">
                        <view class="form-item flex align-center">
                            <text class="label" style="font-size: 28rpx">供应时间</text>
                            <view class="time-range">
                                <view class="time-input" @click="show.time1 = true">
                                    <text class="time-text" :class="{ placeholder: !form.supplyStartDate }">
                                        {{ form.supplyStartDate || '开始时间' }}
                                    </text>
                                    <text
                                        class="time-text"
                                        :class="{ placeholder: !form.supplyStartDate }"
                                        style="font-size: 26rpx"
                                    >
                                        {{ form.supplyStartDate || '开始时间' }}
                                    </text>
                                </view>
                                <text class="time-separator">-</text>
                                <view class="time-input" @click="show.time2 = true">
                                    <text class="time-text" :class="{ placeholder: !form.supplyEndDate }">
                                        {{ form.supplyEndDate || '结束时间' }}
                                    </text>
                                    <text
                                        class="time-text"
                                        :class="{ placeholder: !form.supplyEndDate }"
                                        style="font-size: 26rpx"
                                    >
                                        {{ form.supplyEndDate || '结束时间' }}
                                    </text>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="form-section" style="padding: 0 10rpx">
                        <view class="form-item required flex align-center">
                            <text class="label" style="font-size: 28rpx">分类</text>
                            <view class="time-input" @click="show.classify = true">
                                <text
                                    class="select-text"
                                    :class="{ placeholder: !form.classifyText }"
                                    style="font-size: 26rpx"
                                >
                                    {{ form.classifyText || '请选择分类' }}
                                </text>
                            </view>
                        </view>
                    </view>
                </view>

                <view class="bg-white mt20" style="padding: 0.875rem 1rem">
                    <view class="mb-1 flex justify-start"> 上传图片 </view>
                    <uni-file-picker
                        :value="form.imageObj"
                        ref="uploadRef"
                        limit="1"
                        :auto-upload="false"
                        @select="handleUpload"
                        @delete="handleDelete"
                    />
                </view>
                <view class="fui-btn__box" v-if="!form.id" style="margin-top: 30rpx">
                    <fui-button text="发布需求" bold radius="96rpx" @click="submit" />
                </view>
            </fui-form>

            <fui-date-picker
                :show="show.time1"
                type="3"
                @change="handleChangeTime1"
                @cancel="show.time1 = false"
                :minDate="getCurrentDate()"
            />
            <fui-date-picker
                :show="show.time2"
                type="3"
                @change="handleChangeTime2"
                @cancel="show.time2 = false"
                :minDate="getCurrentDate()"
            />
            <fui-picker
                :show="show.status"
                :layer="1"
                :linkage="true"
                :options="options.status"
                @change="handleChangeStatus"
                @cancel="show.status = false"
            />
            <fui-picker
                :show="show.classify"
                :layer="1"
                :linkage="true"
                :options="options.classify"
                @change="handleChangeClassify"
                @cancel="show.classify = false"
            />
            <fui-picker
                :show="show.address"
                :options="options.address"
                :linkage="true"
                :layer="3"
                @change="handleChangeAddress"
                @cancel="show.address = false"
            />
            <fui-toast ref="toastRef" />
        </view>
    </view>
</template>

<style lang="scss" scoped>
    body {
        background-color: #e6f5e8;
    }

    .page {
        background-color: #e6f5e8;
        width: 750rpx;
        overflow-x: hidden;

        .mt20 {
            margin-top: 30rpx;
            background: #fff;
            padding: 20rpx;
            border-radius: 10rpx;
        }

        .formBox {
            width: 690rpx;
            margin: 30rpx auto;
        }

        .purchase-form {
            background: transparent;
        }

        .form-section {
            // background: #ffffff;
            // border-radius: 12rpx;
            // margin-bottom: 20rpx;

            // box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
            border-bottom: 1rpx solid #f5f5f5;
        }

        .form-item {
            padding: 30rpx 0;
            border-bottom: 1rpx solid #f5f5f5;

            &:last-child {
                border-bottom: none;
            }

            &.required .label::before {
                content: '*';
                color: #ff4d4f;
                margin-right: 8rpx;
            }

            // 添加点击区域样式
            .select-input {
                position: relative;
            }
        }

        .form-row {
            display: flex;
            justify-content: space-between;
        }

        .half-width {
            width: 48%;
        }

        .align-center {
            align-items: center;
        }

        .label {
            display: block;
            font-size: 28rpx;
            color: #333333;
            font-weight: 500;
            width: 180rpx;
            // margin-right: 20rpx;
        }

        .input {
            width: 100%;
            height: 80rpx;
            background: #f8f9fa;
            border-radius: 8rpx;
            padding: 0 20rpx;
            font-size: 28rpx;
            color: #333333;

            &::placeholder {
                color: #999999;
            }
        }

        .price-range {
            display: flex;
            align-items: center;
            // justify-content: space-between;
        }

        .price-input {
            width: 15%;
            // height: 80rpx;
            // background: #f8f9fa;
            // border-radius: 8rpx;
            padding: 0 10rpx;
            font-size: 28rpx;
            text-align: center;
        }

        .price-separator {
            color: #666666;
            font-size: 28rpx;
            margin: 0 10rpx;
        }

        .select-input {
            flex: 1;
            border-radius: 8rpx;
            padding: 0 20rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            cursor: pointer;
        }

        .select-text {
            font-size: 28rpx;
            color: #333333;
            padding: 0 20rpx;
            &.placeholder {
                color: #999999;
            }
        }

        .select-arrow {
            color: #999999;
            font-size: 24rpx;
            line-height: 1;
        }

        .time-range {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .time-input {
            width: 45%;
            // height: 80rpx;
            // background: #f8f9fa;
            border-radius: 8rpx;
            display: flex;
            align-items: center;
        }

        .time-text {
            font-size: 28rpx;
            color: #333333;

            &.placeholder {
                color: #999999;
            }
        }

        .time-separator {
            color: #666666;
            font-size: 28rpx;
            margin: 0 10rpx;
        }

        .upload-area {
            margin-top: 10rpx;
        }

        .custom-uploader {
            :deep(.uni-file-picker__container) {
                border: 2rpx dashed #d9d9d9;
                border-radius: 8rpx;
                background: #f8f9fa;
            }
        }

        .upload-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 200rpx;
            color: #999999;
        }

        .upload-icon {
            font-size: 48rpx;
            margin-bottom: 10rpx;
        }

        .upload-text {
            font-size: 24rpx;
        }

        .submit-section {
            background: transparent;
            padding: 40rpx 0;
        }

        .submit-btn {
            width: 100%;
            height: 88rpx;
            background: #5db66f;
            border-radius: 44rpx;
            color: #ffffff;
            font-size: 32rpx;
            font-weight: 500;
            border: none;

            &:active {
                background: #4ca85c;
                opacity: 0.9;
            }
        }
    }

    ::v-deep .uni-input-placeholder {
        font-size: 28rpx !important;
        color: #999999 !important;
    }

    :deep(.fui-button) {
        width: 690rpx;
        border-color: #5db66f !important;
        background: #5db66f !important;
    }

    // 移除fui-form的默认样式
    :deep(.fui-form) {
        background: transparent;
    }

    :deep(.fui-form__item) {
        background: transparent;
        border: none;
        margin-bottom: 0;
        padding: 0;
    }
</style>
