<template>
    <view class="container">
        <u-form :model="formData" :rules="rules" ref="formRef" label-width="160rpx">
            <!-- 基地基本信息 -->
            <view class="section-title">基地基本信息</view>

            <u-form-item label="基地名称" prop="baseName" required>
                <u-input v-model="formData.baseName" placeholder="请输入基地名称" border="bottom" />
            </u-form-item>

            <u-form-item label="基地类型" prop="baseType" required class="clickable" @click="show.farmType = true">
                <view class="address-display">
                    <text :class="{'placeholder-text': !formData.baseTypeText}">
                        {{ formData.baseTypeText || '请选择基地类型' }}
                    </text>
                </view>
            </u-form-item>

            <u-form-item label="规模" prop="scale" required>
                <u-input v-model="formData.scale" placeholder="请输入规模（亩）" border="bottom" type="number">
                    <template #suffix>
                        <text class="suffix-text">亩</text>
                    </template>
                </u-input>
            </u-form-item>

            <!-- 地址信息 -->
            <view class="section-title">地址信息</view>

            <u-form-item label="省市区" prop="province" required class="clickable" @click="show.address = true">
                <view class="address-display">
                    <text :class="{'placeholder-text': !formData.province}">
                        {{ formData.province || '请选择省市区' }}
                    </text>
                </view>
            </u-form-item>

            <u-form-item label="详细地址" prop="detailedAddress" required>
                <u-input v-model="formData.detailedAddress" placeholder="请输入详细地址" border="bottom" />
            </u-form-item>

            <!-- 负责人信息 -->
            <view class="section-title">负责人信息</view>

            <u-form-item label="负责人姓名" prop="managerName" required>
                <u-input v-model="formData.managerName" placeholder="请输入负责人姓名" border="bottom" />
            </u-form-item>

            <u-form-item label="联系电话" prop="contactPhone" required>
                <u-input v-model="formData.contactPhone" placeholder="请输入联系电话" border="bottom" type="number" />
            </u-form-item>

            <u-form-item label="身份证号" prop="idCard" required>
                <u-input v-model="formData.idCard" placeholder="请输入身份证号" border="bottom" />
            </u-form-item>

            <!-- 经营信息 -->
            <view class="section-title">经营信息</view>

            <u-form-item label="种植作物" prop="plantedCrops" required>
                <u-input v-model="formData.plantedCrops" placeholder="请输入种植作物，多个用逗号分隔" border="bottom" />
            </u-form-item>

            <u-form-item label="经营年限" prop="operationYears" required>
                <u-input v-model="formData.operationYears" placeholder="请输入经营年限" border="bottom" type="number">
                    <template #suffix>
                        <text class="suffix-text">年</text>
                    </template>
                </u-input>
            </u-form-item>

            <!-- 基地图片 -->
            <view class="section-title">认证材料</view>
            <u-form-item label="基地图片" prop="baseImages">
                <u-upload :fileList="formData.baseImages" @afterRead="(e) => afterRead(e, 'baseImages')"
                    @delete="(e) => deletePic(e, 'baseImages')" name="1" multiple :maxCount="5"
                    :previewFullImage="true"></u-upload>

            </u-form-item>
            <u-form-item label="身份证明" prop="identityProveUrl" required>
                <div>
                    <u-upload :fileList="formData.identityProveUrl" @afterRead="(e) => afterRead(e, 'identityProveUrl')"
                        @delete="(e) => deletePic(e, 'identityProveUrl')" name="identityProveUrl" multiple :maxCount="2"
                        :previewFullImage="true"></u-upload>
                    <div><i>身份证/营业执照图片</i></div>
                </div>
            </u-form-item>
            <u-form-item label="场地证明" prop="landProveUrl" required>
                <div>
                    <u-upload :fileList="formData.landProveUrl" @afterRead="(e) => afterRead(e, 'landProveUrl')"
                        @delete="(e) => deletePic(e, 'landProveUrl')" name="landProveUrl" multiple :maxCount="2"
                        :previewFullImage="true"></u-upload>
                    <div><i>土地合同/场地照片</i></div>
                </div>

            </u-form-item>
            <u-form-item label="生产证明" prop="productionProveUrl" required>
                <div>
                    <u-upload :fileList="formData.productionProveUrl"
                        @afterRead="(e) => afterRead(e, 'productionProveUrl')"
                        @delete="(e) => deletePic(e, 'productionProveUrl')" name="productionProveUrl" multiple
                        :maxCount="2" :previewFullImage="true"></u-upload>
                    <div><i>现场作业照片/产品照片</i></div>
                </div>

            </u-form-item>
            <u-form-item label="质量证书">
                <div>
                    <u-upload :fileList="formData.qualityCertificateUrl"
                        @afterRead="(e) => afterRead(e, 'qualityCertificateUrl')"
                        @delete="(e) => deletePic(e, 'qualityCertificateUrl')" name="qualityCertificateUrl" multiple
                        :maxCount="2" :previewFullImage="true"></u-upload>
                    <div><i>质量认证证书</i></div>
                </div>

            </u-form-item>
            <u-form-item label="其他材料">
                <div>
                    <u-upload :fileList="formData.otherMaterialUrl" @afterRead="(e) => afterRead(e, 'otherMaterialUrl')"
                        @delete="(e) => deletePic(e, 'otherMaterialUrl')" name="otherMaterialUrl" multiple :maxCount="2"
                        :previewFullImage="true"></u-upload>
                    <div><i>其他补充材料</i></div>
                </div>

            </u-form-item>
            <!-- 提交按钮 -->
            <view class="submit-btn-container">
                <u-button type="primary" @click="submitForm" :loading="loading">提交</u-button>
            </view>
        </u-form>
        <fui-picker :show="show.address" :options="options.address" :linkage="true" :layer="3"
            @change="handleChangeAddress" @cancel="show.address = false"></fui-picker>
        <fui-picker :show="show.farmType" :layer="1" :linkage="true" :options="options.farmType"
            @change="handleChangeFarmType" @cancel="show.farmType = false"></fui-picker>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { areaTree } from '@/utils/areaData'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/modules/user'
