<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 { areaTree, getTextByCode, getCodeByText } from '@/utils/areaData'
    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: 0,
            maxPrice: 0,
            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)

    function initDict() {
        pageData.options.address = areaTree
        console.log(dictStore.getDictList['purchase_status'])

        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 = `${getTextByCode(res.province)}/${getTextByCode(res.city)}/${getTextByCode(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: extname,
            url: 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.text.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 表单数据
     */
    const changeAddressValue = (formData) => {
        const addressValue = formData.address.split('/')
        if (addressValue.length === 3) {
            formData.province = getCodeByText(addressValue[0])
            formData.city = getCodeByText(addressValue[1])
            formData.country = getCodeByText(addressValue[2])
        }
    }
</script>

<template>
    <fui-form ref="formRef">
        <fui-input required label="供应标题" placeholder="请输入供应标题" v-model="form.title"></fui-input>
        <fui-input label="规格说明" borderTop placeholder="请输入规格说明" v-model="form.productSpecs"></fui-input>
        <fui-input required label="最低价" borderTop placeholder="请输入最低价" v-model="form.minPrice"></fui-input>
        <fui-input required label="最高价" borderTop placeholder="请输入最高价" v-model="form.maxPrice"></fui-input>
        <fui-input required label="计量单位" borderTop placeholder="请输入计量单位" v-model="form.unit"></fui-input>
        <fui-input required label="币种" borderTop placeholder="请输入币种" v-model="form.currency"></fui-input>
        <fui-input
            required
            label="供应数量"
            borderTop
            placeholder="请输入供应数量"
            v-model="form.supplyQuantity"
        ></fui-input>
        <fui-input
            required
            label="最小起订量"
            borderTop
            placeholder="请输入最小起订量"
            v-model="form.minOrderQuantity"
        ></fui-input>
        <fui-input
            required
            label="省/市/区县"
            placeholder="请选择省/市/区县"
            v-model="form.address"
            @click="show.address = true"
        ></fui-input>
        <fui-input label="详细地址" placeholder="请输入详细地址" v-model="form.detailedAddress"></fui-input>
        <fui-input
            label="供应开始时间"
            borderTop
            placeholder="请选择供应开始时间"
            v-model="form.supplyStartDate"
            @click="show.time1 = true"
        ></fui-input>
        <fui-input
            label="供应结束时间"
            borderTop
            placeholder="请选择供应结束时间"
            v-model="form.supplyEndDate"
            @click="show.time2 = true"
        ></fui-input>
        <fui-input
            required
            label="分类"
            placeholder="请选择分类"
            v-model="form.classifyText"
            @click="show.classify = true"
        ></fui-input>
        <fui-input
            label="状态"
            placeholder="请选择状态"
            v-model="form.statusText"
            @click="show.status = true"
        ></fui-input>
        <view class="bg-white" 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"
            ></uni-file-picker>
        </view>
        <view class="fui-btn__box bg-white p-4" v-if="!form.id">
            <fui-button text="发布需求" bold radius="96rpx" @click="submit"></fui-button>
        </view>
    </fui-form>

    <fui-date-picker
        :show="show.time1"
        type="3"
        @change="handleChangeTime1"
        @cancel="show.time1 = false"
    ></fui-date-picker>
    <fui-date-picker
        :show="show.time2"
        type="3"
        @change="handleChangeTime2"
        @cancel="show.time2 = false"
    ></fui-date-picker>
    <fui-picker
        :show="show.status"
        :layer="1"
        :linkage="true"
        :options="options.status"
        @change="handleChangeStatus"
        @cancel="show.status = false"
    ></fui-picker>
    <fui-picker
        :show="show.classify"
        :layer="1"
        :linkage="true"
        :options="options.classify"
        @change="handleChangeClassify"
        @cancel="show.classify = false"
    ></fui-picker>
    <fui-picker
        :show="show.address"
        :options="options.address"
        :linkage="true"
        :layer="3"
        @change="handleChangeAddress"
        @cancel="show.address = false"
    ></fui-picker>

    <fui-toast ref="toastRef"></fui-toast>
</template>

<style lang="scss" scoped>
    :deep(.fui-button) {
        border-color: #ff9800 !important;
        background: #ff9800 !important;
    }
</style>
