<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/modules/user'
import { useGlobSetting } from '/@/hooks/setting'
import * as NongchangAPI from '@/api/model/nongchang'
import AreaPicker from '@/components/AreaPicker/index.vue'
import { useDictStore } from '@/store/modules/dict'

const dictStore = useDictStore()
const userStore = useUserStore()
const globSetting = useGlobSetting()
onLoad((pageOptions) => {
    if (pageOptions.id) {
        uni.setNavigationBarTitle({
            title: '编辑农场',
        })
        pageData.form.id = pageOptions.id;
        NongchangAPI.farmsGet({ id: pageOptions.id }).then((res) => {
            // 将 res 中的数据赋值到 formData 中，key 保持一致
            Object.keys(res).forEach((key) => {
                if (key in pageData.form) {
                    pageData.form[key] = res[key]
                }
            })
            // 回显省市区名称
            if (res.provinceName && res.cityName && res.districtName) {
                pageData.form.provinceName = res.provinceName
                pageData.form.cityName = res.cityName
                pageData.form.districtName = res.districtName
                pageData.form.provinceText = res.provinceName + '/' + res.cityName + '/' + res.districtName
            }
            
            // 编辑模式下，如果已有示例图片，需要设置到上传组件中
            if (res.coverImage) {
                nextTick(() => {
                    // 设置上传组件的初始文件
                    const uploadComponent = uploadRef.value
                    if (uploadComponent) {
                        uploadComponent.clearFiles()
                        // 构造文件对象格式，适配uni-file-picker的数据结构
                        const fileItem = {
                            url: res.coverImage,
                            name: res.coverImage.split('/').pop() || 'image.jpg',
                            extname: res.coverImage.split('.').pop() || 'jpg'
                        }
                        uploadComponent.files.push(fileItem)
                    }
                })
            }
            
            // 编辑模式下，根据字典值获取对应的文本
            // 延迟执行，确保字典数据已加载完成
            nextTick(() => {
                if (res.farmType) {
                    const farmTypeItem = pageData.options.farmType.find(item => item.value == res.farmType)
                    if (farmTypeItem) {
                        pageData.form.farmTypeText = farmTypeItem.text
                    }
                }
                
                if (res.growCrops) {
                    const growCropsItem = pageData.options.mainProducts.find(item => item.value == res.growCrops)
                    if (growCropsItem) {
                        pageData.form.growCropsText = growCropsItem.text
                    }
                }
            })
        })
    }
})
onShow(() => {
    // 数据字典赋值
    initDict()
    pageData.form.userId = userStore.getUserInfo.id
})

const pageData = reactive({
    loading: false,
    show: {
        address: false,
        mainProducts: false,
        farmType: false,
    },
    options: {
        address: [],
        mainProducts: [],
        farmType: [],
    },
    form: {
        id:'',
        userId: '',
        farmName: '',
        farmType: '',
        farmTypeText: '',
        growCrops: '',
        growCropsText: '',
        totalArea: '',
        farmProfiles: '',
        owner: '',
        ownerPhone: '',
        provinceText: '',
        provinceName: '',
        cityName: '',
        districtName: '',
        addressDetail: '',
        coverImage: '',
        slogan: '',
    },
    rules: [
        {
            name: 'farmName',
            rule: ['required'],
            msg: ['请输入农场名称'],
        },
        {
            name: 'farmType',
            rule: ['required'],
            msg: ['请选择农场类型'],
        },
        {
            name: 'growCrops',
            rule: ['required'],
            msg: ['请选择种植物种'],
        },
        {
            name: 'totalArea',
            rule: ['required'],
            msg: ['请输入总面积'],
        },
        {
            name: 'farmProfiles',
            rule: ['required'],
            msg: ['请输入农场简介'],
        },
        {
            name: 'owner',
            rule: ['required'],
            msg: ['请输入农场主姓名'],
        },
        {
            name: 'ownerPhone',
            rule: ['required'],
            msg: ['请输入农场主电话'],
        },
        {
            name: 'provinceName',
            rule: ['required'],
            msg: ['请填写省市区信息！'],
        },
        {
            name: 'cityName',
            rule: ['required'],
            msg: ['请填写省市区信息！'],
        },
        {
            name: 'districtName',
            rule: ['required'],
            msg: ['请填写省市区信息！'],
        },
        {
            name: 'addressDetail',
            rule: ['required'],
            msg: ['请填写详细地址'],
        },
    ],
})

