<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: {
            time: false,
            classify: false,
            address: false,
        },
        options: {
            address: [],
            classify: [],
        },
        form: {
            id: '',
            title: '',
            count: 0,
            unit: '',
            deadLine: '',
            priceStart: 0,
            priceEnd: 0,
            address: '',
            province: '',
            city: '',
            country: '',
            classify: '',
            classifyText: '',
            inputTextArea: '',
            image: null,
        },
        rules: [
            {
                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: 'classify',
                rule: ['required'],
                msg: ['请选择分类'],
            },
            {
                name: 'image',
                rule: ['required'],
                msg: ['请上传示例图片'],
            },
        ],
    })

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

    function initDict() {
        pageData.options.classify = dictStore.getDictList['classify'].map((item) => {
            return {
                value: item.value,
                text: item.text,
            }
        })
        pageData.options.address = areaTree
    }

    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) => {
            console.log(res)

            pageData.form = res
            pageData.form.address = `${getTextByCode(res.province)}/${getTextByCode(res.city)}/${getTextByCode(res.country)}`
        })
    }

    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
    }
    function handleChangeAddress(e) {
        pageData.form.address = e.text.join('/')
        pageData.show.address = 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: () => {
                toastRef.value.show({
                    type: 'error',
                    text: '上传失败',
                })
                uploadRef.value.clearFiles()
                pageData.form.image = null
            },
        })
    }
    // 文件删除
    function handleDelete() {
        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.purchaseSellAdd(pageData.form)
                    .then(() => {
                        toastRef.value.show({
                            type: 'success',
                            text: '需求发布成功',
                        })
                        uni.switchTab({
                            url: '/pages/chanxiao/chanxiao',
                        })
                    })
                    .catch((err) => {
                        toastRef.value.show({
                            type: 'error',
                            text: '需求发布失败',
                        })
                    })
            }
        })
    }
    /**
     * 处理地区值
     * @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="标题" borderTop placeholder="请输入标题" v-model="form.title"></fui-input>
        <fui-input required label="数量" borderTop placeholder="请输入数量" v-model="form.count"></fui-input>
        <fui-input required label="单位" borderTop placeholder="请输入单位" v-model="form.unit"></fui-input>
        <fui-input
            required
            label="截至时间"
            borderTop
            placeholder="请选择截至时间"
            v-model="form.deadLine"
            @click="show.time = true"
        ></fui-input>
        <fui-input required label="最低价" placeholder="请输入最低价" v-model="form.priceStart"></fui-input>
        <fui-input required label="最高价" placeholder="请输入最高价" v-model="form.priceEnd"></fui-input>
        <fui-input
            required
            label="省/市/区县"
            placeholder="请选择省/市/区县"
            v-model="form.address"
            @click="show.address = 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.inputTextArea"></fui-input>
        <view class="bg-white" style="padding: 0.875rem 0.35rem">
            <view class="mb-1 flex justify-start">
                <text class="pr-1" style="color: #ff2b2b">*</text>
                示例图片
            </view>
            <uni-file-picker
                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.time"
        type="3"
        @change="handleChangeTime"
        @cancel="show.time = false"
    ></fui-date-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>
