<template>
  <div class="custom-page">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="searchForm" class="search-bar">
      <el-form-item label="关键词">
        <el-input v-model="searchForm.name" placeholder="请输入关键词" clearable />
      </el-form-item>
      <el-form-item label="" label-width="0">
        <AreaCascader v-model:region-code="searchForm.regionCode" v-model:grid-id="searchForm.id" :width="600" />
      </el-form-item>
      <el-form-item label="种植作物" prop="planCrop">
        <url-select
          v-model="searchForm.planCrop"
          url="/land-resource/crops/page"
          :params="{ status: '0' }"
          label-key="cropsName"
          value-key="id"
          placeholder="请选择种植作物"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 功能区域 -->
    <section class="function-bar">
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </section>
    <!-- 表格区域 -->
    <TableComponent
      :loading="loading"
      :columns="columns"
      :table-data="tableData"
      :current-page="pageData.currentPage"
      :page-size="pageData.pageSize"
      :total="pageData.total"
      :show-pagination="true"
      :show-border="true"
      :show-sort="true"
      style="max-height: calc(100vh - 220px)"
      @page-change="handlePageChange"
    >
      <template #action="scope">
        <custom-table-operate :actions="actions" :data="scope" />
      </template>
    </TableComponent>

    <!-- 详情/编辑对话框 -->
    <el-dialog :key="dialogTitle" v-model="visible" :title="dialogTitle" width="60%" align-center :draggable="true">
      <el-form ref="basicFormRef" :model="formData" :disabled="isReadonly" label-width="120px">
        <p class="form-title">种植信息</p>
        <el-row :gutter="20">
          <el-col :span="4">
            <!-- 作物图片 -->
            <FileUploader v-model="formData.cropUrl" :limit="1" />
          </el-col>
          <el-col :span="10">
            <!-- 种植作物 -->
            <el-form-item label="种植作物" prop="cropName">
              <el-input v-model="formData.cropName" placeholder="请输入种植作物名称" clearable />
            </el-form-item>

            <!-- 地块编号 -->
            <el-form-item label="地块编号" prop="plotCode">
              <el-input v-model="formData.plotCode" placeholder="请输入地块编号" clearable />
            </el-form-item>

            <!-- 种植基地编号 -->
            <el-form-item label="种植基地编号" prop="baseCode">
              <el-input v-model="formData.baseCode" placeholder="请输入种植基地编号" clearable />
            </el-form-item>

            <!-- 种植批次编号 -->
            <el-form-item label="种植批次编号" prop="batchCode">
              <el-input v-model="formData.batchCode" placeholder="请输入种植批次编号" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <!-- 作物品种 -->
            <el-form-item label="作物品种" prop="cropVariety">
              <el-select v-model="formData.cropVariety" placeholder="请选择作物品种" clearable filterable>
                <el-option v-for="item in cropVarieties" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

            <!-- 地块名称 -->
            <el-form-item label="地块名称" prop="plotName">
              <el-input v-model="formData.plotName" placeholder="请输入地块名称" clearable />
            </el-form-item>

            <!-- 种植基地 -->
            <el-form-item label="种植基地" prop="baseName">
              <el-input v-model="formData.baseName" placeholder="请输入种植基地名称" clearable />
            </el-form-item>

            <!-- 种植批次 -->
            <el-form-item label="种植批次" prop="batchName">
              <el-input v-model="formData.batchName" placeholder="请输入种植批次名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <p class="form-title">农事作业管理</p>
        <el-form-item label="农事作业列表">
          <el-card v-for="(task, index) in formData.farmingTasks" :key="index" class="mb-4">
            <el-row :gutter="20">
              <el-col :span="4">
                <!-- 作业图片占位，可加上传组件 -->
                <div
                  style="
                    width: 100px;
                    height: 100px;
                    background-color: #f0f0f0;
                    border: 1px solid #ccc;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  "
                >
                  <FileUploader v-model="formData.cropUrl" :limit="1" />
                </div>
              </el-col>
              <el-col :span="20">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="作业类型">
                      <el-input v-model="task.type" placeholder="如：种子处理、播种等" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="负责人">
                      <el-input v-model="task.responsible" placeholder="请输入负责人" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="开始时间">
                      <el-date-picker v-model="task.startDate" type="date" placeholder="选择开始日期" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="结束时间">
                      <el-date-picker v-model="task.endDate" type="date" placeholder="选择结束日期" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="作业内容">
                  <el-input v-model="task.content" type="textarea" rows="3" placeholder="请输入具体作业内容" />
                </el-form-item>
                <el-form-item label="实际作业情况">
                  <el-input v-model="task.actual" type="textarea" rows="2" placeholder="如：肥料使用量：XX 公斤/亩" />
                </el-form-item>
                <el-button type="danger" @click="removeTask(index)">删除此作业</el-button>
              </el-col>
            </el-row>
          </el-card>
          <el-button type="primary" plain @click="addTask">新增作业</el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <template v-if="!isReadonly">
            <el-button type="primary" @click="submitAll">确定</el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue';
