<script setup lang="ts">
    import { reactive, toRefs } 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 { areaTree } from '@/utils/areaData'
    import { useDictStore } from '@/store/modules/dict'

    const dictStore = useDictStore()
    const userStore = useUserStore()
    const globSetting = useGlobSetting()

    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: {
            userId: '',
            farmName: '',
            title: '',
            farmType: '',
            farmTypeText: '',
            contactPhone: '',
            contactPerson: '',
            description: '',
            address: '',
            provinceName: '',
            cityName: '',
            districtName: '',
            addressDetail: '',
            mainBusiness: '',
            mainProducts: '',
            mainProductsText: '',
            totalArea: '',
            coverImage: '',
        },
        rules: [
            {
                name: 'farmName',
                rule: ['required'],
                msg: ['请输入农场名称'],
            },
            {
                name: 'title',
                rule: ['required'],
                msg: ['请输入农场类型'],
            },
            {
                name: 'farmType',
                rule: ['required'],
                msg: ['请选择农场类型'],
            },
            {
                name: 'contactPhone',
                rule: ['required'],
                msg: ['请输入联系电话'],
            },
            {
                name: 'contactPerson',
                rule: ['required'],
                msg: ['请输入联系人'],
            },
            {
                name: 'description',
                rule: ['required'],
                msg: ['请输入农场简介'],
            },
            {
                name: 'address',
                rule: ['required'],
                msg: ['请选择农场地址'],
            },
            {
                name: 'addressDetail',
                rule: ['required'],
                msg: ['请填写详细地址'],
            },
            {
                name: 'mainBusiness',
                rule: ['required'],
                msg: ['请填写主要业务'],
            },
            {
                name: 'mainProducts',
                rule: ['required'],
                msg: ['请选择主要产品'],
            },
            {
                name: 'totalArea',
                rule: ['required'],
                msg: ['请输入农场面积'],
            },
        ],
    })

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

    function initDict() {
        pageData.options.address = areaTree
        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 handleChangeFarmType(e) {
        pageData.form.farmType = e.value
        pageData.form.farmTypeText = e.text
        pageData.show.farmType = false
    }
    function handleChangeMainProducts(e) {
        pageData.form.mainProducts = e.value
        pageData.form.mainProductsText = e.text
        pageData.show.mainProducts = false
    }
    function handleChangeAddress(e) {
        pageData.form.address = e.text.join('/')
        pageData.form.provinceName = e.text[0]
        pageData.form.cityName = e.text[1]
        pageData.form.districtName = e.text[2]
        pageData.show.address = 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
                NongchangAPI.farmsAdd(pageData.form)
                    .then(() => {
                        toastRef.value.show({
                            type: 'success',
                            text: '添加农场成功',
                        })
                        uni.switchTab({
                            url: '/pages/mine/index',
                        })
                    })
                    .finally(() => {
                        pageData.loading = false
                    })
            }
        })
    }
</script>

<template>
    <fui-form ref="formRef">
        <fui-input required label="农场名称" placeholder="请输入农场名称" v-model="form.farmName"></fui-input>
        <fui-input required label="农场标语" placeholder="请输入农场标语" v-model="form.title"></fui-input>
        <fui-input
            required
            label="农场类型"
            placeholder="请选择农场类型"
            v-model="form.farmTypeText"
            @click="show.farmType = true"
        ></fui-input>
        <fui-input required label="联系人" placeholder="请输入联系人" v-model="form.contactPerson"></fui-input>
        <fui-input required label="联系电话" placeholder="请输入联系电话" v-model="form.contactPhone"></fui-input>
        <fui-textarea
            required
            label="农场描述"
            placeholder="请输入农场描述"
            v-model="pageData.form.description"
        ></fui-textarea>
        <fui-input
            required
            label="地区"
            placeholder="请选择地区"
            v-model="form.address"
            @click="show.address = true"
        ></fui-input>
        <fui-input required label="详细地址" placeholder="请输入详细地址" v-model="form.addressDetail"></fui-input>
        <fui-input
            required
            label="主营业务"
            borderTop
            placeholder="请输入主营业务"
            v-model="form.mainBusiness"
        ></fui-input>
        <fui-input
            required
            label="主要产品"
            borderTop
            placeholder="请选择主要产品"
            v-model="form.mainProductsText"
            @click="show.mainProducts = true"
        ></fui-input>
        <fui-input
            required
            label="总面积(亩)"
            borderTop
            placeholder="请输入总面积"
            v-model="form.totalArea"
        ></fui-input>
        <view class="bg-white" style="padding: 0.875rem 0.35rem">
            <view class="mb-1 flex justify-start"> 封面图片 </view>
            <uni-file-picker
                ref="uploadRef"
                limit="1"
                :auto-upload="false"
                @select="handleUpload"
                @delete="handleDelete"
            ></uni-file-picker>
        </view>
        <view class="fui-btn__box bg-white p-4">
            <fui-button text="添加农场" bold radius="96rpx" @click="submit"></fui-button>
        </view>
    </fui-form>

    <fui-picker
        :show="show.farmType"
        :layer="1"
        :linkage="true"
        :options="options.farmType"
        @change="handleChangeFarmType"
        @cancel="show.farmType = false"
    ></fui-picker>
    <fui-picker
        :show="show.mainProducts"
        :layer="1"
        :linkage="true"
        :options="options.mainProducts"
        @change="handleChangeMainProducts"
        @cancel="show.mainProducts = false"
    ></fui-picker>
    <fui-picker
        :show="show.address"
        :options="options.address"
        :linkage="true"
        :layer="3"
        @change="handleChangeAddress"
        @cancel="show.address = false"
    ></fui-picker>

    <fui-toast ref="toastRef"></fui-toast>
    <fui-loading isFixed v-if="pageData.loading" backgroundColor="rgba(0, 0, 0, 0.4)"></fui-loading>
</template>

<style lang="scss" scoped>
    :deep(.fui-button) {
        border-color: #ff9800 !important;
        background: #ff9800 !important;
    }
</style>
