<script setup lang="ts">
    import { reactive, toRefs, ref } 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 AreaPicker from '@/components/AreaPicker/index.vue'

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

    const pageData = reactive({
        title: '农机表单',
        loading: false,
        show: {
            address: false,
        },
        form: {
            id: '',
            name: '',
            phone: '',
            price: '',
            scope: '',
            type: '',
            picture: '',
            pictureObj: null,
        },
        optionsValText: '',
        rules: [
            { name: 'name', rule: ['required'], msg: ['请填写作业标题'] },
            { name: 'phone', rule: ['required', 'isMobile'], msg: ['请填写联系方式', '手机号格式不正确'] },
            { name: 'scope', rule: ['required'], msg: ['请填写服务范围'] },
            { name: 'price', rule: ['required'], msg: ['请填写价格'] },
            { name: 'picture', rule: ['required'], msg: ['请上传图片'] },
        ],
    })

    const { show, form } = toRefs(pageData)

    function handleAreaConfirm(e) {
        pageData.form.scope = e.fullCode
        pageData.optionsValText = e.fullText
    }

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

    function parseUrlInfo(url) {
        const fileName = url.split('/').pop()
        return { name: fileName, extname: fileName.split('.').pop(), url }
    }

    const toastRef = ref()
    const uploadRef = ref()
    function handleUpload(file) {
        uni.uploadFile({
            url: `${globSetting.apiUrl + globSetting.urlPrefix}/sys/common/upload`,
            filePath: file.tempFiles[0].path,
            name: 'file',
            formData: { biz: 'temp' },
            header: { 'X-Access-Token': userStore.getToken },
            success: (res) => {
                const data = JSON.parse(res.data)
                if (data.code === 200 || data.code === 0) {
                    toastRef.value.show({ type: 'success', text: '上传成功' })
                    pageData.form.picture = data.message
                }
            }
        })
    }
    function handleDelete() {
        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: '发布成功' })
                    setTimeout(() => uni.navigateBack(), 1500)
                })
            }
        })
    }
</script>

<template>
    <view class="page">
        <view class="formBox">
            <fui-form ref="formRef" label-weight="auto" top="60" :disabled="form.id ? true : false">
                <view class="mt20">
                    <fui-input required label="作业标题" placeholder="请输入" v-model="form.name" labelSize="28" label-width="180" />
                    <fui-input required label="联系方式" type="number" placeholder="请输入手机号" v-model="form.phone" labelSize="28" label-width="180" />
                    <view class="form-item required flex align-center" style="padding: 20rpx 10rpx">
                        <text class="label">服务范围</text>
                        <view class="time-input" @click="show.address = true">
                            <text class="select-text" :class="{ placeholder: !pageData.form.scope }">
                                {{ pageData.optionsValText || '请选择' }}
                            </text>
                        </view>
                    </view>
                    <fui-input required type="number" label="价格" placeholder="请输入" v-model="form.price" labelSize="28" label-width="180">
                        <template #suffix><view class="unit-slot">元/亩</view></template>
                    </fui-input>
                </view>

                <view class="bg-white mt20" style="padding: 30rpx">
                    <view class="mb-1" style="font-size: 28rpx"><span style="color: red">*&nbsp;</span>上传图片</view>
                    <uni-file-picker :value="form.pictureObj" limit="1" @select="handleUpload" @delete="handleDelete" />
                </view>

                <view class="fui-btn__box" v-if="!form.id">
                    <fui-button text="提交发布" bold radius="100rpx" @click="submit" />
                </view>
            </fui-form>

            <AreaPicker v-model:show="show.address" :layer="3" title="选择服务范围" @confirm="handleAreaConfirm" />
            <fui-toast ref="toastRef" />
            <fui-loading isFixed v-if="pageData.loading" />
        </view>
    </view>
</template>

<style lang="scss" scoped>
    .page { background-color: #f7f8fa; min-height: 100vh; font-family: 'DingTalk Sans', sans-serif; }
    .formBox { padding: 24rpx; .mt20 { background: #fff; border-radius: 20rpx; padding: 10rpx 24rpx; margin-bottom: 24rpx; } }
    .form-item { padding: 30rpx 0; display: flex; align-items: center; border-bottom: 1rpx solid #f8f8f8; .label { font-size: 28rpx; color: #333; width: 180rpx; .red { color: #ff4d4f; } } }
    .select-text { font-size: 28rpx; &.placeholder { color: #ccc; } }
    .unit-slot { font-size: 28rpx; color: #999; margin-left: 12rpx; }
    :deep(.fui-input__label) { font-family: 'DingTalk Sans' !important; }
</style>
