<template>
  <div class="custom-page">
    <h1>草地</h1>
    <!-- 搜索 -->
    <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 lable="">
        <AreaCascader v-model:region-code="searchForm.regionCode" v-model:grid-id="searchForm.id" :width="600" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch"> 搜索 </el-button>
        <el-button @click="resetSearch"> 重置 </el-button>
      </el-form-item>
    </el-form>
    <!-- 四个固定 Tabs -->
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <!-- <el-tab-pane label="待提交" name="0" /> -->
      <el-tab-pane label="待审核" name="1" />
      <el-tab-pane label="已通过" name="2" />
      <el-tab-pane label="已驳回" name="0" />
    </el-tabs>
    <avue-crud
      ref="crudRef"
      v-model:page="pageData"
      :data="crudData"
      :option="crudOptions"
      :table-loading="loading"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    >
      <!-- <template #menu-left>
        <el-button type="primary" icon="Plus" @click="handleAdd">新增网格</el-button>
      </template> -->
      <template #menu="scope">
        <custom-table-operate :actions="crudOptions.actions" :data="scope" />
      </template>
    </avue-crud>
    <el-dialog :key="dialogTitle" v-model="visible" :title="dialogTitle" width="60%" align-center :draggable="true">
      <el-form ref="form" :model="formData" :rules="rules" :disabled="isReadonly" label-width="100px" class="form-item">
        <p class="form-title">填写网格信息</p>
        <el-form-item label="网格名称" prop="gridName">
          <el-input v-model="formData.gridName" placeholder="请输入网格名称" />
        </el-form-item>
        <el-form-item label="所属行政区域" prop="gridAreaCode">
          <AreaSelect v-model="formData.gridAreaCode" :label="null" :emit-path="false" />
        </el-form-item>
        <el-form-item label="网格化地图" prop="scopeImg">
          <FileUploader v-model="formData.scopeImg" :limit="1" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="formData.note" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button v-if="!isReadonly" type="primary" @click="handleSubmit()"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// ---------------------------------------------------------------------
// avue-crud 通用代码
// ---------------------------------------------------------------------
import { ref, reactive, watch, onMounted, computed, nextTick } from 'vue';
import { CRUD_OPTIONS } from '@/config';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/store/modules/user';
import { mockData } from './landData';

const UserStore = useUserStore();
const user = UserStore.getUserInfo();
console.log('admin 属性：', user.admin);

const loading = ref(false);

const visible = ref(false);
const isReadonly = ref(false);
const dialogTitle = ref();
const activeTab = ref('1');
const formData = ref({
  gridName: '',
  gridAreaCode: '',
  scope: '',
  scopeImg: '',
  note: '',
});
const initialFormData = { ...formData.value };
const resetForm = () => {
  formData.value = { ...initialFormData };
};

const pageData = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
const searchForm = ref({
  gridName: '',
  keyword: '',
  regionCode: '',
  id: '',
  status: -1,
});
const initialSearchForm = { ...searchForm.value };
const resetSearch = () => {
  searchForm.value = { ...initialSearchForm };
};
// 过滤对象，只保留有值的属性
const filterObject = (obj) => {
  const newObj = {};
  Object.keys(obj).forEach((key) => {
    const value = obj[key];
    // 检查值是否有效，排除空字符串、null 和 undefined
    if (value !== '' && value !== null && value !== undefined) {
      newObj[key] = value;
    }
  });
  return newObj;
};

