<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="农户" prop="supplierId">
            <el-select
              v-model="formData.supplierId"
              placeholder="请选择农户"
              clearable
              :loading="supplierLoading"
              class="!w-full"
            >
              <el-option
                v-for="supplier in supplierList"
                :key="supplier.id"
                :label="supplier.name"
                :value="supplier.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入编号" />
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="记录时间" prop="recordTime">-->
<!--            <el-date-picker-->
<!--              v-model="formData.recordTime"-->
<!--              type="datetime"-->
<!--              placeholder="请选择记录时间"-->
<!--              value-format="YYYY-MM-DD HH:mm:ss"-->
<!--              class="!w-full"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="首次采摘时间" prop="firstPickingTime">
            <el-date-picker
              v-model="formData.firstPickingTime"
              type="date"
              placeholder="请选择首次采摘时间"
              value-format="YYYY-MM-DD"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采摘总量(kg)" prop="totalQuantity">
            <el-input-number
              v-model="formData.totalQuantity"
              placeholder="请输入采摘总量"
              class="!w-full"
              :min="0"
              :precision="2"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-divider content-position="left">灌溉记录</el-divider>
        </el-col>
        <el-col :span="24">
          <el-table :data="irrigationData" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="date" label="日期" width="245">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.date"
                  type="datetime"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </template>
            </el-table-column>
            <el-table-column prop="duration" label="时长(小时)" width="190">
              <template #default="scope">
                <el-input-number v-model="scope.row.duration" :min="0" :precision="1" controls-position="right" />
              </template>
            </el-table-column>
            <el-table-column prop="method" label="灌溉方式" width="240">
              <template #default="scope">
                <el-select v-model="scope.row.method" placeholder="请选择灌溉方式">
                  <el-option label="滴灌" value="drip" />
                  <el-option label="喷灌" value="spray" />
                  <el-option label="漫灌" value="flood" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注">
              <template #default="scope">
                <el-input v-model="scope.row.remark" placeholder="请输入备注" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  @click="handleIrrigationDelete(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" @click="handleIrrigationAdd">新增灌溉记录</el-button>
          </div>
        </el-col>

        <el-col :span="24">
          <el-divider content-position="left">基肥记录</el-divider>
        </el-col>
        <el-col :span="24">
          <el-table :data="baseFertilizerData" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="name" label="肥料名称" width="245">
              <template #default="scope">
                <el-input v-model="scope.row.name" placeholder="请输入肥料名称" />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="用量(kg/亩)" width="190">
              <template #default="scope">
                <el-input-number v-model="scope.row.amount" :min="0" :precision="2" controls-position="right" />
              </template>
            </el-table-column>
            <el-table-column prop="date" label="施用日期" width="240">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.date"
                  type="datetime"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </template>
            </el-table-column>
            <el-table-column prop="method" label="施用方法">
              <template #default="scope">
                <el-input v-model="scope.row.method" placeholder="请输入施用方法" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  @click="handleBaseFertilizerDelete(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" @click="handleBaseFertilizerAdd">新增基肥记录</el-button>
          </div>
        </el-col>

        <el-col :span="24">
          <el-divider content-position="left">追肥记录</el-divider>
        </el-col>
        <el-col :span="24">
          <el-table :data="additionalFertilizerData" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="name" label="肥料名称" width="245">
              <template #default="scope">
                <el-input v-model="scope.row.name" placeholder="请输入肥料名称" />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="用量(kg/亩)" width="190">
              <template #default="scope">
                <el-input-number v-model="scope.row.amount" :min="0" :precision="2" controls-position="right" />
              </template>
            </el-table-column>
            <el-table-column prop="date" label="施用日期" width="240">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.date"
                  type="datetime"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </template>
            </el-table-column>
            <el-table-column prop="method" label="施用方法">
              <template #default="scope">
                <el-input v-model="scope.row.method" placeholder="请输入施用方法" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  @click="handleAdditionalFertilizerDelete(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" @click="handleAdditionalFertilizerAdd">新增追肥记录</el-button>
          </div>
        </el-col>

        <el-col :span="24">
          <el-divider content-position="left">农药使用记录</el-divider>
        </el-col>
        <el-col :span="24">
          <el-table :data="pesticideData" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="target" label="防治对象" width="160">
              <template #default="scope">
                <el-input v-model="scope.row.target" placeholder="请输入防治对象" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="农药名称" width="160">
              <template #default="scope">
                <el-input v-model="scope.row.name" placeholder="请输入农药名称" />
              </template>
            </el-table-column>
            <el-table-column prop="time" label="使用时间" width="245">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.time"
                  type="datetime"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="使用量" width="120">
              <template #default="scope">
                <el-input v-model="scope.row.amount" placeholder="使用量" />
              </template>
            </el-table-column>
            <el-table-column prop="brix" label="使用浓度" width="120">
              <template #default="scope">
                <el-input v-model="scope.row.brix" placeholder="使用浓度" />
              </template>
            </el-table-column>
            <el-table-column prop="pattern" label="使用方式" width="120">
              <template #default="scope">
                <el-select v-model="scope.row.pattern" placeholder="请选择使用方式">
                  <el-option label="喷洒" value="spray" />
                  <el-option label="浸泡" value="soak" />
                  <el-option label="撒施" value="spread" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="effect" label="防治效果" >
              <template #default="scope">
                <el-select v-model="scope.row.effect" placeholder="请选择防治效果">
                  <el-option label="优" value="excellent" />
                  <el-option label="良" value="good" />
                  <el-option label="一般" value="normal" />
                  <el-option label="差" value="poor" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  @click="handlePesticideDelete(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" @click="handlePesticideAdd">新增农药使用记录</el-button>
          </div>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { FarmingManagementVO, createFarmingManagement, updateFarmingManagement, getFarmingManagement } from '@/api/erp/purchase/supplier/farmers'
