<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 NongchangAPI from '@/api/model/nongchang'
    import * as UserInfoAPI from '@/api/model/userInfo'
    import { useDictStore } from '@/store/modules/dict'
    import AreaPicker from '@/components/AreaPicker/index.vue'

    const dictStore = useDictStore()
    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    
    const isSave = ref(false)

    onLoad((option) => {
        if (option.id) {
            isSave.value = false
            getDetails(option.id)
            uni.setNavigationBarTitle({ title: '基地详情' })
        } else {
            isSave.value = true
            getCurrentAddressInfo()
            uni.setNavigationBarTitle({ title: '新增基地' })
        }
    })

    onShow(() => {
        initDict()
    })

    const pageData = reactive({
        loading: false,
        show: {
            address: false,
            growCrops: false,
        },
        options: {
            growCrops: [],
        },
        form: {
            id: '',
            baseName: '',
            province: '',
            city: '',
            country: '',
            address: '',
            addressDetail: '',
            scale: '',
            growCrops: '',
            growCropsText: '',
            contactPerson: '',
            contactMobile: '',
            profile: '',
            longitude: '',
            latitude: '',
        },
        rules: [
            { name: 'baseName', rule: ['required'], msg: ['请输入基地名称'] },
            { name: 'address', rule: ['required'], msg: ['请选择所在地区'] },
            { name: 'addressDetail', rule: ['required'], msg: ['请输入详细地址'] },
            { name: 'scale', rule: ['required'], msg: ['请输入基地规模'] },
            { name: 'growCrops', rule: ['required'], msg: ['请选择种植作物'] },
        ],
    })

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

    async function initDict() {
        pageData.options.growCrops = dictStore.getDictList.crops_type.map((item) => {
            return { value: item.value, text: item.text }
        })
    }

    function handleAreaConfirm(e) {
        pageData.form.province = e.text[0]
        pageData.form.city = e.text[1]
        pageData.form.country = e.text[2]
        pageData.form.address = e.fullText
    }

    function getCurrentAddressInfo() {
        const loc = uni.getStorageSync('location')
        if (!loc) return
        UserInfoAPI.location({ lon: loc.lon, lat: loc.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) {
        pageData.loading = true
        NongchangAPI.getFarmbaseDetail({ id }).then((res) => {
            pageData.form = res
            if (res.growCrops) {
                const item = pageData.options.growCrops.find(i => i.value == res.growCrops)
                pageData.form.growCropsText = item ? item.text : ''
            }
        }).finally(() => pageData.loading = false)
    }

    function handleGrowCropsChange(e) {
        pageData.form.growCrops = e.value
        pageData.form.growCropsText = e.text
        pageData.show.growCrops = false
    }

    const toastRef = ref()
    const formRef = ref()
    function submit() {
        formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
            if (res.isPassed) {
                NongchangAPI.saveFarmbase(pageData.form).then(() => {
                    toastRef.value.show({ type: 'success', text: '保存成功' })
                    setTimeout(() => uni.navigateBack(), 1500)
                })
            }
        })
    }
</script>

<template>
    <view class="page">
        <view class="container">
            <fui-form ref="formRef">
                <view class="section-card">
                    <fui-input label="基地名称" placeholder="请输入" v-model="form.baseName" required />
                    <fui-input disabled required label="所在地区" v-model="form.address" @click="show.address = true" />
                    <fui-input label="详细地址" placeholder="请输入" v-model="form.addressDetail" required />
                </view>
                <view class="section-card">
                    <fui-input type="number" label="基地规模" v-model="form.scale" required>
                        <template #suffix><text class="unit">亩</text></template>
                    </fui-input>
                    <fui-input disabled required label="种植作物" v-model="form.growCropsText" @click="show.growCrops = true" />
                </view>
                <!-- 更多字段... -->
                <view class="submit-area" v-if="isSave">
                    <fui-button text="确认保存" radius="100rpx" @click="submit" />
                </view>
            </fui-form>
        </view>

        <AreaPicker v-model:show="show.address" :layer="3" title="选择所属地区" @confirm="handleAreaConfirm" />
        <fui-picker :show="show.growCrops" :options="options.growCrops" @change="handleGrowCropsChange" @cancel="show.growCrops = false" />
        <fui-toast ref="toastRef" />
    </view>
</template>

<style lang="scss" scoped>
    .page { background-color: #f7f8fa; min-height: 100vh; font-family: 'DingTalk Sans', sans-serif; }
    .container { padding: 24rpx; }
    .section-card { background: #fff; border-radius: 24rpx; padding: 10rpx 24rpx; margin-bottom: 24rpx; }
    .submit-area { padding: 40rpx 20rpx; }
    .unit { font-size: 26rpx; color: #999; margin-left: 12rpx; }
    :deep(.fui-input__label) { font-family: 'DingTalk Sans' !important; }
</style>