import { useGlobSetting } from '/@/hooks/setting'
import { useDictStore } from '@/store/modules/dict'
import * as NongchangAPI from '@/api/model/nongchang'
import { useFarmStore } from '@/store/modules/farm'
const dictStore = useDictStore()
// 表单引用
const formRef = ref()
const loading = ref(false)
const show = reactive({
    address: false,
    farmType: false,
})
const options = reactive({
    address: areaTree,
    farmType: []
})
// 表单数据
const formData = reactive({
    farmId: '',
    baseName: '',
    baseType: '',
    baseTypeText: '',
    scale: '',
    provinceName: '',
    cityName: '',
    districtName: '',
    detailedAddress: '',
    province: '',
    managerName: '',
    contactPhone: '',
    idCard: '',
    plantedCrops: '',
    operationYears: '',
    baseImages: [],
    identityProveUrl: [],//身份证明(身份证/营业执照图片)
    landProveUrl: [],//土地证明(土地证/国有土地使用证)
    productionProveUrl: [],//生产证明(生产许可证/种养许可证)
    qualityCertificateUrl: [],//质量证明(质量认证证书)
    otherMaterialUrl: [],//其他证明(其他证明)
})

// 表单验证规则
const rules = {
    baseName: [
        { required: true, message: '请输入基地名称', trigger: 'blur' },
        { min: 2, max: 50, message: '基地名称长度在2-50个字符之间', trigger: 'blur' }
    ],
    baseType: [
        { required: true, message: '请选择基地类型', trigger: 'change' }
    ],
    scale: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (!value || value === '') {
                    callback(new Error('请输入规模'))
                } else if (!/^[1-9]\d*$/.test(value.toString())) {
                    callback(new Error('规模必须为正整数'))
                } else {
                    callback()
                }
            },
            trigger: ['blur', 'change']
        }
    ],
    province: [
        {
            required: true, message: '请获取地址信息', trigger: 'change',
            // validator: () => formData.provinceName && formData.cityName && formData.districtName
        }
    ],
    detailedAddress: [
        { required: true, message: '请输入详细地址', trigger: 'blur' },
        { min: 5, max: 200, message: '详细地址长度在5-200个字符之间', trigger: 'blur' }
    ],
    managerName: [
        { required: true, message: '请输入负责人姓名', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5]{2,10}$/, message: '姓名必须为2-10个汉字', trigger: 'blur' }
    ],
    contactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    idCard: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        {
            pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: '请输入正确的身份证号码', trigger: 'blur'
        }
    ],
    plantedCrops: [
        { required: true, message: '请输入种植作物', trigger: 'blur' },
        { min: 2, max: 100, message: '种植作物长度在2-100个字符之间', trigger: 'blur' }
    ],
    operationYears: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (value && !/^[1-9]\d*$/.test(value.toString())) {
                    callback(new Error('经营年限必须为正整数'))
                } else {
                    callback()
                }
            },
            message: '经营年限必须为正整数',
            trigger: ['blur', 'change']
        }
    ],
    identityProveUrl: [
        { required: true, message: '请上传身份证明', trigger: 'change', type: 'array' }
    ],
    landProveUrl: [
        { required: true, message: '请上传场地证明', trigger: 'change', type: 'array' }
    ],
    productionProveUrl: [
        { required: true, message: '请上传生产证明', trigger: 'change', type: 'array' }
    ]
}
function handleChangeFarmType(e) {
    formData.baseType = e.value
    formData.baseTypeText = e.text
    show.farmType = false
}
function handleChangeAddress(e) {
    formData.province = e.result;
    formData.provinceName = e.text[0];
    formData.cityName = e.text[1];
    formData.districtName = e.text[2];
    show.address = false
}

