<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,
        show: {
            time1: false,
            time2: false,
        },
        form: {
            id: '',
            name: '',
            type: '',
            scope: '',
            address: '',
            phone: '',
            demand: '',
            startTime: '',
            endTime: '',
            picture: '',
            pictureObj: null,
        },
        rules: [
            {
                name: 'name',
                rule: ['required'],
                msg: ['请填写服务名称'],
            },
            {
                name: 'scope',
                rule: ['required'],
                msg: ['请填写服务范围'],
            },
            {
                name: 'address',
                rule: ['required'],
                msg: ['请填写详细地址'],
            },
            {
                name: 'phone',
                rule: ['required'],
                msg: ['请填写联系方式'],
            },
            {
                name: 'demand',
                rule: ['required'],
                msg: ['请填写需求描述'],
            },
            {
                name: 'startTime',
                rule: ['required'],
                msg: ['请选择开始时间'],
            },
            {
                name: 'endTime',
                rule: ['required'],
                msg: ['请选择结束时间'],
            },
        ],
    })

    const { show, 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,
        }
    }

    function handleChangeTime1(e) {
        pageData.form.startTime = e.result
        pageData.show.time1 = false
    }
    function handleChangeTime2(e) {
        pageData.form.endTime = e.result
        pageData.show.time2 = 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.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.farmMachineAddFarm(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.scope"></fui-input>
        <fui-input required label="详细地址" placeholder="请输入详细地址" v-model="form.address"></fui-input>
        <fui-input required label="联系方式" borderTop placeholder="请输入联系方式" v-model="form.phone"></fui-input>
        <fui-input required label="作业需求" borderTop placeholder="请输入作业需求" v-model="form.demand"></fui-input>
        <fui-input
            required
            label="作业开始时间"
            borderTop
            placeholder="请选择开始时间"
            v-model="form.startTime"
            @click="show.time1 = true"
        ></fui-input>
        <fui-input
            required
            label="作业结束时间"
            borderTop
            placeholder="请选择结束时间"
            v-model="form.endTime"
            @click="show.time2 = true"
        ></fui-input>
        <view class="bg-white" style="padding: 0.875rem 0.35rem">
            <view class="mb-1 flex justify-start"> 图片 </view>
            <uni-file-picker
                :value="form.pictureObj"
                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-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>
