<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 nongjifuwu from '@/api/model/nongjifuwu'
    import { useDictStore } from '@/store/modules/dict'

    const dictStore = useDictStore()
    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    onLoad((option) => {
        pageData.form.type = option.type
        // 获取数据详情
        if (option.id) {
            pageData.title = '查看农机详情'
            getDetails(option.id)
        } else {
            pageData.title = '新增农机作业'
        }
        uni.setNavigationBarTitle({
            title: pageData.title,
        })
    })

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

    const pageData = reactive({
        title: '农机表单',
        loading: false,
        form: {
            id: '',
            name: '',
            phone: '',
            price: 0,
            scope: '',
            type: '',
            picture: '',
            pictureObj: null,
        },
        rules: [
            {
                name: 'name',
                rule: ['required'],
                msg: ['请填写农机名称'],
            },
            {
                name: 'name',
                rule: ['required'],
                msg: ['请填写联系方式'],
            },
            {
                name: 'scope',
                rule: ['required'],
                msg: ['请填写服务范围'],
            },
            {
                name: 'price',
                rule: ['required'],
                msg: ['请填写价格'],
            },
            {
                name: 'picture',
                rule: ['required'],
                msg: ['请上传图片'],
            },
        ],
    })

    const { form } = toRefs(pageData)

    function initDict() {
        console.log(dictStore.getDictList)
    }

    function getDetails(id) {
        pageData.loading = true
        nongjifuwu
            .farmMachineDetails({ id })
            .then((res) => {
                console.log(res)
                pageData.form = res
                pageData.form.pictureObj = pageData.form.picture && parseUrlInfo(pageData.form.picture)
            })
            .finally(() => {
                pageData.loading = false
            })
    }

    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,
        }
    }

    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.picture = data.message // 保存返回的图片信息
                    }
                }
            },
            fail: () => {
                toastRef.value.show({
                    type: 'error',
                    text: '上传失败',
                })
                uploadRef.value.clearFiles()
                pageData.form.picture = null
            },
        })
    }
    // 文件删除
    function handleDelete() {
        uploadRef.value.clearFiles()
        pageData.form.picture = null
    }
    const formRef = ref()
    function submit() {
        formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                nongjifuwu.farmMachineAddMachine(pageData.form).then(() => {
                    toastRef.value.show({
                        type: 'success',
                        text: '发布成功',
                    })
                    uni.redirectTo({
                        url: '/pages/nongjifuwu/nongjifuwu',
                    })
                })
            }
        })
    }
</script>
<template>
    <fui-form ref="formRef" :disabled="form.id ? true : false">
        <fui-input required label="农机名称" placeholder="请输入农机名称" v-model="form.name"></fui-input>
        <fui-input required label="联系方式" placeholder="请输入联系方式" v-model="form.phone"></fui-input>
        <fui-input required label="服务范围" placeholder="请输入服务范围" v-model="form.scope"></fui-input>
        <fui-input
            required
            label="价格(元/亩)"
            borderTop
            placeholder="请输入价格"
            number
            v-model="form.price"
        ></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
                :value="form.pictureObj"
                :max-size="1024"
                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-toast ref="toastRef"></fui-toast>
    <fui-loading isFixed v-if="pageData.loading" backgroundColor="rgba(0, 0, 0, 0.4)"></fui-loading>
</template>

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