<template>
  <div class="field-management">
    <!-- 左侧面板 -->
    <div class="panel left">
      <el-input v-model="searchTerm" placeholder="搜索地块名称" clearable style="margin-bottom: 15px"></el-input>

      <el-table :data="filteredFields" highlight-current-row style="width: 100%" height="calc(100vh - 300px)" @row-click="selectField">
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="area" label="面积(㎡)">
          <template #default="{ row }">
            {{ row.area.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="stats">总面积: {{ totalArea.toFixed(2) }} ㎡</div>

      <div class="button-group">
        <el-button type="primary" @click="startDrawing">新增地块</el-button>
        <el-button type="danger" :disabled="!selectedField" @click="removeField">删除地块</el-button>
      </div>
    </div>

    <!-- 右侧地图区域 -->
    <div class="panel right">
      <tdt-map class="map" :center="mapCenter" :zoom="mapZoom" @init="onMapInit"> </tdt-map>

      <div class="layer-switch">
        <el-radio-group v-model="layerType" size="small" @change="changeBaseLayer">
          <el-radio-button label="vector">矢量</el-radio-button>
          <el-radio-button label="image">影像</el-radio-button>
        </el-radio-group>
      </div>

      <div class="field-layer-switch">
        <el-switch v-model="showFieldLayer" active-text="显示地块"></el-switch>
      </div>

      <div class="zoom-scale">缩放级别: {{ mapZoom }}, 比例尺: 1:{{ scale.toLocaleString() }}</div>

      <el-dialog v-model="drawDialogVisible" title="新增地块">
        <el-form>
          <el-form-item label="地块名称">
            <el-input v-model="newFieldName"></el-input>
          </el-form-item>
          <el-form-item label="地块面积">
            <el-input :value="newFieldArea.toFixed(2) + ' ㎡'" readonly></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="cancelDrawing">取消</el-button>
          <el-button type="primary" @click="saveNewField">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { TdtMap } from 'vue-tianditu';
import { ElMessage } from 'element-plus';
// import { map_config } from '../../config/map';

// 模拟接口服务（使用localStorage）
const fieldService = {
  getFields() {
    const fields = localStorage.getItem('fields');
    return Promise.resolve(fields ? JSON.parse(fields) : []);
  },
  createField(field) {
    return this.getFields().then((fields) => {
      field.id = Date.now();
      fields.push(field);
      localStorage.setItem('fields', JSON.stringify(fields));
      return field;
    });
  },
  deleteField(id) {
    return this.getFields().then((fields) => {
      const newFields = fields.filter((f) => f.id !== id);
      localStorage.setItem('fields', JSON.stringify(newFields));
      return newFields;
    });
  },
};

// 响应式状态
const fields = ref([]);
const selectedField = ref(null);
const searchTerm = ref('');
const newFieldName = ref('');
const drawDialogVisible = ref(false);
const newFieldCoords = ref([]);
const newFieldArea = ref(0);
const layerType = ref('vector');
const showFieldLayer = ref(true);
const map = ref(null);
const mapCenter = ref([100.088, 23.883]);
const mapZoom = ref(12);
const scale = ref(0);

// 天地图图层
const baseLayers = {
  vector: null,
  vectorLabel: null,
  image: null,
  imageLabel: null,
};

// 覆盖物图层
const overlayLayer = ref(null);

// 计算属性
const filteredFields = computed(() => {
  const term = searchTerm.value.toLowerCase();
  return term ? fields.value.filter((f) => f.name.toLowerCase().includes(term)) : fields.value;
});

const totalArea = computed(() => {
  return fields.value.reduce((sum, field) => sum + field.area, 0);
});

// 地图初始化
const onMapInit = (mapInstance) => {
  map.value = mapInstance;

  // 创建图层
  baseLayers.vector = new T.TileLayer('vec');
  baseLayers.vectorLabel = new T.TileLayer('cva');
  baseLayers.image = new T.TileLayer('img');
  baseLayers.imageLabel = new T.TileLayer('cia');

  // 添加默认图层
  map.value.addLayer(baseLayers.image);
  map.value.addLayer(baseLayers.imageLabel);

  // 创建覆盖物图层
  overlayLayer.value = new T.Map.OverlayLayer();
  map.value.addLayer(overlayLayer.value);

  // 添加控件
  map.value.addControl(new T.Control.Zoom());
  map.value.addControl(new T.Control.Scale());

  // 事件监听
  map.value.addEventListener('zoomend', updateScale);
  map.value.addEventListener('moveend', updateScale);

  // 初始加载数据
  loadFields();
};

// 更新比例尺
const updateScale = () => {
  if (map.value) {
    mapZoom.value = map.value.getZoom();
    scale.value = Math.round(map.value.getScale());
  }
};

// 切换底图
const changeBaseLayer = () => {
  if (!map.value) return;

  // 移除当前底图
  map.value.removeLayer(baseLayers.vector);
  map.value.removeLayer(baseLayers.vectorLabel);
  map.value.removeLayer(baseLayers.image);
  map.value.removeLayer(baseLayers.imageLabel);

  // 添加新底图
  if (layerType.value === 'vector') {
    map.value.addLayer(baseLayers.vector);
    map.value.addLayer(baseLayers.vectorLabel);
  } else {
    map.value.addLayer(baseLayers.image);
    map.value.addLayer(baseLayers.imageLabel);
  }
};

// 加载地块数据
const loadFields = () => {
  fieldService.getFields().then((data) => {
    fields.value = data;
    refreshOverlays();
  });
};

// 刷新覆盖物
const refreshOverlays = () => {
  if (!map.value || !overlayLayer.value) return;

  // 清除所有覆盖物
  overlayLayer.value.clearOverLays();

  // 如果不显示地块图层则跳过绘制
  if (!showFieldLayer.value) return;

  // 绘制所有地块
  fields.value.forEach((field) => {
    const isSelected = selectedField.value?.id === field.id;
    const polygon = createPolygon(field, isSelected);
    overlayLayer.value.addOverLay(polygon);
  });
};

// 创建多边形
const createPolygon = (field, isSelected = false) => {
  const coords = field.geometry.coordinates[0].map((c) => new T.LngLat(c[0], c[1]));
  return new T.Polygon(coords, {
    color: isSelected ? '#ff0000' : '#1890ff',
    weight: isSelected ? 3 : 2,
    opacity: 0.8,
    fillColor: isSelected ? '#ffa39e' : '#e6f7ff',
    fillOpacity: 0.5,
  });
};

// 选择地块
const selectField = (field) => {
  selectedField.value = field;
  refreshOverlays();

  // 居中显示选中地块
  if (map.value) {
    const coords = field.geometry.coordinates[0];
    const center = coords.reduce(
      (acc, coord) => {
        acc[0] += coord[0];
        acc[1] += coord[1];
        return acc;
      },
      [0, 0]
    );

    center[0] /= coords.length;
    center[1] /= coords.length;

    map.value.panTo(new T.LngLat(center[0], center[1]));
  }
};

// 开始绘制
const startDrawing = () => {
  if (!map.value) return;

  // 清除当前覆盖物
  refreshOverlays();

  // 创建绘制工具
  const polygonTool = new T.PolygonTool(map.value, {
    showLabel: true,
    color: '#fa541c',
    weight: 3,
    opacity: 0.6,
    fillColor: '#ffbb96',
    fillOpacity: 0.4,
  });

  polygonTool.open();

  // 绘制完成事件
  polygonTool.addEventListener('draw', (e) => {
    newFieldCoords.value = e.currentLnglats.map((lnglat) => [lnglat.lng, lnglat.lat]);
    newFieldArea.value = e.currentArea;
    drawDialogVisible.value = true;

    // 清除临时图形
    polygonTool.close();
  });
};

// 保存新地块
const saveNewField = () => {
  if (!newFieldName.value.trim()) {
    ElMessage.error('请输入地块名称');
    return;
  }

  const newField = {
    id: Date.now(),
    name: newFieldName.value,
    area: newFieldArea.value,
    geometry: {
      type: 'Polygon',
      coordinates: [newFieldCoords.value],
    },
  };

  fieldService.createField(newField).then(() => {
    ElMessage.success('地块创建成功');
    drawDialogVisible.value = false;
    newFieldName.value = '';
    loadFields();
  });
};

// 取消绘制
const cancelDrawing = () => {
  drawDialogVisible.value = false;
  refreshOverlays();
};

// 删除地块
const removeField = () => {
  if (!selectedField.value) return;

  fieldService.deleteField(selectedField.value.id).then(() => {
    ElMessage.success('地块已删除');
    selectedField.value = null;
    loadFields();
  });
};

// 监听地块图层显示状态
watch(showFieldLayer, refreshOverlays);
</script>

<style scoped>
.field-management {
  display: flex;
  height: calc(100vh - 160px);
}

.panel.left {
  width: 320px;
  padding: 15px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
}

.panel.right {
  flex: 1;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

.layer-switch {
  position: absolute;
  top: 15px;
  right: 15px;
  background: white;
  padding: 8px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

.field-layer-switch {
  position: absolute;
  top: 60px;
  right: 15px;
  background: white;
  padding: 8px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 8px;
}

.zoom-scale {
  position: absolute;
  bottom: 15px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255, 255, 255, 0.85);
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

.stats {
  padding: 12px;
  margin: 10px 0;
  background: #edf2ff;
  border-radius: 4px;
  font-weight: 500;
  color: #364fc7;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.button-group > * {
  flex: 1;
}
</style>
