<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <el-form-item label="名称" prop="farm_name">
                    <el-input v-model="formData.farm_name" clearable placeholder="请输入名称" />
                </el-form-item>
              <el-form-item label="所属用户" prop="user_id">
                <el-select
                    v-model="formData.user_id"
                    remote
                    filterable
                    placeholder="请输入用户信息"
                    :remote-method="queryUser"
                    :loading="loading"
                >
                  <el-option
                      v-for="(item, index) in optionsData.user"
                      :key="index"
                      :label="item.userinfo"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
                <el-form-item label="养殖基地类型" prop="farm_type">
                    <el-select
                        class="flex-1"
                        v-model="formData.farm_type"
                        clearable
                        placeholder="请选择养殖基地类型"
                    >
                        <el-option
                            v-for="(item, index) in dictData.farm_type"
                            :key="index"
                            :label="item.name"
                            :value="parseInt(item.value)"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="养殖种类" prop="breed_type">
                    <el-select
                        class="flex-1"
                        v-model="formData.breed_type"
                        clearable
                        placeholder="请选择养殖种类"
                    >
                        <el-option
                            v-for="(item, index) in dictData.breed_type"
                            :key="index"
                            :label="item.name"
                            :value="parseInt(item.value)"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="养殖场规模" prop="form_scale">
                    <el-input
                        v-model="formData.form_scale"
                        clearable
                        placeholder="请输入养殖场规模"
                    />
                </el-form-item>
                <el-form-item label="负责人" prop="master">
                    <el-input v-model="formData.master" clearable placeholder="请输入负责人" />
                </el-form-item>
                <el-form-item label="联系方式" prop="master_contact">
                    <el-input
                        v-model="formData.master_contact"
                        clearable
                        placeholder="请输入联系方式"
                    />
                </el-form-item>
                <el-form-item
                    label="省"
                    :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
                    prop="province"
                >
                    <el-select
                        v-model="formData.province"
                        placeholder="请选择省"
                        clearable
                        @change="province_change"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="(item, index) in datas.provinceOptions"
                            :key="index"
                            :label="item.province_name"
                            :value="item.province_code"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="市"
                    :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
                    prop="city"
                >
                    <el-select
                        v-model="formData.city"
                        placeholder="请选择市"
                        clearable
                        @change="city_change"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="(item, index) in datas.cityOptions"
                            :key="index"
                            :label="item.city_name"
                            :value="item.city_code"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="区"
                    :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
                    prop="area"
                >
                    <el-select
                        v-model="formData.area"
                        placeholder="请选择区"
                        clearable
                        @change="area_change"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="(item, index) in datas.areaOptions"
                            :key="index"
                            :label="item.county_name"
                            :value="item.county_code"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="镇"
                    :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
                    prop="street"
                >
                    <el-select
                        v-model="formData.street"
                        placeholder="请选择镇"
                        clearable
                        @change="street_change"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="(item, index) in datas.streetOptions"
                            :key="index"
                            :label="item.town_name"
                            :value="item.town_code"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="村"
                    :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
                    prop="village"
                >
                    <el-select
                        v-model="formData.village"
                        placeholder="请选择村"
                        clearable
                        @change="village_change"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="(item, index) in datas.villageOptions"
                            :key="index"
                            :label="item.village_name"
                            :value="item.village_code"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="队"
                    :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
                    prop="bridge"
                >
                    <el-select
                        v-model="formData.bridge"
                        placeholder="请选择队"
                        clearable
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="(item, index) in datas.brigadeOptions"
                            :key="index"
                            :label="item.group_name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="地址" prop="address">
                    <el-input v-model="formData.address" clearable placeholder="请输入地址" />
                </el-form-item>

                <el-form-item label="图片" prop="pic" class="avatar-uploader">
                              <el-upload
                                  :accept="acceptFileTypes"
                                  v-model="formData.pic"
                                  :data="{ cid: 0 }"
                                  :headers="{ Token: userStore.token }"
                                  :action="action"
                                  :show-file-list="false"
                                  :on-success="handleAvatarSuccessAvatar"
                              >
                                <div class="avatar-uploader-icon">
                                  <img class="avatar" style="width: 200px; height: 130px"
                                       v-if="formData.pic"
                                       :src="formData.pic"
                                  />
                                  <el-icon  v-else >
                                    <Plus />
                                  </el-icon>
                                </div>
                              </el-upload>