const userStore = useUserStore()
const globSetting = useGlobSetting()
const toastRef = ref()
// 文件上传
function afterRead(event, key) {
    // 获取上传的文件列表
    const files = event.file

    // 如果没有文件，直接返回
    if (!files || files.length === 0) return

    // 记录成功上传的数量
    let successCount = 0
    let totalCount = files.length

    // 遍历所有文件进行上传
    files.forEach((file) => {
        uni.uploadFile({
            url: globSetting.apiUrl + globSetting.urlPrefix + '/sys/common/upload', // 直接使用上传接口URL
            filePath: file.url,
            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) {
                        successCount++
                        formData[key].push(data.message)

                        // 所有文件上传完成
                        if (successCount === totalCount) {
                            toastRef.value.show({
                                type: 'success',
                                text: `成功上传${successCount}张图片`,
                            })
                        }
                    }
                }
            },
            fail: () => {
                toastRef.value.show({
                    type: 'error',
                    text: '部分图片上传失败',
                })
            },
        })
    })
}
// 删除图片
const deletePic = (event: any, key) => {
    formData[key].splice(event.index, 1)
}

// 提交表单
const submitForm = async () => {
    try {
        // 先进行表单验证
        const valid = await formRef.value.validate()
        if (!valid) {
            return
        }

        loading.value = true

        // 准备提交数据
        const submitData = { ...formData }

        // 将数组字段转换为逗号分隔的字符串
        const arrayFields = [
            'baseImages',
            'identityProveUrl',
            'landProveUrl',
            'productionProveUrl',
            'qualityCertificateUrl',
            'otherMaterialUrl'
        ]

        arrayFields.forEach(field => {
            if (Array.isArray(submitData[field])) {
                submitData[field] = submitData[field].filter(item => item?.trim()).join(',')
            }
        })

        // 根据是否有ID决定调用编辑还是新增接口
        const apiCall = submitData.id ? NongchangAPI.editFarmbase : NongchangAPI.addFarmbase

        try {
            await apiCall(submitData)

            uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 1500
            })

            // 延迟返回上一页
            setTimeout(() => {
                uni.navigateBack()
            }, 1500)

        } catch (error) {
            console.error('API调用失败:', error)
            uni.showToast({
                title: error.message || '提交失败，请重试',
                icon: 'none',
                duration: 2000
            })
        } finally {
            loading.value = false
        }

    } catch (error) {
        console.log('表单验证失败:', error)
        loading.value = false
        uni.showToast({
            title: '请完善表单信息',
            icon: 'none',
            duration: 2000
        })
    }
}
const farmStore = useFarmStore()
onLoad((pageOptions) => {
    // 页面加载时的初始化操作
    const farmInfo = farmStore.getFarm
    if (farmInfo) {
        formData.farmId = farmInfo.id
    }
    // 修复：修改页面上定义的 options 对象中的 farmType
    options.farmType = dictStore.getDictList['farm_type'].map((item) => {
        return {
            value: item.value,
            text: item.text,
        }
    })
    if (pageOptions.id) {
        NongchangAPI.getFarmbaseInfoById({ id: pageOptions.id }).then(res => {
            if (res) {
                // 将 res 中的数据赋值到 formData 中，key 保持一致
                Object.keys(res).forEach(key => {
                    if (key in formData) {
                        // 如果是数组类型的字段且返回的是字符串，需要转换为数组
                        if (['baseImages', 'identityProveUrl', 'landProveUrl', 'productionProveUrl', 'qualityCertificateUrl', 'otherMaterialUrl'].includes(key) &&
                            typeof res[key] === 'string') {
                            formData[key] = res[key].split(',').filter(item => item.trim() !== '')
                        } else {
                            formData[key] = res[key]
                        }
                    }
                })
                formData.id = res.id
                formData.province = res.provinceName + res.cityName + res.districtName
                // 根据 res.baseType 的值从 options.farmType 中查找对应的文本
                if (res.baseType && options.farmType.length > 0) {
                    const foundItem = options.farmType.find((item: any) => item.value === res.baseType)
                    if (foundItem) {
                        formData.baseTypeText = foundItem.text
                    }
                }

                // 数据赋值完成后，延迟触发表单验证更新
                setTimeout(() => {
                    if (formRef.value) {
                        // 逐个验证可能存在问题的字段
                        formRef.value.validateField('scale')
                        formRef.value.validateField('operationYears')
                        // 重新验证整个表单
                        formRef.value.validate()
                    }
                }, 200)
            }
        })
    }
})
</script>

