<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="土地ID" prop="land_id">
    <el-select
        v-model="formData.land_id"
        filterable
        remote
        reserve-keyword
        placeholder="请输入用户信息"
        :remote-method="queryLand"
        :loading="loading"
      >
        <el-option
          v-for="item in landOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
</el-form-item>
                <el-form-item label="种植种类" prop="kind">
    <el-input v-model="formData.kind" clearable placeholder="请输入种植种类" />
</el-form-item>
                <el-form-item label="种植品牌" prop="breed">
    <el-input v-model="formData.breed" clearable placeholder="请输入种植品牌" />
</el-form-item>
                <el-form-item label="种植面积" prop="area">
    <el-input v-model="formData.area" clearable placeholder="请输入种植面积" />
</el-form-item>
                <el-form-item label="种植人员" prop="user">
    <el-input v-model="formData.user" clearable placeholder="请输入种植人员" />
</el-form-item>
                <el-form-item label="备注信息" prop="remark">
    <el-input v-model="formData.remark" clearable placeholder="请输入备注信息" />
</el-form-item>
                <el-form-item label="生长状态" prop="status">
    <el-select class="flex-1" v-model="formData.status" clearable placeholder="请选择生长状态">
        <el-option 
            v-for="(item, index) in dictData.plant_status"
            :key="index" 
            :label="item.name"
            :value="parseInt(item.value)"
        />
    </el-select>
</el-form-item>
                <!-- <el-form-item label="种植图片" prop="pic">
    <material-picker v-model="formData.pic" :limit="4" />
</el-form-item> -->
                <el-form-item label="播种时间" prop="plant_date">
    <el-date-picker 
        class="flex-1 !flex"
        v-model="formData.plant_date"
        clearable
        type="datetime"
        value-format="YYYY-MM-DD HH:mm:ss"
        placeholder="选择播种时间">
    </el-date-picker>
</el-form-item>

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

<script lang="ts" setup name="landPlantEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiLandPlantAdd, apiLandPlantEdit, apiLandPlantDetail, apiLandLists, getUserList } from '@/api/land_plant'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
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 popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑土地种植' : '新增土地种植'
})

// 表单数据
const formData = reactive({
    id: '',
    land_id: '',
    kind: '',
    breed: '',
    area: '',
    user: '',
    remark: '',
    status: '',
    qr_code: '',
    plant_date: ''
})


// 表单验证
const formRules = reactive<any>({
    land_id: [{
        required: true,
        message: '请输入土地id',
        trigger: ['blur']
    }],
    kind: [{
        required: true,
        message: '请输入种植种类',
        trigger: ['blur']
    }],
    breed: [{
        required: true,
        message: '请输入种植品牌',
        trigger: ['blur']
    }],
    area: [{
        required: true,
        message: '请输入种植面积',
        trigger: ['blur']
    }],
    user: [{
        required: true,
        message: '请输入种植人员',
        trigger: ['blur']
    }],
    plant_date: [{
        required: true,
        message: '请选择播种时间',
        trigger: ['blur']
    }],
})


// 获取详情
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]
            if (key == 'pic') {
                formData[key] = ''
            }
        }
    }
    
    //@ts-ignore
    formData.plant_date = timeFormat(formData.plant_date,'yyyy-mm-dd hh:MM:ss') 
}

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

interface ListItem {
    value: string
    label: string
}
const landOptions = ref<ListItem[]>([])
const loading = ref(false)

const queryLand = async (query: string) => {
    if (query) {
        loading.value = true
        const landList = await apiLandLists({
            title: query
        })
        loading.value = false
        if (landList.count > 0) {
            landOptions.value = landList.lists.map((land: any) => {
                return { value: `${land.id}`, label: `ID: ${land.id} / 名称: ${land.title}` }
            })
        } else {
            landOptions.value = []
        }
        loading.value = false
    } else {
        landOptions.value = []
    }
}

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

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

// 关闭回调
const handleClose = () => {
    emit('close')
}



defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
