<template>
  <div class="pc-container">
    <NavigationBar></NavigationBar>
    <foldpanelLeft :title="xiaoquIntroduce.deptName + '简介'">
      <IndexModelLeft />
    </foldpanelLeft>
    <foldpanelRight>
      <IndexModelRight />
    </foldpanelRight>
    <mars-map @mapLoad="mapLoad" :options="options" ref="map">
      <template #select>
        <div class="select-search">
          <el-select
            v-model="community"
            placeholder="选择社区"
            clearable
            @change="handleChange"
            :popper-append-to-body="false"
          >
            <el-option
              v-for="dict in communityList"
              :key="dict.dept_id"
              :label="dict.dept_name"
              :value="dict.dept_id"
            >
            </el-option>
          </el-select>

          <el-select
            style="margin-left: 10px"
            v-model="xiaoqu"
            placeholder="选择小区"
            clearable
            v-show="xiaoquList.length > 0"
            :popper-append-to-body="false"
            @change="goXiaoqu"
          >
            <el-option
              v-for="dict in xiaoquList"
              :key="dict.xiaoqu_id"
              :label="dict.dept_name"
              :value="dict.xiaoqu_id"
            >
            </el-option>
          </el-select>
        </div>
      </template>
    </mars-map>
  </div>
</template>

<script>
import MarsMap from "@/components/mars-map";
import NavigationBar from "@/components/NavigationBar/index.vue";
import { mapGetters } from "vuex";
import {
  foldpanelLeft,
  IndexModelLeft,
  foldpanelRight,
  IndexModelRight,
} from "@/views/components/index.js";
import { getCommunitylist, getXiaoqulist } from "@/api/taicangpop/data.js";

