<template>
  <div class="mars3D-container">
    <div id="leaflet-map"></div>
    <div class="map-search" id="mapSearch">
      <div class="search-input">
        <input
          type="text"
          v-model="queryParams.signName"
          placeholder="请输入店铺名称"
        />
        <div class="search-sub" @click="handlerSearch()">搜索</div>
      </div>

      <div class="search-result" v-show="shopShow">
        <div
          class="reslut-item"
          v-for="item in shopList"
          :key="item.id"
          @click="mapLocation(item)"
        >
          {{ item.signName }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import sm_shop from "./sm_shop.json";
import { getBShop, updateBShop } from "@/api/other.js";
import { getToken } from "@/utils/auth";
import axios from "axios";
export default {
  props: {
    xiaoquId: {
      type: String,
      default: "",
    },
  },

  mounted() {
    this.initMap();

    document.addEventListener("click", this.handleClickOutside);
  },
  beforeDestroy() {
    document.removeEventListener("click", this.handleClickOutside);
    const element = document.getElementById("mapSearch");
    if (element) {
      element.remove();
    }
  },
  data() {
    const basePathUrl = window.basePathUrl || "";
    return {
      queryParams: {
        signName: undefined,
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      shopLayer: null,
      shopShow: false,
      shopParams: {
        signName: undefined,
      },
      shopList: [],
      popupImage: undefined,
      configUrl: basePathUrl + "config/config.json",
      map: null,
      mapLayer: {
        picture: null,
        geoJsonLayer: null,
        textMarker: null,
        Popup: null,
      },
      highlightStyle: {
        fill: true,
        fillColor: "#FD873F",
        fillOpacity: 0.9,
        color: "#02F5FF", //描边颜色
        weight: 2, //描边宽度
      },
      previousLayer: null,
    };
  },
  methods: {
    closehighlightStyle() {
      this.map.closePopup();
      this.handlehighlight();
    },
    mapLocation(item) {
      this.map.closePopup();
      this.shopShow = false;
      this.geojson.eachLayer((layer) => {
        let id =
          layer.feature.properties["楼号"] + layer.feature.properties["门牌号"];
        if (id == item.buildingId + item.houseNumber) {
          this.handlehighlight();
          this.previousLayer = layer;
          layer.setStyle(this.highlightStyle);
          let point = layer._bounds.getCenter();
          this.map.setView([point.lat, point.lng], 19);
        }
      });
    },
    async handlerSearch() {
      if (!this.queryParams.signName) return;
      let res = await getBShop(this.queryParams);
      if (res.rows.length == 0) {
        this.$modal.msgWarning(`未查询到${this.queryParams.signName}`);
        return;
      }
      this.shopList = res.rows;
      this.shopShow = true;
    },
    handleClickOutside(event) {
      if (
        this.shopShow &&
        !document.getElementById("mapSearch").contains(event.target)
      ) {
        this.shopShow = false;
      }
    },

    /**初始化地图 */
    initMap() {
      this.map = L.map("leaflet-map", {
        center: [31.478296, 121.089856], // 地图中心[纬度，经度]
        zoom: 15, // 地图层级
        maxZoom: 19,
        minZoom: 11,
        zoomControl: false, // 放大缩小按钮
        attributionControl: false, // 右下角leaflet图标
      });
      this.mapLayer.picture = L.tileLayer(
        "https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
        {
          maxZoom: 19,
          minZoom: 9,
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
        }
      ).addTo(this.map);

      this.map.createPane("geoJsonLayer");
      this.map.getPane("geoJsonLayer").style.zIndex = 502;
      this.map.getPane("geoJsonLayer").style.pointerEvents = "none";
      this.mapLayer.geoJsonLayer = L.featureGroup().addTo(this.map);

      this.map.createPane("textMarker");
      this.map.getPane("textMarker").style.zIndex = 503;
      this.map.getPane("textMarker").style.pointerEvents = "none";
      this.mapLayer.textMarker = L.featureGroup().addTo(this.map);

      this.initShop();
    },

    handlehighlight() {
      // 重置上一个高亮图层样式
      if (this.previousLayer) {
        this.geojson.resetStyle(this.previousLayer);
      }
    },

    /**
     * 渲染商铺面数据
     */
    initShop() {
      this.geojson = L.geoJSON(sm_shop, {
        pane: "geoJsonLayer",
        style: {
          fill: true,
          fillColor: "#0B3369",
          fillOpacity: 0.9,
          color: "#02F5FF", //描边颜色
          weight: 2, //描边宽度
        },
        onEachFeature: (feature, layer) => {
          let itemData = feature.properties;
          // 创建文字标记
          if (
            layer._bounds &&
            layer._bounds._northEast &&
            layer._bounds._southWest
          ) {
            let point = layer._bounds.getCenter();
            this.addTextMarker(itemData["门牌号"], point);
          }
          if (!itemData.isClick) {
            //绑定
            layer.bindPopup(
              this.bindPopup(itemData["楼号"], itemData["门牌号"]),
              {
                minWidth: 380,
                className: "diyPopup",
                closeButton: false,
              }
            );
            //点击
            layer.on("click", async () => {
              this.handlehighlight(layer);
              layer.setStyle(this.highlightStyle);
              this.previousLayer = layer;
            });
            //打开
            layer.on("popupopen", async () => {
              const res = await getBShop({
                buildingId: itemData["楼号"],
                houseNumber: itemData["门牌号"],
              });
              if (res.rows.length === 0) return;
              let listItem = res.rows[0];
              this.popupImage = undefined;
              setTimeout(() => {
                // 回显弹窗内容
                let image = document.getElementById("shopImgae");
                let name = document.getElementById("shopName");
                let phone = document.getElementById("shopPhone");
                let category = document.getElementById("shopCategory");
                let status = document.getElementById("shopStatus");
                let signName = document.getElementById("shopSignName");
                let shopArea = document.getElementById("shopShopArea");
                let businessLicense =
                  document.getElementById("businessLicense");

                image.src = this.filterSignImage(listItem.photo);
                name.value = listItem.name;
                phone.value = listItem.phone;
                category.value = listItem.category;
                status.value = listItem.status;
                signName.value = listItem.signName;
                shopArea.value = listItem.shopArea;
                businessLicense.value = listItem.businessLicense;

                document
                  .getElementById("popup-close")
                  .addEventListener("click", (event) => {
                    this.handlehighlight(layer);
                    layer.closePopup();
                  });

                //修改按钮
                document
                  .getElementById("updateBtn")
                  .addEventListener("click", (event) => {
                    document.getElementById("updateBtn").style.display = "none";
                    this.handlerPopup(false, null, {
                      name,
                      phone,
                      category,
                      status,
                      signName,
                      shopArea,
                      businessLicense,
                    });
                  });
                //保存
                document
                  .getElementById("submit")
                  .addEventListener("click", (event) => {
                    this.handlerPopup(true, listItem.id, {
                      name,
                      phone,
                      category,
                      status,
                      signName,
                      shopArea,
                      businessLicense,
                    });
                  });

                //更改图片
                document
                  .getElementById("uploadButton")
                  .addEventListener("click", function () {
                    document.getElementById("fileInput").click();
                  });

                // 选中图片
                document
                  .getElementById("fileInput")
                  .addEventListener("change", (e) => {
                    const file = e.target.files[0];
                    if (!file) {
                      return; // 如果没有选择文件，则不做任何事情
                    }
                    const formData = new FormData();
                    formData.append("file", file);
                    axios
                      .post(this.uploadImgUrl, formData, {
                        headers: this.headers,
                      })
                      .then((res) => {
                        image.src =
                          process.env.VUE_APP_BASE_API + res.data.fileName;
                        this.popupImage = res.data.fileName;
                      });
                  });
              }, 400);
            });
            //关闭
            layer.on("popupclose", async () => {
              this.handlehighlight();
            });
          }
        },
      }).addTo(this.mapLayer.geoJsonLayer);
      this.map.fitBounds(this.geojson.getBounds());
    },

    addTextMarker(name, point) {
      // console.log("sss");
      var myIcon = L.divIcon({
        className: "building-marker",
        html: `<div class="marker-name">${name}</div>`,
      });
      L.marker([point.lat, point.lng], {
        icon: myIcon,
        interactive: false, //禁止marker交互，防止遮挡点不到面
      }).addTo(this.mapLayer.textMarker);
    },

    bindPopup() {
      let html = `
            <div class="mypopup" id="shopPopup">
              <div id="popup-close"></div>
        <div class="shop-dialogs">
                        <div class="tab-title">
                          <div class="tab-list">
                            <div class="tab-item">商铺信息</div>
                          </div>
                          <div class="tab-btn-group">
                              <div id="updateBtn">
                                <span></span>
                                修改</div>
                              <div id="submit">
                                <span></span>
                                保存</div>
                            </div>
                          </div>
                          <div class="image-box">
                            <div class="file-upload" id="uploadBox">
                               <input type="file" id="fileInput" accept="image/*" style="display: none">
                                <button id="uploadButton">更换图片</button>
                              </div>
                              <img src="" id="shopImgae"  class="shop-image"/>

                            </div>

                        <div class="shop-rows">
                            <div class="row-item flex-div">
                                  <div >
                                  <div class="item-lable">负责人：</div>
                                  <input id="shopName" class="item-value" type="text" value=""  readonly>
                                  </div>
                                  <div >
                                  <div class="item-lable">电话：</div>
                                  <input id="shopPhone" class="item-value" type="text" value="" readonly>
                                  </div>
                              </div>

                              <div class="row-item flex-div">
                                  <div >
                                  <div class="item-lable">经营类别：</div>
                                  <input id="shopCategory" class="item-value" type="text" value="" readonly>
                                  </div>
                                  <div >
                                  <div class="item-lable">经营状态：</div>
                                  <input id="shopStatus" class="item-value" type="text" value="" readonly>
                                  </div>
                              </div>
                              <div class="row-item flex-div">
                                <div >
                                  <div class="item-lable">商铺名称：</div>
                                  <input id="shopSignName" class="item-value" type="text" value="" readonly>
                                  </div>
                                   <div >
                                  <div class="item-lable">面积㎡：</div>
                                  <input id="shopShopArea" class="item-value" type="text" value="" readonly>
                                  </div>
                              </div>

                                 <div class="row-item flex-div">
                                <div style="width: 100%;">
                                  <div class="item-lable" style="width: 24%;">营业执照名称：</div>
                                  <input id="businessLicense" class="item-value" type="text" value=""  readonly style="width: 76%;">
                                  </div>

                              </div>
                          </div>
        </div>
      </div>
      `;

      return html;
    },

    filterSignImage(photo) {
      if (photo) {
        return process.env.VUE_APP_BASE_API + photo;
      } else {
        return require("@/assets/images/ui/no-image.png");
      }
    },
    handlerPopup(isBoolean, id, elemnet) {
      let imageBox = document.getElementById("uploadBox");
      imageBox.style.display = "block";
      let subBtn = document.getElementById("submit");
      subBtn.style.display = isBoolean ? "none" : "block";
      // console.log(elemnet);
      elemnet.name.readOnly = isBoolean;
      elemnet.phone.readOnly = isBoolean;
      elemnet.category.readOnly = isBoolean;
      elemnet.status.readOnly = isBoolean;
      elemnet.signName.readOnly = isBoolean;
      elemnet.shopArea.readOnly = isBoolean;
      elemnet.businessLicense.readOnly = isBoolean;

      //报错
      if (isBoolean) {
        let data = {
          id: id,
          photo: this.popupImage,
          name: elemnet.name.value,
          phone: elemnet.phone.value,
          category: elemnet.category.value,
          status: elemnet.status.value,
          signName: elemnet.signName.value,
          shopArea: elemnet.shopArea.value,
          businessLicense: elemnet.businessLicense.value,
        };
        updateBShop(data).then((res) => {
          elemnet.name.readOnly = true;
          elemnet.phone.readOnly = true;
          elemnet.category.readOnly = true;
          elemnet.status.readOnly = true;
          elemnet.signName.readOnly = true;
          elemnet.shopArea.readOnly = true;
          elemnet.businessLicense.readOnly = true;
          document.getElementById("updateBtn").style.display = "block";
          imageBox.style.display = "none";
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.mars3D-container {
  position: relative;
  height: 100%;
  overflow: hidden;
  background: white;
}
#leaflet-map {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 10;
  height: 100%;
  width: 100%;
}
.map-search {
  position: absolute;
  top: 120px;
  z-index: 101;
  right: 410px;
  width: 250px;
  .search-input {
    display: flex;
    align-items: center;
    height: 40px;
    border: 1px solid rgba(2, 101, 203, 1);
    input {
      flex: 1;
      padding-left: 6px;
      height: 100%;
      border: 0;
      caret-color: rgba(2, 101, 203, 1);
      background: rgba(10, 37, 72, 1);
      color: #fff;
      font-size: 14px;
    }
    input::placeholder {
      font-size: 14px;
      color: rgba(119, 185, 254, 0.4);
    }
    input:focus-visible {
      border: 0;
      outline: none;
    }
    .search-sub {
      width: 65px;
      height: 100%;
      cursor: pointer;
      font-size: 14px;
      color: #ffffff;
      font-weight: bold;
      line-height: 39px;
      text-align: center;
      background: linear-gradient(0deg, #053261 20%, #0268d2 100%);
      border-left: 1px solid #0265cb;
    }
  }
  .search-result {
    margin-top: 5px;
    width: 100%;
    height: 200px;
    border: 1px solid rgba(2, 101, 203, 1);
    background: rgba(10, 37, 72, 1);
    overflow-y: auto;
    .reslut-item {
      font-size: 14px;
      color: #c8f1ff;
      padding: 6px;
    }
    .reslut-item:hover {
      cursor: pointer;
      background: #0265cb;
    }
  }
}
</style>