function initDict() {
    pageData.options.mainProducts = dictStore.getDictList.main_business.map((item) => {
        return {
            value: item.value,
            text: item.text,
        }
    })
    pageData.options.farmType = dictStore.getDictList.farm_type.map((item) => {
        return {
            value: item.value,
            text: item.text,
        }
    })
}
function handleAreaConfirm(e) {
    pageData.form.provinceName = e.text[0]
    pageData.form.cityName = e.text[1]
    pageData.form.districtName = e.text[2]
    pageData.form.provinceText = e.fullText
}
function handleChangeFarmType(e) {
    pageData.form.farmType = e.value
    pageData.form.farmTypeText = e.text
    pageData.show.farmType = false
}
function handleChangeGrowCrops(e) {
    pageData.form.growCrops = e.value
    pageData.form.growCropsText = e.text
    pageData.show.mainProducts = false
}
const toastRef = ref()
const uploadRef = ref()
// 文件上传
function handleUpload(file) {
    pageData.loading = true
    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.coverImage = data.message // 保存返回的图片信息
                }
            }
        },
        fail: (err) => {
            toastRef.value.show({
                type: 'error',
                text: '上传失败',
            })
            uploadRef.value.clearFiles()
            pageData.form.coverImage = null
        },
        complete: () => {
            pageData.loading = false
        },
    })
}
// 文件删除
function handleDelete(file) {
    uploadRef.value.clearFiles()
    pageData.form.coverImage = null
}
const formRef = ref()
function submit() {
    formRef.value.validator(pageData.form, pageData.rules, true).then((res) => {
        if (res.isPassed) {
            pageData.loading = true
            
            // 提交前处理：通过对provinceText值按/分隔，分别赋值给provinceName、cityName和districtName
            if (pageData.form.provinceText) {
                const addressParts = pageData.form.provinceText.split('/')
                if (addressParts.length >= 3) {
                    pageData.form.provinceName = addressParts[0]
                    pageData.form.cityName = addressParts[1]
                    pageData.form.districtName = addressParts[2]
                }
            }

             const apiCall = pageData.form.id ? NongchangAPI.farmsEdit : NongchangAPI.farmsAdd
            apiCall(pageData.form)
                .then((res) => {
                    toastRef.value.show({
                        type: 'success',
                        text: pageData.form.id ? '保存修改成功' : '添加农场成功',
                    })
                    
                    // 获取农场ID：编辑时使用当前ID，新增时从返回值获取（假设返回的是ID或包含ID的对象）
                    // 根据后端接口惯例，如果返回的是ID字符串直接使用，如果是对象则取id字段
                    // 暂时假设res为ID或者不影响跳转，优先使用pageData.form.id，如果是新增则尝试从res获取
                    // 如果res不是id，则需要确认接口返回值结构。通常新增接口返回ID比较合理。
                    // 鉴于不确定接口返回值，这里先假设编辑时id已知，新增时尝试从res获取，如果获取不到则回退到列表页
                    
                    const targetId = pageData.form.id || (typeof res === 'string' ? res : res?.id);
                    
                    setTimeout(() => {
                        if (targetId) {
                            // 跳转到农场详情页，注意路径需要是绝对路径
                            uni.redirectTo({
                                url: `/pages/nongchang/detail/index?id=${targetId}`
                            })
                        } else {
                            // 如果没有ID，回退上一页
                            uni.navigateBack()
                        }
                    }, 500);
                })
                .finally(() => {
                    pageData.loading = false
                })
        }
    })
}
</script>

