<template>
  <ContentWrap>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="font-medium">农作物种植管理表</span>
        </div>
      </template>

      <el-form :model="formData" label-width="100px" :rules="rules" ref="formRef">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息 Basic Information</el-divider>
        <el-row :gutter="20" class="mb-4">
          <el-col :span="8">
            <el-form-item label="农户选择" prop="supplierId">
              <el-select
                v-model="formData.supplierId"
                placeholder="请选择农户"
                style="width: 100%"
                :loading="loading"
                filterable
                clearable
              >
                <el-option v-for="farmer in farmerList" :key="farmer.id" :label="farmer.name" :value="farmer.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="编号" prop="code">
              <el-input v-model="formData.code" placeholder="请输入编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="记录时间" prop="recordTime">
              <el-date-picker
                v-model="formData.recordTime"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 灌水时间 -->
        <el-divider content-position="left">灌水时间 Irrigation time</el-divider>
        <el-row :gutter="20" class="mb-4">
          <el-col :span="24">
            <!--            <el-form-item label="灌溉记录">-->
            <el-table :data="formData.irrigation" border style="width: 100%">
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column prop="date" label="日期" width="180">
                <template #default="scope">
                  <el-date-picker
                    v-model="scope.row.date"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="duration" label="时长(小时)" width="180">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.duration"
                    :min="0"
                    :precision="1"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="method" label="灌溉方式">
                <template #default="scope">
                  <el-select v-model="scope.row.method" placeholder="请选择灌溉方式" style="width: 100%">
                    <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="100" align="center">
                <template #default="scope">
                  <el-button link type="danger" @click="handleDeleteRow(formData.irrigation, scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="mt-2">
              <el-button type="primary" @click="handleAddRow('irrigation')">添加灌溉记录</el-button>
            </div>
            <!--            </el-form-item>-->
          </el-col>
        </el-row>

        <!-- 肥料使用 -->
        <el-divider content-position="left">肥料使用 Use of fertilizer</el-divider>
        <el-row :gutter="20" class="mb-4">
          <el-col :span="24">
            <el-tabs type="border-card">
              <el-tab-pane label="基肥 Base fertilizer">
                <el-table :data="formData.baseFertilizer" border style="width: 100%">
                  <el-table-column type="index" label="序号" width="60" align="center" />
                  <el-table-column prop="name" label="肥料名称">
                    <template #default="scope">
                      <el-input v-model="scope.row.name" placeholder="请输入肥料名称" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="amount" label="用量(kg/亩)">
                    <template #default="scope">
                      <el-input-number
                        v-model="scope.row.amount"
                        :min="0"
                        :precision="2"
                        style="width: 100%"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="date" label="施用日期">
                    <template #default="scope">
                      <el-date-picker
                        v-model="scope.row.date"
                        type="date"
                        placeholder="选择日期"
                        style="width: 100%"
                      />
                    </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="100" align="center">
                    <template #default="scope">
                      <el-button link type="danger" @click="handleDeleteRow(formData.baseFertilizer, scope.$index)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="mt-2">
                  <el-button type="primary" @click="handleAddRow('baseFertilizer')">添加基肥记录</el-button>
                </div>
              </el-tab-pane>
              <el-tab-pane label="追肥 Additional fertilizer">
                <el-table :data="formData.additionalFertilizer" border style="width: 100%">
                  <el-table-column type="index" label="序号" width="60" align="center" />
                  <el-table-column prop="name" label="肥料名称">
                    <template #default="scope">
                      <el-input v-model="scope.row.name" placeholder="请输入肥料名称" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="amount" label="用量(kg/亩)">
                    <template #default="scope">
                      <el-input-number
                        v-model="scope.row.amount"
                        :min="0"
                        :precision="2"
                        style="width: 100%"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="date" label="施用日期">
                    <template #default="scope">
                      <el-date-picker
                        v-model="scope.row.date"
                        type="date"
                        placeholder="选择日期"
                        style="width: 100%"
                      />
                    </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="100" align="center">
                    <template #default="scope">
                      <el-button link type="danger" @click="handleDeleteRow(formData.additionalFertilizer, scope.$index)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="mt-2">
                  <el-button type="primary" @click="handleAddRow('additionalFertilizer')">添加追肥记录</el-button>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>

        <!-- 农药使用 -->
        <el-divider content-position="left">农药使用 Use of pesticide</el-divider>
        <el-row :gutter="20" class="mb-4">
          <el-col :span="24">
            <el-table :data="formData.pesticide" border style="width: 100%">
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column prop="target" label="防治对象 Target">
                <template #default="scope">
                  <el-input v-model="scope.row.target" placeholder="请输入防治对象" />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="农药名称 Name">
                <template #default="scope">
                  <el-input v-model="scope.row.name" placeholder="请输入农药名称" />
                </template>
              </el-table-column>
              <el-table-column prop="time" label="使用时间 Time">
                <template #default="scope">
                  <el-date-picker
                    v-model="scope.row.time"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="使用量 Amount">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.amount"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="brix" label="使用浓度 Brix">
                <template #default="scope">
                  <el-input v-model="scope.row.brix" placeholder="请输入浓度" />
                </template>
              </el-table-column>
              <el-table-column prop="pattern" label="使用方式 Pattern">
                <template #default="scope">
                  <el-select v-model="scope.row.pattern" placeholder="请选择使用方式" style="width: 100%">
                    <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="防治效果 Effect">
                <template #default="scope">
                  <el-select v-model="scope.row.effect" placeholder="请选择防治效果" style="width: 100%">
                    <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="100" align="center">
                <template #default="scope">
                  <el-button link type="danger" @click="handleDeleteRow(formData.pesticide, scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="mt-2">
              <el-button type="primary" @click="handleAddRow('pesticide')">添加农药使用记录</el-button>
            </div>
          </el-col>
        </el-row>

        <!-- 采收情况 -->
        <el-divider content-position="left">采收情况 Picking</el-divider>
        <el-row :gutter="20" class="mb-4">
          <el-col :span="12">
            <el-form-item label="首次采摘时间" prop="harvesting.firstPickingTime">
              <el-date-picker
                v-model="formData.harvesting.firstPickingTime"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="采摘总量" prop="harvesting.totalQuantity">
              <el-input-number
                v-model="formData.harvesting.totalQuantity"
                :min="0"
                :precision="2"
                style="width: 90%"
              />
              <span class="ml-2">公斤(kg)</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider />
        <el-row :gutter="20" class="mb-4">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="form-footer">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </ContentWrap>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from 'vue'
