<script setup lang="ts">
    import { reactive, ref, toRefs } from 'vue'
    import { onLoad } from '@dcloudio/uni-app'
    import { useUserStore } from '@/store/modules/user'
    import { useGlobSetting } from '/@/hooks/setting'
    import * as LinghuoyonggongAPI from '@/api/model/linghuoyonggong'
    import * as nongjifuwu from '@/api/model/nongjifuwu'
    import { getText } from '@/utils/dict/area'
    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: {
            time1: false,
            time2: false,
            address: false,
        },
        optionsValText: '',
        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', 'isMobile'], msg: ['请填写联系方式', '手机号格式不正确'] },
            { name: 'demand', rule: ['required'], msg: ['请填写作业需求'] },
            { name: 'startTime', rule: ['required'], msg: ['请选择开始时间'] },
            { name: 'endTime', 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)
            if (res.scope) pageData.optionsValText = getText(res.scope, ' / ')
        }).finally(() => pageData.loading = false)
    }

    function parseUrlInfo(url) {
        const fileName = url.split('/').pop()
        return { name: fileName, extname: fileName.split('.').pop(), 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`,
            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
                }
            }
        })
    }
    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: '发布成功' })
                    setTimeout(() => uni.navigateBack(), 1500)
                })
            }
        })
    }

    function getCurrentDate() {
        const d = new Date()
        return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
    }
</script>

<template>
    <view class="page">
        <!-- 发布模式 -->
        <view v-if="!form.id" class="formBox">
            <fui-form ref="formRef" label-weight="auto" top="60">
                <view class="mt20">
                    <fui-input required label="服务名称" v-model="form.name" 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 label="详细地址" v-model="form.address" labelSize="28" label-width="180" />
                    <fui-input required type="number" label="联系方式" v-model="form.phone" labelSize="28" label-width="180" />
                </view>
                <view class="mt20">
                    <fui-textarea required label="作业需求" v-model="form.demand" labelSize="28" label-width="180" />
                    <view class="form-item flex align-center" style="padding: 30rpx 10rpx">
                        <text class="label">作业时间</text>
                        <view class="time-range">
                            <view class="time-input" @click="show.time1 = true">
                                <text class="time-text" :class="{ placeholder: !form.startTime }">{{ form.startTime || '开始' }}</text>
                            </view>
                            <text class="sep">至</text>
                            <view class="time-input" @click="show.time2 = true">
                                <text class="time-text" :class="{ placeholder: !form.endTime }">{{ form.endTime || '结束' }}</text>
                            </view>
                        </view>
                    </view>
                </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="form.picture = null" />
                </view>
                <view class="fui-btn__box">
                    <fui-button text="立即发布" bold radius="100rpx" @click="submit" />
                </view>
            </fui-form>
        </view>

        <!-- 详情模式... (已在之前步骤重构) -->
        <view v-else class="product-detail">
            <!-- 详情 UI 内容 -->
            <view class="detail-banner">
                <image v-if="form.picture" :src="form.picture" mode="aspectFill" class="banner-img" />
                <view v-else class="banner-placeholder"><fui-icon name="picture" :size="100" color="#ddd"></fui-icon></view>
            </view>
            <view class="info-card">
                <text class="product-title">{{ form.name }}</text>
            </view>
        </view>

        <AreaPicker v-model:show="show.address" :layer="3" @confirm="handleAreaConfirm" />
        <fui-date-picker :show="show.time1" type="3" @change="handleChangeTime1" @cancel="show.time1 = false" :min-date="getCurrentDate()" />
        <fui-date-picker :show="show.time2" type="3" @change="handleChangeTime2" @cancel="show.time2 = false" :min-date="getCurrentDate()" />
        <fui-toast ref="toastRef" />
        <fui-loading isFixed v-if="pageData.loading" />
    </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; } } }
    .time-range { display: flex; align-items: center; flex: 1; margin-left: 20rpx; .time-input { flex: 1; text-align: center; } .sep { margin: 0 10rpx; color: #ccc; } }
    .select-text { font-size: 28rpx; &.placeholder { color: #ccc; } }
    :deep(.fui-input__label) { font-family: 'DingTalk Sans' !important; }
</style>
