<template>
  <div class="container">
    <div class="input-card-right">
      <div class="img">
        <image-upload :limit="1" :isShowTip="false" v-model="picture" />
      </div>

      <el-button :style="topRightCoord ? buttonStyleActive : buttonStyleInactive" @click="setClickType('topRight')">
        点击右上角坐标
      </el-button>

      <el-button :style="bottomLeftCoord ? buttonStyleActive : buttonStyleInactive" @click="setClickType('bottomLeft')">
        点击左下角坐标
      </el-button>

      <el-button @click="generateMap" :disabled="!canGenerateMap">
        生成导览地图
      </el-button>

      <el-button @click="saveMap" :disabled="!canSaveMap">
        保存
      </el-button>
    </div>

    <div id="amap-container" class="map-container"></div>

    <div class="coordinates">
      <div v-if="topRightCoord">右上角: {{ topRightCoord }}</div>
      <div v-if="bottomLeftCoord">左下角: {{ bottomLeftCoord }}</div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import globalConfig from '@/utils/config/globalConfig';
import { getArea, putguide } from "@/api/system/area";

export default {
  name: "NewPage",

  data() {
    return {
      map: null,
      clickType: null,
      topRightCoord: null,
      bottomLeftCoord: null,
      markers: [],
      picture: '',
      buttonStyleActive: 'background-color: #409EFF; color: white;',
      buttonStyleInactive: 'background-color: #fff; color: #409EFF;',
      areaLon: null,
      areaLat: null,
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        parkingName: null,
        areaId: null,
        type: "2"
      },
      // 默认区域id
      defaultAreaId: "",
      isMapGenerated: false,
    };
  },
  computed: {
    canGenerateMap() {
      return this.picture && this.topRightCoord && this.bottomLeftCoord;
    },
    canSaveMap() {
      return this.isMapGenerated;
    }
  },
  created() {
    const areaId = this.$route.params && this.$route.params.areaId;
    this.getArea(areaId);
  },
  mounted() {
    this.initMap();
  },
  methods: {
    /** 查询运营区域详细 */
    getArea(areaId) {
      getArea(areaId).then(response => {
        this.queryParams.areaId = response.data.areaId;
        this.areaLon = response.data.longitude;
        this.areaLat = response.data.latitude;
        this.defaultAreaId = response.data.areaId;
      });
    },
    initMap() {
      AMapLoader.load({
        key: globalConfig.aMap.key,
        version: "2.0",
        plugins: [
          "AMap.ToolBar",
          "AMap.Driving",
          "AMap.PolygonEditor",
          "AMap.PlaceSearch",
        ],
      }).then((AMap) => {
        this.map = new AMap.Map("amap-container", {
          viewMode: "3D",
          zoom: 13,
          center: [this.areaLon, this.areaLat], // 初始化地图中心点位置
        });
        this.map.setFitView();
        this.map.on('click', this.handleMapClick);
      }).catch((e) => {
        console.error(e);
      });
    },
    setClickType(type) {
      this.clickType = type;
      // 清除相应的坐标和标记
      if (type === 'topRight' && this.topRightCoord) {
        this.clearMarker('topRight');
        this.topRightCoord = null;
      } else if (type === 'bottomLeft' && this.bottomLeftCoord) {
        this.clearMarker('bottomLeft');
        this.bottomLeftCoord = null;
      }
    },
    handleMapClick(event) {
      const lnglat = event.lnglat;

      // 只有在点击了“右上角坐标”或“左下角坐标”按钮后才能添加标记
      if (this.clickType === 'topRight') {
        this.topRightCoord = lnglat;
        this.addMarker(lnglat, 'topRight');
      } else if (this.clickType === 'bottomLeft') {
        this.bottomLeftCoord = lnglat;
        this.addMarker(lnglat, 'bottomLeft');
      }

      // 清除点击类型
      this.clickType = null;
    },
    addMarker(lnglat, type) {
      // 清除之前的标记
      this.clearMarker(type);

      // 创建新标记
      const marker = new AMap.Marker({
        position: lnglat,
      });
      this.map.add(marker);
      this.markers.push({ marker, type });
    },
    clearMarker(type) {
      this.markers = this.markers.filter(({ marker, type: markerType }) => {
        if (markerType === type) {
          this.map.remove(marker);
          return false;
        }
        return true;
      });
    },
    generateMap() {
      if (!this.canGenerateMap) {
        this.$message.error('请上传图片并选择两个坐标点');
        return;
      }

      // 确保坐标精度
      const lnglatToFixed = (lnglat) => ({
        lng: lnglat.lng.toFixed(6),
        lat: lnglat.lat.toFixed(6)
      });

      const topRight = lnglatToFixed(this.topRightCoord);
      const bottomLeft = lnglatToFixed(this.bottomLeftCoord);

      console.log('Top Right:', topRight);
      console.log('Bottom Left:', bottomLeft);

      // 计算边界
      const bounds = new AMap.Bounds([bottomLeft.lng, bottomLeft.lat], [topRight.lng, topRight.lat]);

      console.log('Bounds:', bounds);

      // 创建图片图层
      const imageLayer = new AMap.ImageLayer({
        url: this.picture,
        bounds: bounds,
        zooms: [15, 20],
        zIndex: 999 // 设置zIndex确保图层在其他图层之上
      });

      // 清除现有图层
      this.map.getLayers().forEach(layer => {
        if (layer instanceof AMap.ImageLayer) {
          this.map.remove(layer);
        }
      });

      // 添加图片图层
      this.map.add(imageLayer);

      // 设置地图已生成的标志
      this.isMapGenerated = true;
    },
    saveMap() {
      if (!this.canSaveMap) {
        this.$message.error('请先生成导览地图');
        return;
      }

      // 格式化坐标为字符串格式，不包含方括号
      const formatLngLat = (lnglat) => `${lnglat.lng},${lnglat.lat}`;

      // 保存逻辑
      const mapData = {
        guideMap: this.picture,
        upperRight: formatLngLat(this.topRightCoord),
        lowerLeft: formatLngLat(this.bottomLeftCoord),
        areaId: this.defaultAreaId
      };

      putguide(mapData).then(response => {
        // 处理更新后的响应
      });

      // 例如，将 mapData 发送到后端保存
      console.log('保存地图数据:', mapData);
      this.$message.success('地图数据已保存');
    }
  },
};
</script>

<style scoped lang="scss">
.map-container {
  width: 100%;
  height: 90vh;
}

.container {
  position: relative;
  border: 1px solid rgb(204, 204, 204);
}

.input-card-right {
  position: fixed;
  top: 100px;
  left: 230px;
  z-index: 100;
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
  align-items: flex-end;
  margin-bottom: 10px;
}

.img {
  width: 150px;
  height: 150px;
}

.coordinates {
  position: absolute;
  bottom: 15px;
  left: 15px;
  background: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 5px;
}
</style>