export default {
  name: "Index",
  computed: {
    ...mapGetters(["dept", "xiaoquIntroduce"]),
  },
  components: {
    MarsMap,
    NavigationBar,
    foldpanelLeft,
    IndexModelLeft,
    foldpanelRight,
    IndexModelRight,
  },
  data() {
    const basePathUrl = window.basePathUrl || "";
    return {
      options: {
        scene: {
          center: {
            lat: 31.344002,
            lng: 121.120196,
            alt: 21247.4,
            heading: 355.1,
            pitch: -53.8,
          },
          showSun: false,
          showMoon: false,
          showSkyBox: false,
          showSkyAtmosphere: false,
          fog: false,
          backgroundColor: "rgba(0,0,0,0)",
          backgroundImage: `url(${require("../assets/images/ui/index_bg.jpg")})`,
          orderIndependentTranslucency: false,
          contextOptions: { webgl: { antialias: mars3d.Util.isPCBroswer() } },
          globe: {
            show: false, // 不显示地球
            showGroundAtmosphere: false,
            enableLighting: false,
          },
          clock: {
            currentTime: "2023-11-01 12:00:00", // 固定光照时间
          },
          cameraController: {
            zoomFactor: 1.5,
            minimumZoomDistance: 0.1,
            maximumZoomDistance: 200000,
            enableCollisionDetection: false, // 允许进入地下
          },
        },
      },
      community: 100,
      communityList: [],
      xiaoqu: "",
      xiaoquList: [],
      map: null,
      mapLayer: {},
      streetUrl: basePathUrl + "lib/geoJson/loujiangjiedao.json",
      shequUrl: basePathUrl + "lib/geoJson/shequ.json",
      xiaoquUrl: basePathUrl + "lib/geoJson/xiaoqu.json",
      roaduUrl: basePathUrl + "lib/geoJson/road.json",
      roaduNameUrl: basePathUrl + "lib/geoJson/road-name.json",
      riveruUrl: basePathUrl + "lib/geoJson/river.json",
      riverNameUrl: basePathUrl + "lib/geoJson/river-name.json",
    };
  },

  created() {
    if (this.$auth.hasRoleNet("network")) {
      this.$router.replace("/xiaoqu");
      return;
    }
    this.getCommunity();
    this.$store.dispatch("GetYjtotal");
    this.$store.dispatch("GetXiaoquInfo", this.dept.deptId);
    this.$store.dispatch("getThreeCell");
    this.$store.dispatch("GetcolorList");
  },
  methods: {
    goXiaoqu(id) {
      if (id == 260 || id == 254 || id == 257) {
        this.$modal.msgWarning("该小区功能暂未开放!");
        return;
      }

      this.$router.push({ path: "/xiaoqu", query: { xiaoquId: id } });
    },

    mapLoad(map) {
      let _this = this;
      this.map = map;

      map.on(mars3d.EventType.wheel, function (e) {
        _this.zoomChange();
      });

      this.addLayer();
      this.addstreet();
      this.addShequ();
      this.addXiaoqu();
      this.addRoad();
      this.addRiver();
    },
    zoomChange() {
      let level = this.map.level;
      this.mapLayer.shequ.eachGraphic((graphic) => {
        if (graphic.isPrivate) {
          return;
        }
        if (level >= 14) {
          // graphic.openHighlight(
          //   {
          //     label: {
          //       opacity: 0,
          //     },
          //   },
          //   false
          // );
        } else {
          graphic.closeHighlight();
        }
      });
      if (level >= 14) {
        this.mapLayer.xiaoqu.show = true;
      } else {
        this.mapLayer.xiaoqu.show = false;
      }
    },
    //河 - 河名
    addRiver() {
      mars3d.Util.fetchJson({ url: this.riveruUrl }).then((res) => {
        const arr = mars3d.Util.geoJsonToGraphics(res);
        arr.map((item, index) => {
          const graphic = new mars3d.graphic.PolylineEntity({
            positions: item.positions,
            style: {
              visibleDepth: false,
              addHeight: 10,
              width: 2,
              color: "#33816D",
              opacity: 0.8,
            },
          });
          this.mapLayer.river.addGraphic(graphic);
        });
      });
      mars3d.Util.fetchJson({ url: this.riverNameUrl }).then((res) => {
        const arr = mars3d.Util.geoJsonToGraphics(res);
        arr.map((item, index) => {
          const graphic = new mars3d.graphic.LabelEntity({
            name: "贴地文字",
            position: item.position,
            style: {
              addHeight: 11,
              visibleDepth: false,
              text: item.attr.TextString,
              font_size: 12,
              color: "#fff",
              outline: true,
              outlineColor: "#33816D",
              outlineOpacity: 1,
              outlineWidth: 4,
              hasPixelOffset: true,

              // 视距的设置
              scaleByDistance: true,
              scaleByDistance_far: 20000000,
              scaleByDistance_farValue: 0.1,
              scaleByDistance_near: 1000,
              scaleByDistance_nearValue: 1,
            },
          });
          this.mapLayer.river.addGraphic(graphic);
        });
      });
    },
    //路 - 路名
    addRoad() {
      mars3d.Util.fetchJson({ url: this.roaduUrl }).then((res) => {
        const arr = mars3d.Util.geoJsonToGraphics(res);
        arr.map((item, index) => {
          const graphic = new mars3d.graphic.PolylineEntity({
            positions: item.positions,
            style: {
              visibleDepth: false,
              addHeight: 1,
              width: 3,
              color: "#9D6E00",
              opacity: 0.8,
            },
          });
          this.mapLayer.road.addGraphic(graphic);
        });
      });
      mars3d.Util.fetchJson({ url: this.roaduNameUrl }).then((res) => {
        const arr = mars3d.Util.geoJsonToGraphics(res);
        arr.map((item, index) => {
          const graphic = new mars3d.graphic.LabelEntity({
            name: "贴地文字",
            position: item.position,
            style: {
              visibleDepth: false,
              text: item.attr.name,
              font_size: 12,
              color: "#fff",
              outline: true,
              outlineColor: "#9D6E00",
              outlineOpacity: 1,
              outlineWidth: 4,
              hasPixelOffset: true,

              // 视距的设置
              scaleByDistance: true,
              scaleByDistance_far: 20000000,
              scaleByDistance_farValue: 0.1,
              scaleByDistance_near: 1000,
              scaleByDistance_nearValue: 1,
            },
          });
          this.mapLayer.road.addGraphic(graphic);
        });
      });
    },
    //小区
    addXiaoqu() {
      mars3d.Util.fetchJson({ url: this.xiaoquUrl }).then((res) => {
        let _this = this;
        const arr = mars3d.Util.geoJsonToGraphics(res);
        arr.map((item, index) => {
          const polygonEntity = new mars3d.graphic.PolygonEntity({
            id: item.id,
            positions: item.positions,
            style: {
              addHeight: 10,
              fill: false,
              outline: true,
              fill: true,
              color:
                item.attr.Id == 254 ||
                item.attr.Id == 257 ||
                item.attr.Id == 260
                  ? "#545454"
                  : "#ffeb3b",
              opacity: 0.3,
              outlineWidth: 2,
              outlineColor:
                item.attr.Id == 254 ||
                item.attr.Id == 257 ||
                item.attr.Id == 260
                  ? "#545454"
                  : "#ffeb3b",
              label: {
                opacity: 1,
                text: item.attr.name,
                position: "center",
                font_size: 15,
                font_weight: "bold",
                color: "#ffeb3b",
                outline: true,
                outlineColor: "#111",
                outlineOpacity: 1,
                outlineWidth: 4,
                hasPixelOffset: true,
                pixelOffsetY: -2,
                // 视距的设置
                scaleByDistance: true,
                scaleByDistance_far: 20000000,
                scaleByDistance_farValue: 0.1,
                scaleByDistance_near: 1000,
                scaleByDistance_nearValue: 1,
              },
            },
          });
          this.mapLayer.xiaoqu.addGraphic(polygonEntity);

          polygonEntity.on(mars3d.EventType.click, function (e) {
            // console.log(e.id);
            _this.goXiaoqu(e.id);
          });
        });
      });
    },
    // 社区
    addShequ() {
      mars3d.Util.fetchJson({ url: this.shequUrl }).then((res) => {
        const arr = mars3d.Util.geoJsonToGraphics(res);
        arr.map((item, index) => {
          const polygonEntity = new mars3d.graphic.PolygonEntity({
            id: `shequ${item.id}`,
            positions: item.positions,
            style: {
              fill: true,
              color: "#057BEB",
              outline: true,
              outlineWidth: 2,
              outlineColor: "#6ED2FB",
              label: {
                opacity: 1,
                text: item.attr.COMNAME,
                position: "center",
                font_size: 15,
                font_weight: "bold",
                color: "#fff",
                outline: true,
                outlineColor: "#111",
                outlineOpacity: 0.5,
                outlineWidth: 3,
                hasPixelOffset: true,
                pixelOffsetY: -2,
                visibleDepth: false,
                // 视距的设置
                scaleByDistance: true,
                scaleByDistance_far: 20000000,
                scaleByDistance_farValue: 0.1,
                scaleByDistance_near: 1000,
                scaleByDistance_nearValue: 1,
              },
            },
          });
          this.mapLayer.shequ.addGraphic(polygonEntity);
        });
      });
    },
    //创建图层到map
    addLayer() {
      this.mapLayer.river = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.river);

      this.mapLayer.road = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.road);

      this.mapLayer.xiaoqu = new mars3d.layer.GraphicLayer({ show: false });
      this.map.addLayer(this.mapLayer.xiaoqu);

      this.mapLayer.shequ = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.shequ);

      this.mapLayer.street = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.mapLayer.street);
    },

    /**
     * 加载社区底图面
     */
    addstreet() {
      mars3d.Util.fetchJson({ url: this.streetUrl }).then((res) => {
        const arr = mars3d.Util.geoJsonToGraphics(res);

        arr.map((item, index) => {
          const wall = new mars3d.graphic.WallPrimitive({
            positions: item.positions[0],
            style: {
              setHeight: -2000,
              diffHeight: 2000, // 墙高
              width: 10,
              materialType: mars3d.MaterialType.Image2,
              materialOptions: {
                image: require("../assets/images/ui/fence-top.png"),
                color: "#4CE2F5",
              },
            },
          });
          this.mapLayer.street.addGraphic(wall);
        });
      });
    },

    handleChange(e) {
      if (!e) return;
      let _this = this;
      this.$store.dispatch("GetXiaoquInfo", e);
      this.xiaoqu = "";
      this.xiaoquList = this.communityList.filter(
        (item) => item.dept_id == e
      )[0].children;

      if (e == 100) {
        e = undefined;
        this.map.flyHome({
          duration: 1,
        });
        setTimeout(() => {
          this.zoomChange();
        }, 1200);
      } else {
        let shequItem = this.mapLayer.shequ.getGraphicByAttr(`shequ${e}`);
        this.map.flyToPoint(
          new mars3d.LngLatPoint(
            shequItem.centerPoint._lng,
            shequItem.centerPoint._lat
          ),
          {
            radius: 2776.4,
            duration: 1,
            complete: function () {
              if (_this.xiaoquList.length == 0) {
                shequItem.openHighlight({
                  outlineColor: "#ffeb3b",
                  outlineWidth: 5,
                });
              } else {
                _this.zoomChange();
              }
            },
          }
        );
      }
      this.$store.dispatch("GetYjtotal", {
        shequId: e,
      });
      this.$store.commit("SET_QUERY_PARAMS", { shequId: e });
      this.$store.dispatch("getThreeCell", {
        shequId: e,
      });
      this.$store.dispatch("GetcolorList", {
        shequId: e,
      });
    },

    getCommunity() {
      let community = new Promise((resolve, reject) => {
        getCommunitylist().then((res) => {
          res.data["社区list集合"].unshift({
            dept_name: "全部社区",
            dept_id: this.dept.deptId,
          });
          resolve(res.data["社区list集合"]);
        });
      });

      let xiaoqu = new Promise((resolve, reject) => {
        getXiaoqulist().then((res) => {
          resolve(res.data["小区list集合"]);
        });
      });

      Promise.all([community, xiaoqu]).then((res) => {
        this.communityList = res[0].map((item) => {
          item.children = [];
          res[1].forEach((it) => {
            if (item.dept_id == it.shequ_id) item.children.push(it);
          });
          return item;
        });
      });
    },
  },
};
</script>

<style scoped lang="scss">
.pc-container {
  position: relative;
  height: 100%;
  box-sizing: border-box;
  // background: url("~@/assets/images/ui/index_bg.jpg");
  background-size: 100% 100%;
  overflow: hidden;
}

::v-deep .select-search {
  position: absolute;
  left: 410px;
  top: 110px;

  .el-select {
    width: 160px;
    .el-input {
      background: transparent;
    }
    .el-input__inner {
      height: 45px;
      line-height: 45px;
      color: #fff;
      background: url("~@/assets/images/ui/img_btn_search.png");
      background-size: 100% 100%;
      border: 0px !important;
    }
    .el-input__inner::placeholder,
    .el-select__caret {
      color: #fff;
    }
  }
}
</style>
