<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) => {
            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()
                        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
    if (!pageData.form.id) {
        pageData.form.ownerPhone = userStore.getUserInfo?.phone || ''
    }
})

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: ['请填写详细地址'],
        },
    ],
})

const isEditMode = computed(() => !!pageData.form.id)

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`,
        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
            
            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 ? '保存修改成功' : '添加农场成功',
                    })
                    
                    const targetId = pageData.form.id || (typeof res === 'string' ? res : res?.id);
                    
                    setTimeout(() => {
                        if (targetId) {
                            uni.redirectTo({
                                url: `/pages/nongchang/detail/index?id=${targetId}`
                            })
                        } else {
                            uni.navigateBack()
                        }
                    }, 500);
                })
                .finally(() => {
                    pageData.loading = false
                })
        }
    })
}
</script>

<template>
    <view class="page">
        <view class="form-banner">
            <text class="title">{{ isEditMode ? '编辑农场' : '添加农场' }}</text>
            <text class="subtitle">{{ isEditMode ? '修改农场信息，完善经营资料' : '创建您的农场档案，开启智慧管理' }}</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
                        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="picker-input" @click="pageData.show.farmType = true">
                            <text class="select-text" :class="{ placeholder: !pageData.form.farmTypeText }">
                                {{ pageData.form.farmTypeText || '请选择农场类型' }}
                            </text>
                            <fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon>
                        </view>
                    </fui-form-item>
                    <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"
                        readonly
                        disabled
                    />
                    <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"
                            background="#f9f9f9"
                            radius="16"
                            :padding="['24rpx','24rpx']"
                        />
                    </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"
                            background="#f9f9f9"
                            radius="16"
                            :padding="['24rpx','24rpx']"
                        />
                    </view>
                </view>

                <view class="section-card">
                    <view class="card-header">
                        <view class="line"></view>
                        <text>经营区域信息</text>
                    </view>
                    <fui-form-item
                        required
                        asterisk
                        label="归属地区"
                        labelSize="28"
                        :labelWeight="400"
                        labelWidth="auto"
                    >
                        <view class="picker-input" @click="pageData.show.address = true">
                            <text class="select-text" :class="{ placeholder: !pageData.form.provinceText }">
                                {{ pageData.form.provinceText || '请选择归属地区' }}
                            </text>
                            <fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon>
                        </view>
                    </fui-form-item>
                    <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="picker-input" @click="pageData.show.mainProducts = true">
                            <text class="select-text" :class="{ placeholder: !pageData.form.growCropsText }">
                                {{ pageData.form.growCropsText || '请选择种植物种' }}
                            </text>
                            <fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon>
                        </view>
                    </fui-form-item>
                    <fui-input
                        required
                        size="28"
                        labelWidth="auto"
                        labelSize="28"
                        :labelWeight="400"
                        label="总面积 (亩)"
                        placeholder="请输入总面积"
                        v-model="pageData.form.totalArea"
                    />
                </view>

                <view class="section-card">
                    <view class="card-header">
                        <view class="line"></view>
                        <text>农场展示图片</text>
                    </view>
                    <view class="form-item-block">
                        <view class="form-item-label required">示例图片</view>
                        <view class="upload-tips">建议上传农场实景照片，展示农场风貌</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-area">
                    <fui-button :text="pageData.form.id ? '保存修改' : '添加农场'" bold radius="100rpx" @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 {
    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;
        }
    }
}

.form-item-block {
    padding: 24rpx 0;

    &: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;
    }
}

.upload-tips {
    font-size: 22rpx;
    color: #ccc;
    margin-bottom: 20rpx;
}

.block-textarea {
    width: 100%;
}

.block-upload {
    width: 100%;
    :deep(.uni-file-picker__container) {
        background-color: #fff !important;
        border: unset !important;
        border-radius: 16rpx;
        min-height: 200rpx;
        display: flex;
        justify-content: left !important;
    }
}

.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;
    }
}

.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),
:deep(.fui-textarea__wrap) {
    padding: 28rpx 0;
}

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

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

:deep(.fui-input__placeholder),
:deep(.fui-textarea__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(.uni-textarea-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>