const crudData = ref([]);
const crudOptions = reactive({
  ...CRUD_OPTIONS,
  addBtn: false,
  header: false,
  searchBtn: false,
  emptyBtn: false,
  refreshBtn: false,
  height: 'calc(100vh - 360px)',
  column: [
    { label: '地块编号', prop: 'id', width: 160 },
    { label: '地块名称', prop: 'landName', width: 170 },
    { label: '面积', prop: 'area', formatter: (row, column, cellValue) => `${Number(cellValue).toFixed(2)} 亩` },
    { label: '土地分类', prop: 'landTypeName' },
    { label: '土壤类型', prop: 'soilTypeName' },
    { label: '所属行政区域', prop: 'fullRegionName', width: 160 },
    { label: '所属网格', prop: 'gridName', width: 90 },
    { label: '具体位置', prop: 'address', width: 160 },
    { label: '土地承包经营人', prop: 'propertyName' },
    { label: '联系电话', prop: 'propertyPhone' },
    { label: '土地经营权证书编号', prop: 'landCode', width: 160 },
    { label: '是否土地流转', prop: 'isTransfer' },
    { label: '土地受让方', prop: 'transferName' },
    { label: '受让方联系电话', prop: 'transferPhone', width: 100 },
    { label: '流转合同', prop: 'transferContract' },
    { label: '信息填报人', prop: 'fillName' },
    { label: '信息填报单位', prop: 'fillGroup' },
    { label: '信息填报时间', prop: 'fillTime' },
    // { label: '信息更新人', prop: 'updateName' },
    // { label: '信息更新单位', prop: 'updateGroup' },
    { label: '信息更新时间', prop: 'updateTime' },
  ],
  actions: [
    {
      name: '查看',
      icon: 'view',
      event: ({ row }) => handleView(row),
    },
    {
      name: '编辑',
      icon: 'edit',
      event: ({ row }) => handleEdit(row),
    },
    {
      type: 'danger',
      name: '删除',
      icon: 'delete',
      event: ({ row }) => handleDelete(row),
    },
  ],
});
const handleTabChange = ({ name }) => {
  //   activeTab.value = name;
  console.log('切换tab', activeTab.value);
  getData();
};
const handleRefresh = async () => {
  searchForm.value = { ...initialSearchForm };
  getData();
};
const handleCurrentChange = (val) => {
  pageData.value.currentPage = val;
};
const handleSizeChange = (val) => {
  pageData.value.pageSize = val;
};
const handleView = (row) => {
  isReadonly.value = true;
  formData.value = { ...row };
  dialogTitle.value = '查看网格';
  //   visible.value = true;
};
const handleEdit = (row) => {
  isReadonly.value = false;
  formData.value = { ...row };
  dialogTitle.value = '编辑网格';
  //   visible.value = true;
};
const handleDelete = async (row) => {
  console.log('删除', row);
  //   try {
  //     await ElMessageBox.confirm('确认删除该网格吗？', '提示', {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  //       type: 'warning',
  //     });

  //     const response = await deleteGrid(row.id);

  //     ElMessage.success('删除成功');
  //     getData();
  //   } catch (error) {
  //     if (error === 'cancel') {
  //       ElMessage.info('已取消删除');
  //     } else {
  //       ElMessage.error('删除失败');
  //       console.error('删除异常:', error);
  //     }
  //   }
};

const handleSubmit = async () => {
  console.log('提交表单:', formData.value);
  try {
    if (dialogTitle.value === '新增网格') {
      await createGrid(formData.value);
      ElMessage.success('新增成功');
      resetForm();
      visible.value = false;
      getData();
    } else {
      await updateGrid(formData.value);
      ElMessage.success('更新成功');
      resetForm();
      visible.value = false;
      getData();
    }
  } catch (error) {
    ElMessage.error(error.message || '新增失败，请重试');
  }
};

// ---------------------------------------------------------------------
// 业务代码
// ---------------------------------------------------------------------
import { createGrid, updateGrid, deleteGrid, fetchGridList, getGridDetail, exportGrid } from '@/apis/landResourceManagement/gridManagement';

onMounted(() => {
  getData();
});
const getData = async () => {
  //   const filteredParams = filterObject(searchForm.value);
  //   const response = await fetchGridList(filteredParams);
  //   crudData.value = Array.isArray(response.data.records) ? response.data.records : [];
  loading.value = true;
  // 模拟接口延迟
  await new Promise((resolve) => setTimeout(resolve, 300));
  crudData.value = mockData
    .filter((item) => item.status === activeTab.value)
    .map((item) => ({
      ...item,
      landTypeName: '草地',
    }));
  pageData.value.total = crudData.value.length;
  loading.value = false;
};

const handleAdd = () => {
  console.log('handleAdd');
  resetForm();
  isReadonly.value = false;
  dialogTitle.value = '新增网格';
  visible.value = true;
};

const handleSearch = () => {
  getData();
};
const handleCancel = () => {
  visible.value = false;
};
</script>

<style scoped lang="scss">
.custom-page {
  padding-bottom: 0px;
}
h1 {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}
.search-bar {
  padding-left: 20px;
}
:deep(.el-dialog__body) {
  padding: 20px;
  height: calc(100vh - 300px);
  overflow-y: auto;
}
.form-title {
  font-size: 16px;
  font-weight: 500;
  margin: 30px 0;
  color: #333333;
}
.form-item {
  width: 500px;
  margin: 0 auto;
}
.dialog-footer {
  text-align: center;
}
.custom-search {
  display: flex;
  align-items: center;
  padding-left: 20px;

  .el-button {
    margin-left: 12px;
  }
}
</style>
