<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="编号" prop="code">
        <el-input v-model="formData.code" placeholder="请输入编号" />
      </el-form-item>
      <el-form-item label="种植姓名" prop="name">
        <el-select
          v-model="formData.name"
          filterable
          remote
          clearable
          placeholder="请输入并选择种植姓名"
          :remote-method="remoteSupplierFarmerMethod"
          :loading="supplierLoadingFarmer"
          @change="handleSupplierChange"
          style="width: 100%"
        >
          <el-option
            v-for="item in supplierOptionsFarmer"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="管理员" prop="admin">
        <el-input v-model="formData.admin" placeholder="请输入管理员" />
      </el-form-item>
      <el-form-item label="种植区域" prop="area">
        <el-input v-model="formData.area" placeholder="请输入种植区域" />
      </el-form-item>
      <el-form-item label="种植数量" prop="quantity">
        <el-input-number v-model="formData.quantity" :min="0" />
      </el-form-item>
      <el-form-item label="品种名称" prop="varietyName">
        <el-input v-model="formData.varietyName" placeholder="请输入品种名称" />
      </el-form-item>
      <el-form-item label="领取时间" prop="receiveTime">
        <el-date-picker
          v-model="formData.receiveTime"
          type="datetime"
          placeholder="选择领取时间"
          value-format="x"
        />
      </el-form-item>
      <el-form-item label="大棚号" prop="greenhouseNo">
        <el-input v-model="formData.greenhouseNo" placeholder="请输入大棚号" />
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :disabled="formLoading">确定</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'
import { FormInstance } from 'element-plus'
import { getSeedling, createSeedling, updateSeedling } from '@/api/erp/seedling'
import { FarmerApi, type FarmerVO } from '@/api/erp/purchase/farmer'

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref<FormInstance | null>(null) // 表单 Ref

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 供应商（农户）远程搜索数据
const supplierOptionsFarmer = ref<FarmerVO[]>([])
const supplierLoadingFarmer = ref(false)
const remoteSupplierFarmerMethod = async (query: string) => {
  supplierLoadingFarmer.value = true
  try {
    const res = await FarmerApi.getFarmerPage({
      pageNo: 1,
      pageSize: 100,
      name: query || undefined
    })
    supplierOptionsFarmer.value = res.list || []
  } finally {
    supplierLoadingFarmer.value = false
  }
}

const handleSupplierChange = (value: string) => {
  const selected = supplierOptionsFarmer.value.find(item => item.name === value)
  formData.admin = selected?.adminName || ''
}

// 表单数据
const formData = reactive({
  id: undefined,
  code: '',
  admin: '',
  name: '',
  area: '',
  quantity: 0,
  varietyName: '',
  receiveTime: '',
  greenhouseNo: '',
  status: 0,
  remark: ''
})

// 表单校验规则
const formRules = reactive({
  code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
  // admin: [{ required: true, message: '管理员不能为空', trigger: 'blur' }],
  // name: [{ required: true, message: '种植姓名不能为空', trigger: 'change' }],
  // area: [{ required: true, message: '种植区域不能为空', trigger: 'blur' }],
  // quantity: [{ required: true, message: '种植数量不能为空', trigger: 'change' }],
  // varietyName: [{ required: true, message: '品种名称不能为空', trigger: 'blur' }],
  // receiveTime: [{ required: true, message: '领取时间不能为空', trigger: 'change' }],
  // greenhouseNo: [{ required: true, message: '大棚号不能为空', trigger: 'blur' }],
  // status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})

// 表单操作：打开表单
const emit = defineEmits(['success']) // 定义 emit 事件
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增种植信息' : '编辑种植信息'
  formType.value = type
  resetForm()
  // 预加载一次名单，方便直接下拉
  remoteSupplierFarmerMethod('')
  
  // 修改时，设置数据
  if (type === 'update') {
    formLoading.value = true
    try {
      const data = await getSeedling(id as number)
      Object.assign(formData, data)
    } finally {
      formLoading.value = false
    }
  }
}

// 表单操作：重置表单
const resetForm = () => {
  formData.id = undefined
  formData.code = ''
  formData.admin = ''
  formData.name = ''
  formData.area = ''
  formData.quantity = 0
  formData.varietyName = ''
  formData.receiveTime = ''
  formData.greenhouseNo = ''
  formData.status = 0
  formData.remark = ''
  formRef.value?.resetFields()
}

// 表单操作：提交表单
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value.validate()
  
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData }
    // 领取时间已经是时间戳格式，不需要转换
    if (formType.value === 'create') {
      await createSeedling(data)
      message.success(t('common.createSuccess'))
    } else {
      await updateSeedling(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 暴露表单操作方法
defineExpose({ open })
</script> 