import { FarmerApi } from '@/api/erp/purchase/farmer'
import dayjs from 'dayjs'

/** 农作物种植管理表单 */
defineOptions({ name: 'FarmingManagementForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 供应商/农户数据
const supplierList = ref([])
const supplierLoading = ref(false)

// 获取供应商/农户列表
const getSupplierList = async () => {
  supplierLoading.value = true
  try {
    const res = await FarmerApi.getFarmerPage({
      pageNo: 1,
      pageSize: 100
    })
    supplierList.value = res.list || []
  } catch (error) {
    console.error('获取农户列表失败:', error)
  } finally {
    supplierLoading.value = false
  }
}

// 灌溉记录数据
const irrigationData = ref([])
// 基肥记录数据
const baseFertilizerData = ref([])
// 追肥记录数据
const additionalFertilizerData = ref([])
// 农药使用记录数据
const pesticideData = ref([])

// 表单数据
const formData = ref<FarmingManagementVO>({
  id: undefined,
  supplierId: undefined,
  code: undefined,
  recordTime: undefined,
  irrigationRecords: undefined,
  baseFertilizerRecords: undefined,
  additionalFertilizerRecords: undefined,
  pesticideRecords: undefined,
  firstPickingTime: undefined,
  totalQuantity: 0,
  remark: undefined
})

// 表单校验规则
const formRules = reactive({
  supplierId: [{ required: true, message: '农户不能为空', trigger: 'change' }],
  // recordTime: [{ required: true, message: '记录时间不能为空', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await getSupplierList()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await getFarmingManagement(id)
      
      // 确保日期字段是字符串格式
      if (data.recordTime && typeof data.recordTime !== 'string') {
        data.recordTime = dayjs(data.recordTime).format('YYYY-MM-DD HH:mm:ss')
      }
      if (data.firstPickingTime && typeof data.firstPickingTime !== 'string') {
        data.firstPickingTime = dayjs(data.firstPickingTime).format('YYYY-MM-DD')
      }
      
      formData.value = data
      
      // 解析 JSON 数据并处理日期
      try {
        const irrigationRecords = data.irrigationRecords ? JSON.parse(data.irrigationRecords) : []
        irrigationData.value = irrigationRecords.map(record => {
          if (record.date && typeof record.date !== 'string') {
            record.date = dayjs(record.date).format('YYYY-MM-DD HH:mm:ss')
          }
          return record
        })
      } catch (e) {
        irrigationData.value = []
      }
      
      try {
        const baseFertilizerRecords = data.baseFertilizerRecords ? JSON.parse(data.baseFertilizerRecords) : []
        baseFertilizerData.value = baseFertilizerRecords.map(record => {
          if (record.date && typeof record.date !== 'string') {
            record.date = dayjs(record.date).format('YYYY-MM-DD HH:mm:ss')
          }
          return record
        })
      } catch (e) {
        baseFertilizerData.value = []
      }
      
      try {
        const additionalFertilizerRecords = data.additionalFertilizerRecords ? JSON.parse(data.additionalFertilizerRecords) : []
        additionalFertilizerData.value = additionalFertilizerRecords.map(record => {
          if (record.date && typeof record.date !== 'string') {
            record.date = dayjs(record.date).format('YYYY-MM-DD HH:mm:ss')
          }
          return record
        })
      } catch (e) {
        additionalFertilizerData.value = []
      }
      
      try {
        const pesticideRecords = data.pesticideRecords ? JSON.parse(data.pesticideRecords) : []
        pesticideData.value = pesticideRecords.map(record => {
          if (record.time && typeof record.time !== 'string') {
            record.time = dayjs(record.time).format('YYYY-MM-DD HH:mm:ss')
          }
          return record
        })
      } catch (e) {
        pesticideData.value = []
      }
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  // 组装数据
  const data = { ...formData.value } as unknown as FarmingManagementVO
  data.irrigationRecords = JSON.stringify(irrigationData.value)
  data.baseFertilizerRecords = JSON.stringify(baseFertilizerData.value)
  data.additionalFertilizerRecords = JSON.stringify(additionalFertilizerData.value)
  data.pesticideRecords = JSON.stringify(pesticideData.value)
  
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await createFarmingManagement(data)
      message.success(t('common.createSuccess'))
    } else {
      await updateFarmingManagement(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    supplierId: undefined,
    code: undefined,
    recordTime: undefined,
    irrigationRecords: undefined,
    baseFertilizerRecords: undefined,
    additionalFertilizerRecords: undefined,
    pesticideRecords: undefined,
    firstPickingTime: undefined,
    totalQuantity: 0,
    remark: undefined
  }
  irrigationData.value = []
  baseFertilizerData.value = []
  additionalFertilizerData.value = []
  pesticideData.value = []
}

// 新增灌溉记录
const handleIrrigationAdd = () => {
  irrigationData.value.push({
    date: null,
    duration: 0,
    method: '',
    remark: ''
  })
}

// 删除灌溉记录
const handleIrrigationDelete = (index) => {
  irrigationData.value.splice(index, 1)
}

// 新增基肥记录
const handleBaseFertilizerAdd = () => {
  baseFertilizerData.value.push({
    name: '',
    amount: 0,
    date: null,
    method: ''
  })
}

// 删除基肥记录
const handleBaseFertilizerDelete = (index) => {
  baseFertilizerData.value.splice(index, 1)
}

// 新增追肥记录
const handleAdditionalFertilizerAdd = () => {
  additionalFertilizerData.value.push({
    name: '',
    amount: 0,
    date: null,
    method: ''
  })
}

// 删除追肥记录
const handleAdditionalFertilizerDelete = (index) => {
  additionalFertilizerData.value.splice(index, 1)
}

// 新增农药使用记录
const handlePesticideAdd = () => {
  pesticideData.value.push({
    target: '',
    name: '',
    time: null,
    amount: '',
    brix: '',
    pattern: 'spray',
    effect: 'good'
  })
}

// 删除农药使用记录
const handlePesticideDelete = (index) => {
  pesticideData.value.splice(index, 1)
}

// 对外暴露函数
defineExpose({ open })
</script> 