<!--                              <template v-for="img in formData.image">-->
<!--                                <img class="avatar" style="width: 200px; height: 130px"-->
<!--                                     v-if="img"-->
<!--                                     :src="img"-->
<!--                                />-->
<!--                              </template>-->

                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="farmEdit">
import type { FormInstance } from 'element-plus'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import Popup from '@/components/popup/index.vue'
import { apiFarmAdd, apiFarmEdit, apiFarmDetail } from '@/api/farm'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import {
    apiAreaList,
    apiBrigadeList,
    apiCityList,
    apiProvinceList,
    apiStreetList,
    apiVillageList
} from '@/api/common'
import { ref } from 'vue'
import config from '@/config'
import useUserStore from '@/stores/modules/user'
import { ElMessage, type UploadProps, type UploadFile } from 'element-plus'
import {useDictOptions} from "@/hooks/useDictOptions";
import {apiFarmLists} from "@/api/fence_house";
import {getUserList} from "@/api/land";
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const acceptFileTypes = ref('.png, .jpg, .jpeg, image/png, image/jpeg')
const action = ref(`${config.baseUrl}${config.urlPrefix}/upload/image`)
const userStore = useUserStore()

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {

    console.log(uploadFile)
    console.log(uploadFiles)
    console.log(formData.pic)
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
const handleDownload = (file: UploadFile) => {
    console.log(file)
}
const handleAvatarSuccessAvatar: UploadProps['onSuccess'] = (response, uploadFile) => {
    if (response.code == 0) {
        ElMessage.error(response.msg)
        return
    }

    formData.pic.push(response.data.uri)
}
// 弹窗标题
const popupTitle = computed(() => {
    if (mode.value == 'edit') {
        getCityList()
        getAreaList()
        getStreetList()
        getVillageList()
        getBrigadeList()
    }
    return mode.value == 'edit' ? '编辑养殖基地' : '新增养殖基地'
})

// 表单数据
const formData = reactive({
    id: '',
    farm_name: '',
    user_id: 0,
    farm_type: '',
    breed_type: '',
    form_scale: '',
    master: '',
    master_contact: '',
    province: '',
    city: '',
    area: '',
    street: '',
    village: '',
    bridge: '',
    address: '',
    pic: [],
    longitude: '',
    latitude: ''
})

// 表单验证
const formRules = reactive<any>({})

const { optionsData } = useDictOptions<{
  user: any[]
}>({
  user: {
    api: getUserList
  }
})

const loading = ref(false)

const queryUser = async (query: string) => {
  loading.value = true
  const userList = await getUserList({
    keyword: query ?? ''
  })
  optionsData.user = userList
  loading.value = false
}

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiFarmDetail({
        id: row.id
    })
    setFormData(data)
}

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData }
    mode.value == 'edit' ? await apiFarmEdit(data) : await apiFarmAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}
const datas = reactive({
    provinceOptions: [],
    cityOptions: [],
    areaOptions: [],
    streetOptions: [],
    villageOptions: [],
    brigadeOptions: []
})
function province_change(value: string) {
    getCityList()
}
function city_change(value: string) {
    getAreaList()
}
function area_change(value: string) {
    getStreetList()
}
function street_change(value: string) {
    getVillageList()
}
function village_change(value: string) {
    getBrigadeList()
}
// function brigade_change(value: string) {
//     formData.brigade = value
// }
const getProvinceList = async () => {
    const data = await apiProvinceList({})
    datas['provinceOptions'] = data
}
const getCityList = async () => {
    const data = await apiCityList({ city: formData.province })
    datas['cityOptions'] = data
}
const getAreaList = async () => {
    const data = await apiAreaList({ area: formData.city })
    datas['areaOptions'] = data
}
const getStreetList = async () => {
    const data = await apiStreetList({ street: formData.area })
    datas['streetOptions'] = data
}
const getVillageList = async () => {
    const data = await apiVillageList({ village: formData.street })
    datas['villageOptions'] = data
}
const getBrigadeList = async () => {
    const data = await apiBrigadeList()
    datas['brigadeOptions'] = data
}
getProvinceList() // 初始化即请求省份数据

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    width: 200px;
    height: 130px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