<style lang="scss" scoped>
.container {
    padding: 30rpx;
    background-color: #f8f9fa;
    min-height: 100vh;
}

.section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin: 40rpx 0 20rpx 0;
    padding-left: 20rpx;
    border-left: 6rpx solid #5DB66F;
}

.address-display {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12rpx 18rpx;
    background-color: transparent;
    border-bottom: 2rpx solid #e4e7ed;
    border-radius: 0;
    cursor: pointer;
    width: 100%;
    
    text {
        flex: 1;
        font-size: 28rpx;
        color: #333;
    }

    .placeholder-text {
        color: #c0c4cc;
    }
}

.suffix-text {
    color: #909399;
    margin-left: 10rpx;
}

.submit-btn-container {
    margin: 60rpx 0;

    ::v-deep .u-button {
        height: 88rpx;
        border-radius: 44rpx;
        font-size: 32rpx;
        background-color: #5DB66F;
        border-color: #5DB66F;
    }
}

// uview-plus 表单样式调整
::v-deep .u-form-item {
    margin-bottom: 40rpx;

    .u-form-item__body {
        padding: 0;
        align-items: flex-start;
    }

    .u-form-item__body__left__content__label {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        width: 160rpx;
        flex-shrink: 0;
        text-align: right;
        padding-right: 20rpx;
        line-height: 80rpx;
    }

    .u-form-item__body__right {
        flex: 1;
        min-width: 0;
    }
}

::v-deep .u-form-item__body__left__content__required {
    position: static;
    padding-right: 10rpx;
}

// 输入框样式优化 - 只保留下面的线
::v-deep .u-input {
    .u-input__content {
        padding: 0;

        .u-input__content__field-wrapper {
            border: none;
            // border-bottom: 2rpx solid #e4e7ed;
            border-radius: 0;

            .u-input__content__field-wrapper__field {
                font-size: 28rpx;
                // padding: 20rpx 0;
                height: auto;
                // min-height: 80rpx;
            }

            .u-input__content__field-wrapper__placeholder {
                color: #c0c4cc;
                font-size: 28rpx;
            }
        }

        &.u-input--focus {
            .u-input__content__field-wrapper {
                border-bottom-color: #5DB66F;
            }
        }
    }
}

// 上传组件样式调整
::v-deep .u-upload {
    margin-top: 10rpx;

    .u-upload__wrap {
        padding: 0;
    }
}

// 选择器输入框样式
::v-deep .u-input--readonly {
    .u-input__content__field-wrapper {
        background-color: transparent;

        .u-input__content__field-wrapper__field {
            color: #333;
        }
    }
}

// 表单项点击区域样式
::v-deep .u-form-item {
    &.clickable {
        cursor: pointer;
        
        .u-form-item__body__right {
            position: relative;
            
            &:after {
                content: '';
                position: absolute;
                top: 0;
                left: -20rpx;
                right: -20rpx;
                bottom: 0;
            }
        }
    }
}
</style>
