<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) {
                pageData.loading = true
                NongchangAPI.saveFarmbase(pageData.form).then(() => {
                    toastRef.value.show({ type: 'success', text: '保存成功' })
                    setTimeout(() => uni.navigateBack(), 1500)
                }).finally(() => pageData.loading = false)
            }
        })
    }
</script>

<template>
    <view class="page">
        <view class="form-banner">
            <text class="title">{{ isSave ? '新增基地' : '基地详情' }}</text>
            <text class="subtitle">{{ isSave ? '录入生产基地信息，完善经营档案' : '查看基地详细信息' }}</text>
        </view>

        <view class="form-content">
            <fui-form ref="formRef">
                <view class="section-card">
                    <view class="card-header">
                        <view class="line"></view>
                        <text>基地基础信息</text>
                    </view>
                    <fui-input label="基地名称" placeholder="请输入基地名称" v-model="form.baseName" required label-size="28" />
                    <fui-form-item required asterisk label="所在地区" labelSize="28" :labelWeight="400" labelWidth="auto">
                        <view class="picker-input" @click="show.address = true">
                            <text class="select-text" :class="{ placeholder: !form.address }">
                                {{ form.address || '请选择所在地区' }}
                            </text>
                            <fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon>
                        </view>
                    </fui-form-item>
                    <fui-input label="详细地址" placeholder="请输入详细地址" v-model="form.addressDetail" required label-size="28" />
                </view>

                <view class="section-card">
                    <view class="card-header">
                        <view class="line"></view>
                        <text>经营规模信息</text>
                    </view>
                    <fui-input type="number" label="基地规模" v-model="form.scale" required label-size="28">
                        <template #suffix><text class="unit">亩</text></template>
                    </fui-input>
                    <fui-form-item required asterisk label="种植作物" labelSize="28" :labelWeight="400" labelWidth="auto">
                        <view class="picker-input" @click="show.growCrops = true">
                            <text class="select-text" :class="{ placeholder: !form.growCropsText }">
                                {{ form.growCropsText || '请选择种植作物' }}
                            </text>
                            <fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon>
                        </view>
                    </fui-form-item>
                </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" />
        <fui-loading isFixed v-if="pageData.loading" backgroundColor="rgba(0, 0, 0, 0.4)" />
    </view>
</template>

<style lang="scss" scoped>
    .page {
        min-height: 100vh;
        background-color: #f4f7f5;
        font-family: 'DingTalk Sans', sans-serif;
    }

    .form-banner {
        background-color: #5db66f;
        padding: 60rpx 40rpx 100rpx;
        color: #fff;
        .title {
            font-size: 48rpx;
            font-weight: bold;
            display: block;
            letter-spacing: 2rpx;
        }
        .subtitle {
            font-size: 26rpx;
            opacity: 0.9;
            margin-top: 12rpx;
            display: block;
        }
    }

    .form-content {
        padding: 24rpx;
        margin-top: -80rpx;
        position: relative;
        z-index: 10;
    }

    .section-card {
        background-color: #fff;
        border-radius: 28rpx;
        padding: 32rpx;
        margin-bottom: 28rpx;
        box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.03);

        .card-header {
            margin-bottom: 32rpx;
            display: flex;
            align-items: center;
            .line {
                width: 8rpx;
                height: 32rpx;
                background-color: #5db66f;
                border-radius: 4rpx;
                margin-right: 16rpx;
            }
            text {
                font-size: 32rpx;
                font-weight: bold;
                color: #1a1a1a;
            }
        }
    }

    .picker-input {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 20rpx;
        width: 100%;
    }

    .select-text {
        font-size: 28rpx;
        color: #333333;
        flex: 1;
        &.placeholder {
            color: #999999;
        }
    }

    .unit {
        font-size: 26rpx;
        color: #999;
        margin-left: 12rpx;
    }

    .submit-area {
        padding: 60rpx 20rpx 100rpx;
        :deep(.fui-button) {
            background: #5db66f !important;
            border-color: #5db66f !important;
            box-shadow: 0 8rpx 24rpx rgba(93, 182, 111, 0.3);
        }
    }

    :deep(.fui-form) {
        background: transparent;
    }

    :deep(.fui-form__item) {
        background: transparent;
        border: none;
        margin-bottom: 0;
        padding: 0;
    }

    :deep(.fui-input__wrap) {
        padding: 28rpx 0;
    }

    :deep(.fui-input__label) {
        font-size: 28rpx;
        color: #333333;
        font-weight: 400;
        font-family: 'DingTalk Sans', system-ui !important;
    }

    :deep(.fui-input__self) {
        font-size: 28rpx;
        color: #333333;
        font-family: 'DingTalk Sans', system-ui !important;
    }

    :deep(.fui-input__placeholder) {
        color: #d0d0d0;
        font-size: 28rpx;
        font-family: 'DingTalk Sans' !important;
    }

    ::v-deep .uni-input-placeholder {
        font-size: 28rpx !important;
        color: #999999 !important;
        font-family: 'DingTalk Sans' !important;
    }

    :deep(.fui-button) {
        font-family: 'DingTalk Sans' !important;
        font-weight: bold !important;
    }
</style>