import { mockData } from './mockData';

// ==================== 常量定义 ====================
const DIALOG_TITLE = {
  VIEW: '农事作业详情',
  EDIT: '编辑农事作业信息',
  ADD: '新增农事作业',
};

// ==================== 状态管理 ====================
const loading = ref(false);
const visible = ref(false);
const isReadonly = ref(false);
const dialogTitle = ref('');
// const activeFormTab = ref('basic');

// 表单数据
const searchForm = ref({});
const formData = ref({
  gridName: '',
  gridAreaCode: '',
  scope: '',
  scopeImg: '',
  note: '',
});
const initialFormData = { ...formData.value };
// 分页数据
const pageData = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
// 表格数据
const tableData = ref([]);
// ==================== 表格配置 ====================
const columns = ref([
  { label: '地块编号', prop: 'landNumber', width: 160 },
  { label: '地块名称', prop: 'landName', width: 170 },
  { label: '面积', prop: 'planArea', formatter: (row, column, cellValue) => `${Number(cellValue).toFixed(2)} 亩` },
  { label: '所属行政区域', prop: 'belongRegion', width: 160 },
  { label: '所属网格', prop: 'belongGrid', width: 90 },
  { label: '具体位置', prop: 'address', width: 160 },
  { label: '基地编码', prop: 'baseCode' },
  { label: '基地名称', prop: 'baseName' },
  { label: '种植批次编码', prop: 'batchCode' },
  { label: '种植批次名称', prop: 'batchName' },
  { label: '种植作物', prop: 'crop' },
  { label: '作物品种', prop: 'cropBrand' },
  { label: '种植开始时间', prop: 'startDate' },
  { label: '种植结束时间', prop: 'endDate' },
  { label: '经营主体代码', prop: 'businessEntityCode', width: 130 },
  { label: '经营主体类型', prop: 'businessEntityType', width: 130 },
  { label: '经营主体名称', prop: 'businessEntityName', width: 130 },
  // { label: '账号（手机号）', prop: 'account', width: 130 },
  { label: '信息填报时间', prop: 'fillTime', width: 110 },
  { label: '信息审核时间', prop: 'approvalTime', width: 110 },
  { label: '操作', prop: 'action', slotName: 'action', fixed: 'right' },
]);
const actions = [
  {
    name: '查看',
    icon: 'view',
    event: ({ row }) => handleView(row),
  },
  {
    name: '编辑',
    icon: 'edit',
    event: ({ row }) => handleEdit(row),
  },
  {
    type: 'danger',
    name: '删除',
    icon: 'delete',
    event: ({ row }) => handleDelete(row.id),
  },
];

// ==================== 生命周期 ====================
onMounted(() => {
  getData();
});
// ==================== 数据获取 ====================
const getData = async () => {
  await new Promise((resolve) => setTimeout(resolve, 300));
  tableData.value = mockData;
  pageData.value.total = tableData.value.length;
};
// ==================== 表格操作 ====================
const handlePageChange = ({ page, pageSize }) => {
  pageData.value.currentPage = page;
  pageData.value.pageSize = pageSize;
  getData();
};
// ==================== 表单操作 ====================
const handleAdd = () => {
  resetForm();
  dialogTitle.value = DIALOG_TITLE.ADD;
  visible.value = true;
};

const handleView = async (row) => {
  isReadonly.value = true;
  dialogTitle.value = DIALOG_TITLE.VIEW;
  formData.value = { ...row };
  visible.value = true;
};

const handleEdit = (row) => {
  isReadonly.value = false;
  dialogTitle.value = DIALOG_TITLE.EDIT;
  formData.value = { ...row };
  visible.value = true;
};

const handleDelete = async (id) => {
  console.log('删除', id);
  // 实际删除逻辑
};

const resetForm = () => {
  formData.value = {
    gridName: '',
    gridAreaCode: '',
    scope: '',
    scopeImg: '',
    note: '',
  };
};

const handleSearch = () => {
  pageData.value.currentPage = 1;
  getData();
};

const handleReset = () => {
  searchForm.value = {};
  resetForm();
  handleSearch();
};

const submitAll = () => {
  console.log('提交表单', formData.value);
  visible.value = false;
};
</script>

<style scoped lang="scss"></style>
