<template>
  <div>
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="农户" prop="supplierId">
          <el-select
            v-model="queryParams.supplierId"
            placeholder="请选择农户"
            clearable
            :loading="supplierLoading"
            style="width: 180px;"
          >
            <el-option
              v-for="supplier in supplierList"
              :key="supplier.id"
              :label="supplier.name"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="编号" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入编号" clearable />
        </el-form-item>
<!--        <el-form-item label="记录时间" prop="recordTime">-->
<!--                            <el-date-picker-->
<!--                    v-model="queryParams.recordTime"-->
<!--                    type="datetimerange"-->
<!--                    start-placeholder="开始时间"-->
<!--                    end-placeholder="结束时间"-->
<!--                    value-format="YYYY-MM-DD HH:mm:ss"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          <el-button
            type="primary"
            @click="openForm('create')"
            v-hasPermi="['erp:farming-management:create']"
          >
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="list" @row-click="handleRowClick">
        <el-table-column label="编号" align="center" prop="code" />
        <el-table-column label="农户" align="center" prop="supplierName" />
<!--        <el-table-column label="记录时间" align="center" prop="recordTime" width="170">-->
<!--          <template #default="scope">-->
<!--            <span>{{ formatDate(scope.row.recordTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="首次采摘时间" align="center" width="120">
          <template #default="scope">
            <span>{{ formatDate2(scope.row.firstPickingTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="采摘总量(kg)" align="center" prop="totalQuantity" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="170">
          <template #default="scope">
            <span>{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="240" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['erp:farming-management:update']"
            >
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleDetail(scope.row)"
              v-hasPermi="['erp:farming-management:query']"
            >
              详情
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row)"
              v-hasPermi="['erp:farming-management:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailOpen" title="农作物种植管理详情" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="农户">{{ detailData.supplierName }}</el-descriptions-item>
        <el-descriptions-item label="编号">{{ detailData.code }}</el-descriptions-item>
<!--        <el-descriptions-item label="记录时间">{{ formatDate(detailData.recordTime) }}</el-descriptions-item>-->
        <el-descriptions-item label="首次采摘时间">{{ formatDate2(detailData.firstPickingTime) }}</el-descriptions-item>
        <el-descriptions-item label="采摘总量(kg)">{{ detailData.totalQuantity }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailData.remark }}</el-descriptions-item>
      </el-descriptions>

      <template v-if="irrigationData.length > 0">
        <el-divider content-position="left">灌溉记录</el-divider>
        <el-table :data="irrigationData" border style="width: 100%">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="日期" width="120">
            <template #default="scope">
              <span>{{ formatDate(scope.row.date) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="时长(小时)" width="100" />
          <el-table-column prop="method" label="灌溉方式" width="100">
            <template #default="scope">
              {{ getIrrigationMethodText(scope.row.method) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </template>

      <template v-if="baseFertilizerData.length > 0">
        <el-divider content-position="left">基肥记录</el-divider>
        <el-table :data="baseFertilizerData" border style="width: 100%">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="name" label="肥料名称" />
          <el-table-column prop="amount" label="用量(kg/亩)" width="100" />
          <el-table-column label="施用日期" width="120">
            <template #default="scope">
              <span>{{ formatDate(scope.row.date) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="method" label="施用方法" />
        </el-table>
      </template>

      <template v-if="additionalFertilizerData.length > 0">
        <el-divider content-position="left">追肥记录</el-divider>
        <el-table :data="additionalFertilizerData" border style="width: 100%">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="name" label="肥料名称" />
          <el-table-column prop="amount" label="用量(kg/亩)" width="100" />
          <el-table-column label="施用日期" width="120">
            <template #default="scope">
              <span>{{ formatDate(scope.row.date) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="method" label="施用方法" />
        </el-table>
      </template>

      <template v-if="pesticideData.length > 0">
        <el-divider content-position="left">农药使用记录</el-divider>
        <el-table :data="pesticideData" border style="width: 100%">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="target" label="防治对象" />
          <el-table-column prop="name" label="农药名称" />
          <el-table-column label="使用时间" width="120">
            <template #default="scope">
              <span>{{ formatDate(scope.row.time) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="使用量" width="80" />
          <el-table-column prop="brix" label="使用浓度" width="80" />
          <el-table-column prop="pattern" label="使用方式" width="80">
            <template #default="scope">
              {{ getPesticidePatternText(scope.row.pattern) }}
            </template>
          </el-table-column>
          <el-table-column prop="effect" label="防治效果" width="80">
            <template #default="scope">
              {{ getPesticideEffectText(scope.row.effect) }}
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-dialog>

    <!-- 表单弹窗：添加/修改 -->
    <FarmingManagementForm ref="formRef" @success="getList" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getFarmingManagementPage, getFarmingManagement, deleteFarmingManagement } from '@/api/erp/purchase/supplier/farmers'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'
import FarmingManagementForm from './FarmingManagementForm.vue'

const message = useMessage()

const loading = ref(false)
const total = ref(0)
const list = ref([])
const queryFormRef = ref()

// 查询条件
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  supplierId: undefined,
  code: undefined,
  recordTime: undefined
})

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

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

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await getFarmingManagementPage(queryParams)
    list.value = res.list
    total.value = res.total
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 打开表单（新增/编辑）
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

// 详情数据
const detailOpen = ref(false)
const detailData = ref({})
const irrigationData = ref([])
const baseFertilizerData = ref([])
const additionalFertilizerData = ref([])
const pesticideData = ref([])

/** 行点击操作 */
const handleRowClick = (row: SupplierVO) => {
  openForm('update', row.id)
}

// 查看详情
const handleDetail = async (row) => {
  try {
    loading.value = true
    const data = await getFarmingManagement(row.id)
    detailData.value = data

    // 确保备注字段有默认值
    if (detailData.value.remark === undefined || detailData.value.remark === null) {
      detailData.value.remark = ''
    }

    // 解析 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 = []
    }

    detailOpen.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认要删除编号为"${row.code || row.id}"的农作物种植管理记录吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteFarmingManagement(row.id)
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 获取灌溉方式文本
const getIrrigationMethodText = (method) => {
  const methodMap = {
    drip: '滴灌',
    spray: '喷灌',
    flood: '漫灌'
  }
  return methodMap[method] || method
}

// 获取农药使用方式文本
const getPesticidePatternText = (pattern) => {
  const patternMap = {
    spray: '喷洒',
    soak: '浸泡',
    spread: '撒施'
  }
  return patternMap[pattern] || pattern
}

// 获取农药防治效果文本
const getPesticideEffectText = (effect) => {
  const effectMap = {
    excellent: '优',
    good: '良',
    normal: '一般',
    poor: '差'
  }
  return effectMap[effect] || effect
}

// 自定义格式化日期，确保精确到秒
const formatDate = (val: any) => {
  if (!val) return ''
  // 支持时间戳和字符串
  return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
}
// 自定义格式化日期，确保精确到秒
const formatDate2 = (val: any) => {
  if (!val) return ''
  // 支持时间戳和字符串
  return dayjs(val).format('YYYY-MM-DD')
}

onMounted(() => {
  getSupplierList()
  getList()
})
</script>