import { SupplierApi } from '@/api/erp/purchase/supplier'
import { 
  createFarmingManagement, 
  updateFarmingManagement,
  getFarmingManagement
} from '@/api/erp/purchase/supplier/farmers'
import { ElForm } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

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

const message = useMessage() // 消息弹窗
const route = useRoute()
const router = useRouter()
const formRef = ref<InstanceType<typeof ElForm>>()

// 表单校验规则
const rules = {
  supplierId: [{ required: true, message: '请选择农户', trigger: 'change' }],
  recordTime: [{ required: true, message: '请选择记录时间', trigger: 'change' }]
}

// 定义农户类型接口
interface Farmer {
  id: number | string
  name: string
  [key: string]: any
}

// 农户列表数据
const farmerList = ref<Farmer[]>([])
const loading = ref(false)

// 获取农户列表
const getFarmerList = async () => {
  loading.value = true
  try {
    // 使用正确的API方法
    const res = await SupplierApi.getSupplierPage({
      pageNo: 1,
      pageSize: 100,
      type: 'farmer' // 假设有一个类型字段来区分农户
    })
    farmerList.value = res.list || []
  } catch (error) {
    console.error('获取农户列表失败:', error)
    message.error('获取农户列表失败')
  } finally {
    loading.value = false
  }
}

// 也可以考虑使用简单列表接口
const getSimpleFarmerList = async () => {
  loading.value = true
  try {
    const res = await SupplierApi.getSupplierSimpleList()
    farmerList.value = res || []
  } catch (error) {
    console.error('获取农户列表失败:', error)
    message.error('获取农户列表失败')
  } finally {
    loading.value = false
  }
}

// 表单数据
const formData = reactive({
  // 基本信息
  id: undefined as number | undefined,
  supplierId: '',
  code: '',
  recordTime: new Date(),

  // 灌溉记录
  irrigation: [
    {
      date: undefined,
      duration: 0,
      method: '',
      remark: ''
    }
  ],

  // 基肥
  baseFertilizer: [
    {
      name: '',
      amount: 0,
      date: undefined,
      method: ''
    }
  ],

  // 追肥
  additionalFertilizer: [
    {
      name: '',
      amount: 0,
      date: undefined,
      method: ''
    }
  ],

  // 农药使用
  pesticide: [
    {
      target: '',
      name: '',
      time: undefined,
      amount: 0,
      brix: '',
      pattern: '',
      effect: ''
    }
  ],

  // 采收情况
  harvesting: {
    firstPickingTime: undefined,
    totalQuantity: 0,
  },

  // 备注
  remark: ''
})

// 添加行
const handleAddRow = (type: string) => {
  if (type === 'irrigation') {
    formData.irrigation.push({
      date: undefined,
      duration: 0,
      method: '',
      remark: ''
    })
  } else if (type === 'baseFertilizer') {
    formData.baseFertilizer.push({
      name: '',
      amount: 0,
      date: undefined,
      method: ''
    })
  } else if (type === 'additionalFertilizer') {
    formData.additionalFertilizer.push({
      name: '',
      amount: 0,
      date: undefined,
      method: ''
    })
  } else if (type === 'pesticide') {
    formData.pesticide.push({
      target: '',
      name: '',
      time: undefined,
      amount: 0,
      brix: '',
      pattern: '',
      effect: ''
    })
  } 
}