<template>
    <view class="page">
        <view class="page-container">
            <fui-form ref="formRef">
                <!-- 第一组表单 -->
                <view class="form-card">
                    <fui-input
                        required
                        label="农场名称"
                        labelSize="28"
                        size="28"
                        :labelWeight="400"
                        labelWidth="auto"
                        placeholder="请输入农场名称"
                        v-model="pageData.form.farmName"
                    />
                    <fui-form-item
                        required
                        asterisk
                        label="农场类型"
                        labelSize="28"
                        :labelWeight="400"
                        labelWidth="auto"
                    >
                        <view class="time-input" @click="pageData.show.farmType = true">
                            <text class="select-text" :class="{ placeholder: !pageData.form.farmTypeText }">
                                {{ pageData.form.farmTypeText || '请选择农场类型' }}
                            </text>
                        </view>
                    </fui-form-item>
                    <!-- <view class="fui-input-wrapper" @click="pageData.show.farmType = true">
                        <fui-input
                            required
                            readonly
                            label="农场类型"
                            placeholder="请选择农场类型"
                            v-model="pageData.form.farmTypeText"
                            labelSize="28"
                            :labelWeight="400"
                            labelWidth="auto"
                        />
                    </view> -->
                    <fui-input
                        required
                        labelSize="28"
                        size="28"
                        :labelWeight="400"
                        labelWidth="auto"
                        label="农场主姓名"
                        placeholder="请输入农场主姓名"
                        v-model="pageData.form.owner"
                    />
                    <fui-input
                        required
                        type="number"
                        labelSize="28"
                        size="28"
                        :labelWeight="400"
                        labelWidth="auto"
                        label="农场主电话"
                        placeholder="请输入农场主电话"
                        v-model="pageData.form.ownerPhone"
                    />
                    <!-- 农场简介换行显示 -->
                    <view class="form-item-block">
                        <view class="form-item-label required">农场简介</view>
                        <fui-textarea
                            height="100rpx"
                            size="28"
                            :borderTop="false"
                            :borderBottom="false"
                            placeholder="请输入农场简介"
                            v-model="pageData.form.farmProfiles"
                            class="block-textarea"
                        />
                    </view>
                    <!-- 农场标语 -->
                    <view class="form-item-block">
                        <view class="form-item-label">农场标语</view>
                        <fui-textarea
                            height="100rpx"
                            size="28"
                            :borderTop="false"
                            :borderBottom="false"
                            placeholder="请输入农场标语"
                            v-model="pageData.form.slogan"
                            class="block-textarea"
                        />
                    </view>
                </view>

                <!-- 第二组表单 -->
                <view class="form-card">
                    <fui-form-item
                        required
                        asterisk
                        label="归属地区"
                        labelSize="28"
                        :labelWeight="400"
                        labelWidth="auto"
                    >
                        <view class="time-input" @click="pageData.show.address = true">
                            <text class="select-text" :class="{ placeholder: !pageData.form.provinceText }">
                                {{ pageData.form.provinceText || '请选择归属地区' }}
                            </text>
                        </view>
                    </fui-form-item>
                    <!-- <view class="fui-input-wrapper" @click="pageData.show.address = true">
                        <fui-input
                            required
                            readonly
                            labelWidth="auto"
                            labelSize="28"
                            :labelWeight="400"
                            label="归属地区"
                            placeholder="请选择归属地区"
                            :value="pageData.form.provinceText"
                        />
                    </view> -->
                    <fui-input
                        required
                        labelWidth="auto"
                        labelSize="28"
                        :labelWeight="400"
                        size="28"
                        label="详细地址"
                        placeholder="请输入详细地址"
                        v-model="pageData.form.addressDetail"
                    />
                    <fui-form-item
                        required
                        asterisk
                        label="种植物种"
                        labelSize="28"
                        :labelWeight="400"
                        labelWidth="auto"
                    >
                        <view class="time-input" @click="pageData.show.mainProducts = true">
                            <text class="select-text" :class="{ placeholder: !pageData.form.growCropsText }">
                                {{ pageData.form.growCropsText || '请选择种植物种' }}
                            </text>
                        </view>
                    </fui-form-item>
                    <!-- <view class="fui-input-wrapper" @click="pageData.show.mainProducts = true">
                        <fui-input
                            required
                            readonly
                            labelWidth="auto"
                            labelSize="28"
                            :labelWeight="400"
                            label="种植物种"
                            placeholder="请选择种植物种"
                            v-model="pageData.form.growCropsText"
                        />
                    </view> -->
                    <fui-input
                        required
                        size="28"
                        labelWidth="auto"
                        labelSize="28"
                        :labelWeight="400"
                        label="总面积 (亩)"
                        placeholder="请输入总面积"
                        v-model="pageData.form.totalArea"
                    />
                </view>

                <!-- 第三组表单 - 图片上传 -->
                <view class="form-card">
                    <!-- 上传图片换行显示 -->
                    <view class="form-item-block">
                        <view class="form-item-label required">示例图片</view>
                        <view class="block-upload">
                            <uni-file-picker
                                ref="uploadRef"
                                limit="1"
                                :auto-upload="false"
                                @select="handleUpload"
                                @delete="handleDelete"
                            />
                        </view>
                    </view>
                </view>

                <view class="submit-btn-box">
                    <fui-button :text="pageData.form.id ? '保存修改' : '添加'" bold radius="96rpx" @click="submit" />
                </view>
            </fui-form>
        </view>

        <fui-picker
            :show="pageData.show.farmType"
            :layer="1"
            :linkage="true"
            :options="pageData.options.farmType"
            @change="handleChangeFarmType"
            @cancel="pageData.show.farmType = false"
        />
        <fui-picker
            :show="pageData.show.mainProducts"
            :layer="1"
            :linkage="true"
            :options="pageData.options.mainProducts"
            @change="handleChangeGrowCrops"
            @cancel="pageData.show.mainProducts = false"
        />
        <AreaPicker v-model:show="pageData.show.address" :layer="3" title="选择归属地区" @confirm="handleAreaConfirm" />

        <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 {
    background: #e8f5e9;
    min-height: 100vh;
}