// 删除行
const handleDeleteRow = (array: any[], index: number) => {
  if (array.length === 1) {
    message.warning('至少保留一行记录')
    return
  }
  array.splice(index, 1)
}

// 获取详情
const getDetail = async (id: number) => {
  try {
    loading.value = true
    const data = await getFarmingManagement(id)
    if (data) {
      formData.id = data.id
      formData.supplierId = data.supplierId
      formData.code = data.code || ''
      formData.recordTime = data.recordTime
      formData.remark = data.remark || ''
      
      // 处理JSON字段
      if (data.irrigationRecords) {
        try {
          formData.irrigation = JSON.parse(data.irrigationRecords)
        } catch (e) {
          console.error('解析灌溉记录失败', e)
        }
      }
      
      if (data.baseFertilizerRecords) {
        try {
          formData.baseFertilizer = JSON.parse(data.baseFertilizerRecords)
        } catch (e) {
          console.error('解析基肥记录失败', e)
        }
      }
      
      if (data.additionalFertilizerRecords) {
        try {
          formData.additionalFertilizer = JSON.parse(data.additionalFertilizerRecords)
        } catch (e) {
          console.error('解析追肥记录失败', e)
        }
      }
      
      if (data.pesticideRecords) {
        try {
          formData.pesticide = JSON.parse(data.pesticideRecords)
        } catch (e) {
          console.error('解析农药记录失败', e)
        }
      }
      
      formData.harvesting.firstPickingTime = data.firstPickingTime
      formData.harvesting.totalQuantity = data.totalQuantity || 0
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    message.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  // 表单校验
  await formRef.value?.validate()

  // 构建提交数据
  const submitData: any = {
    supplierId: formData.supplierId,
    code: formData.code,
    recordTime: formData.recordTime,
    irrigationRecords: JSON.stringify(formData.irrigation),
    baseFertilizerRecords: JSON.stringify(formData.baseFertilizer),
    additionalFertilizerRecords: JSON.stringify(formData.additionalFertilizer),
    pesticideRecords: JSON.stringify(formData.pesticide),
    firstPickingTime: formData.harvesting.firstPickingTime,
    totalQuantity: formData.harvesting.totalQuantity,
    remark: formData.remark
  }

  // 如果是编辑模式，添加id
  if (formData.id) {
    submitData.id = formData.id
  }

  try {
    loading.value = true
    if (formData.id) {
      // 更新
      await updateFarmingManagement(submitData)
      message.success('更新成功')
    } else {
      // 新增
      await createFarmingManagement(submitData)
      message.success('创建成功')
    }
    // 返回列表页
    router.push('/erp/purchase/supplier/farmers')
  } catch (error) {
    console.error('保存失败:', error)
    message.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = () => {
  if (formData.id) {
    // 如果是编辑，重新获取详情
    getDetail(formData.id)
  } else {
    // 重置基本信息
    formData.supplierId = ''
    formData.code = ''
    formData.recordTime = new Date()
    // 重置灌溉记录
    formData.irrigation = [{ date: undefined, duration: 0, method: '', remark: '' }]
    formData.baseFertilizer = [{ name: '', amount: 0, date: undefined, method: '' }]
    formData.additionalFertilizer = [{ name: '', amount: 0, date: undefined, method: '' }]
    formData.pesticide = [{ target: '', name: '', time: undefined, amount: 0, brix: '', pattern: '', effect: '' }]
    formData.harvesting.firstPickingTime = undefined
    formData.harvesting.totalQuantity = 0
    formData.remark = ''
  }
  message.success('表单已重置')
}

onMounted(() => {
  // 获取农户列表
  getFarmerList()
  // 或者使用 getSimpleFarmerList()
  
  // 如果是编辑模式，获取详情
  const id = route.query.id as string
  if (id) {
    getDetail(parseInt(id))
  }
})
</script>

<style scoped>
.mt-2 {
  margin-top: 12px;
}
.ml-2 {
  margin-left: 12px;
}
.mb-4 {
  margin-bottom: 24px;
}
:deep(.el-divider) {
  margin: 24px 0;
}
:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: 500;
  color: #409EFF;
}
:deep(.el-table) {
  margin: 8px 0;
}
:deep(.el-table th) {
  background-color: #f5f7fa;
}
:deep(.el-card__header) {
  padding: 16px 20px;
  background-color: #f5f7fa;
}
.card-header {
  display: flex;
  align-items: center;
  height: 24px;
}
.font-medium {
  font-size: 16px;
  font-weight: 500;
}
:deep(.el-tabs__item) {
  height: 40px;
  line-height: 40px;
}
.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
:deep(.el-form-item__content) {
  width: 100%;
}
</style>