.page-container {
    padding: 28rpx;
}

.form-card {
    background-color: #ffffff;
    border-radius: 20rpx;
    margin-bottom: 20rpx;
    padding: 0;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.upload-title {
    padding: 28rpx;
    font-size: 28rpx;
    color: #333333;
    font-weight: 400;
}

.upload-content {
    padding: 0 32rpx 32rpx;
}

.submit-btn-box {
    padding: 32rpx 0;
}

:deep(.fui-button) {
    border-color: #ff9800 !important;
    background: #ff9800 !important;
}

:deep(.fui-input__wrap),
:deep(.fui-textarea__wrap) {
    padding: 28rpx 32rpx;
    // border-bottom: 1px solid #e5e5e5;
}

:deep(.fui-input__label),
:deep(.fui-textarea__label) {
    font-size: 28rpx;
    color: #333333;
    min-width: 160rpx;
    font-weight: 400;
}

:deep(.fui-input__self),
:deep(.fui-textarea__self) {
    font-size: 28rpx;
    color: #333333;
}

:deep(.fui-input__placeholder),
:deep(.fui-textarea__placeholder) {
    color: #d0d0d0;
    font-size: 28rpx;
}

.form-card :deep(.fui-input__wrap:last-child),
.form-card :deep(.fui-textarea__wrap:last-child) {
    border-bottom: none;
}

::v-deep .uni-input-placeholder {
    font-size: 28rpx !important;
    color: #999999 !important;
}
:deep(.uni-textarea-placeholder) {
    font-size: 28rpx !important;
    color: #999999 !important;
}
:deep(.fui-button) {
    width: 690rpx;
    border-color: #5db66f !important;
    background: #5db66f !important;
}

// 移除fui-form的默认样式
:deep(.fui-form) {
    background: transparent;
}

:deep(.fui-form__item) {
    background: transparent;
    border: none;
    margin-bottom: 0;
    padding: 0;
}
:deep(.fui-input__border-bottom) {
    right: 32rpx !important;
}
.form-item-block {
    padding: 24rpx 12rpx;
    // border-bottom: 1px solid #e5e5e5;

    &:last-child {
        border-bottom: none;
    }
}

.form-item-label {
    font-size: 28rpx;
    color: #333333;
    font-weight: 400;
    margin-bottom: 20rpx;

    &.required::before {
        content: '*';
        color: #ff4d4f;
        margin-right: 8rpx;
    }
}

.block-textarea {
    width: 100%;
    padding: 0rpx 12rpx !important;
}

.block-upload {
    width: 100%;
    padding: 0 20rpx;
    :deep(.uni-file-picker__container) {
        background-color: #fff !important;
        border: unset !important;
        border-radius: 16rpx;
        min-height: 200rpx;
        display: flex;
        justify-content: left !important;
    }
}
.select-text {
    font-size: 28rpx;
    color: #333333;
    padding: 0 20rpx;
    &.placeholder {
        color: #999999;
    }
}

.fui-input-wrapper {
    cursor: pointer;
}
</style>
