<template>
  <div>
    <!-- <cpt-bread
      @tap="clickBreadItem"
      v-if="breadList.length > 1"
      :bread-list="breadList"
    /> -->
    <div class="g-row">
      <div class="g-left">
        <div class="m-box">
          <title-box
              :text="`${currentLevel === 'district' ? '区' : currentLevel === 'street' ? '街道' : currentLevel === 'community' ? '社区' : currentLevel === 'grid' ? '网格' : ''}介绍`"/>
          <jdjs :currentLevelData="currentLevelData"/>
        </div>
        <div class="m-box">
          <title-box text="需求清单"/>
          <RequirementList :currentLevelData="currentLevelData"/>
        </div>
      </div>
      <div class="g-center">
        <div :class="listShow ? 'm-map' : 'g-center-open'" style="overflow: hidden">
          <map-top :currentLevelData="currentLevelData" :level="currentLevel" :peopleType="peopleType"
                   @changeType="changeType"/>
          <div v-if="breadList.length > 1" class="go-back" @click="goBackMap">
            <img src="~@/assets/images/shuju/overview/go-back.png"/>
          </div>
          <grid-map
              ref="map"
              :level="currentLevel"
              :peopleType="peopleType"
              :srcGridData="orgData"
              @clickAgency="clickAgencyItem"
              @clickDotBtn="handleClickDotBtn"
              @resourcesPointClick="resourcesPointClick"
              @showMapDialog="showMapDialog"
          />
          <div class="map-legend">
            <div class="legend-title">
              供需匹配地图
            </div>
            <div class="legend-list">
              <div class="legend-item blue">
                未完成需求
              </div>
              <div class="legend-item orange">
                难解决问题
              </div>
              <div class="legend-item green">
                可调配资源
              </div>
              <div class="legend-item red">
                不满意问题
              </div>
            </div>
          </div>
        </div>

      </div>

      <div class="g-right">

        <div class="m-box">
          <title-box text="问题清单"></title-box>
          <wtqd v-if="eventType === 1" :currentLevelData="currentLevelData" :date="sjhfDate"/>
        </div>

      </div>
    </div>
    <!--
      -- MapDialog
      -- type必填
      -- njjwtqk = 难解决问题情况
      -- bmysxqk = 不满意事项情况
      -- xqwwcqk = 需求未完成情况
    -->
    <MapDialog v-if="isShowMapDialog" ref="MapDialog" :currentLevelData="currentLevelData" :type="mapType"
               @close="isShowMapDialog = false"/>
    <cpt-loading v-show="false"/>
    <MapResourceInfo ref="MapResourceInfo" :currentLevelData="currentLevelData"/>
  </div>
</template>
<script>
import gridMap from "@/views/dataBoard/cpts/sjkb-map/index";
import cptBread from "@/views/dataBoard/renfang/cpts/bread";
import cptLoading from "@/views/dataBoard/cpts/loading";
import titleBox from "@/views/dataBoard/satisfactionEval/components/Title";
import jdjs from "@/views/dataBoard/overview/components/jdjs.vue";
import jdtphx from "@/views/dataBoard/overview/components/jdtphx.vue";
import mapTop from "@/views/dataBoard/overview/components/map-top.vue";
import jdwgy from "@/views/dataBoard/overview/components/jdwgy.vue";
import rfsjtj from "@/views/dataBoard/overview/components/rfsjtj.vue";
import sqrfph from "@/views/dataBoard/overview/components/sqrfph.vue";
import sq12345 from "@/views/dataBoard/overview/components/sq12345.vue";
import RequirementList from "@/views/dataBoard/overview/components/RequirementList.vue";

import DynamicHumanRoomData from "@/views/dataBoard/overview/components/DynamicHumanRoomData.vue";
import GridUpdateRanking from "@/views/dataBoard/overview/components/GridUpdateRanking.vue";
import CommunityResult from "@/views/dataBoard/overview/components/CommunityResult.vue";
import EventAndFollowUp from "@/views/dataBoard/overview/components/EventAndFollowUp.vue";
import wtqd from "@/views/dataBoard/overview/components/wtqd.vue";
import MapDialog from "@/views/dataBoard/overview/components/MapDialog/index.vue";

import RankingGridData from "@/views/dataBoard/overview/components/RankingGridData.vue";
import FollowUp from "@/views/dataBoard/overview/components/FollowUp.vue";
import Tabs from "@/views/dataBoard/satisfactionEval/components/Tabs/index.vue";

import {requestPostBi} from "@/js/dai/request-bipass";
import {requestPost} from "@/js/dai/request";
import {spliceIntoChunks} from "@/utils/index";
import MapResourceInfo from "@/views/dataBoard/overview/components/MapResourceInfo.vue";

export default {
  name: "overview",

  components: {
    gridMap,
    cptLoading,
    cptBread,
    titleBox,
    jdjs,
    jdtphx,
    mapTop,
    jdwgy,
    rfsjtj,
    sqrfph,
    sq12345,
    DynamicHumanRoomData,
    CommunityResult,
    EventAndFollowUp,
    RankingGridData,
    GridUpdateRanking,
    FollowUp,
    Tabs,
    wtqd,
    RequirementList,
    MapDialog,
    MapResourceInfo
  },

  data() {
    return {
      loading: false,
      rfphDate: this.$moment().subtract(1, "month").format("YYYY-MM"),
      sq12345Date: this.$moment().subtract(1, "month").format("YYYY-MM"),
      sqzcDate: this.$moment().subtract(1, "month").format("YYYY-MM"),
      sjhfDate: this.$moment().subtract(1, "month").format("YYYY-MM"),
      sqwggxDate: this.$moment().subtract(1, "month").format("YYYY-MM"),
      orgData: {
        children: [],
      }, //当前组织对象
      showMap: false,
      isShowMapDialog: false,
      orgId: "",
      orgLevel: "",
      currentLevel: "",//地图对应level
      currentLevelData: {
        orgId: this.$store.state.chooseArea.chooseName.orgId,
        orgLevel: this.$store.state.chooseArea.chooseName.level,
        meta: {title: "人房总览"},
      },
      breadList: [
        {
          orgId: "",
          orgLevel: "",
          id: "",
          level: "",
          meta: {title: "人房总览"},
        },
      ],
      peopleList: {
        staffGrid: "网格员",
        staffDepartment: "单位/组织",
        staffAgency: "社区工作者",
        chief: "楼长/单元长",
        publicWelfareNum: "公益岗",
        volunteer: "志愿者",
        unit: "微网格",
        building: "楼栋",
      },
      displayedResiId: "",
      displayedHouseId: "",
      dynamicType: 1,
      dynamicTypeList: [
        {
          value: 1,
          label: "更新动态",
        },
        {
          value: 2,
          label: "网格更新排行",
        },
      ],
      eventType: 1,
      eventTypeList: [
        {
          value: 1,
          label: "12345事件",
        },
        {
          value: 2,
          label: "事件回访",
        },
      ],
      customerName: "",
      peopleType: "staffAgency",
      listShow: true,
      mapType: ''
    };
  },

  mounted() {
    // const queryOrgId = getQueryPara("orgId");
    // const queryOrgLevel = getQueryPara("orgLevel");
    // this.init(queryOrgId, queryOrgLevel);
    this.changeCustomerName();
    this.getMapData();
    // this.$refs.map.setNumpoint()
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 设置 showMap 为 true，表示要显示地图
      vm.showMap = true;
      console.log(vm);
      console.log(vm.showMap);
    });
  },

  beforeRouteLeave(to, from, next) {
    // 离开当前路由时，重置 showMap 为 false，表示要隐藏地图
    // this.showMap = false;
    console.log(this.showMap);
    next();
  },
  watch: {
    "$store.state.chooseArea.chooseName"(val) {
      if (val.orgId) {
        this.currentLevelData = {
          ...this.currentLevelData,
          ...val,
          orgLevel: val.level,
        };
        // this.getMapData();
      }
    },
  },

  methods: {
    changeCustomerName() {
      this.customerName = localStorage.getItem("customerNameDataBoard") || "数据分析可视化平台";
    },
    changeType(e) {
      this.peopleType = e;
    },
    dynamicTypeChange(val) {
      this.dynamicType = val;
    },
    eventTypeChange(val) {
      this.eventType = val;
    },
    async init(queryOrgId, queryOrgLevel) {
      if (queryOrgId) {
        this.orgId = queryOrgId;
        this.orgLevel = queryOrgLevel || "agency";
      } else {
        this.orgId = this.$store.state.user.agencyId;
        this.orgLevel = "agency";
      }

      //加载组织数据
      this.loading = false;
      await this.getMapData();
      // await this.getSubMapData();

      this.loading = true;
    },
    changeDate(e) {
      this.rfphDate = e;
    },
    handleClickDotBtn(type, info) {
      if (type == "watch-resi") {
        this.displayedResiId = info.user_id;
      } else if (type == "watch-house") {
        this.displayedHouseId = info.house_id;
      }
    },

    clickBreadItem({item}) {
      this.toBread(item);
    },

    clickAgencyItem(item) {
      this.$refs.map.clearMarkert();
      if (item.id) {
        if (item.level == "grid") {
          this.customerName = item.parentName + "-" + item.name;
        } else {
          this.customerName = item.name || item.meta.title;
        }
        this.currentLevelData = {
          orgId: item.id,
          orgLevel: item.level,
        };
      } else {
        this.customerName = localStorage.getItem("customerNameDataBoard") || "数据分析可视化平台";
        this.currentLevelData = {
          ...this.$store.state.chooseArea.chooseName,
          orgLevel: this.$store.state.chooseArea.chooseName.level,
        };
      }
      this.toBread({
        orgId: item.id,
        orgLevel: item.level,
        meta: {title: item.name},
        name: item.name,
        parentName: item.parentName,
      });
    },
    goBackMap() {
      const item = this.breadList[this.breadList.length - 2];
      this.clickAgencyItem(item);
    },
    toBread(item) {
      const {orgId} = item;
      const {breadList} = this;
      let index = breadList.findIndex((val) => val.orgId === orgId);
      if (index >= 0) {
        this.breadList = breadList.slice(0, index + 1);
      } else {
        breadList.push({...item, id: item.orgId, level: item.orgLevel});
        this.breadList = breadList;
      }
      this.getMapData(item.orgId, item.orgLevel);
    },
    getCenterPoint(geoCoordinateList) {
      const geoCoordinateListFlat = geoCoordinateList.reduce((s, v) => {
        return (s = s.concat(v))
      }, [])
      const total = geoCoordinateListFlat.length
      let X = 0
      let Y = 0
      let Z = 0
      for (const g of geoCoordinateListFlat) {
        const lat = g.lat * Math.PI / 180
        const lon = g.lng * Math.PI / 180
        const x = Math.cos(lat) * Math.cos(lon)
        const y = Math.cos(lat) * Math.sin(lon)
        const z = Math.sin(lat)
        X += x
        Y += y
        Z += z
      }

      X = X / total
      Y = Y / total
      Z = Z / total
      const Lon = Math.atan2(Y, X)
      const Hyp = Math.sqrt(X * X + Y * Y)
      const Lat = Math.atan2(Z, Hyp)

      return {lng: Lon * 180 / Math.PI, lat: Lat * 180 / Math.PI}
    },
    // 点击搜索结果条目，在地图上显示点和详情弹窗
    handleClickSearchItem(item) {
      if (!item.longitude) {
        return this.$message.error("请先设置坐标");
      }
      this.$refs.map.setDotMarker(item, [parseFloat(item.longitude), parseFloat(item.latitude)]);
    },
    setNum(data) {
      // data
      let params = [];
      let org = this.orgData.children;
      org.forEach((item) => {
        data.forEach((item2) => {
          let coordinates = spliceIntoChunks(item.coordinates.split(",").map((item) => parseFloat(item)), 2)
          let coordinates2 = coordinates.map(item3 => {
            return [{
              lat: item3[1],
              lng: item3[0]
            }]
          })
          let index = parseInt(coordinates.length / 2)
          let centerLngLat = this.getCenterPoint(coordinates2)
          // spliceIntoChunks
          if (item2.orgId === item.id && item.coordinates) {
            params.push({
              ...item2,
              peopleType: this.peopleList[this.peopleType],
              latitude: centerLngLat.lat,
              longitude: centerLngLat.lng,
              coordinates
            });
          }
        });
      });
      // if (params.length) {
      this.$refs.map.setNum(params);
      // }
    },
    upDownShow() {
      this.listShow = !this.listShow;
    },
    setPoint(data) {
      // if (data) {
      this.$refs.map.setPoint(data, this.currentLevel, this.peopleType);
      // }
    },
    //获取地图上显示的组织数据
    async getMapData(orgId = this.$store.state.chooseArea.chooseName.orgId, level = this.$store.state.chooseArea.chooseName.level) {
      const url = "org_map";
      this.$http.post(`/gov/org/agency/maporg`, {orgId, level}).then(({data: {data}}) => {
        this.orgData = data;
        this.orgId = this.orgData.id;
        this.orgLevel = this.orgData.level;
        this.currentLevel = this.orgData.agencyLevel;
        this.currentLevelData = {
          orgId: this.orgId,
          orgLevel: this.currentLevel,
        };
        console.log(this.currentLevelData, 'this.currentLevelData 33210')
        this.peopleType = this.currentLevel === "grid" ? "unit" : "staffAgency";
        this.$refs.map.removeResourcesPoint();
        console.log(this.currentLevel, 'level', orgId, this.currentLevel === 'agency' || this.currentLevel === 'community' || this.currentLevel === 'grid')
        if (this.currentLevel !== 'street') {
          this.setResourcesPoint({agencyId: this.orgId})
        }
        this.getMapCount()
      });
    },
    showMapDialog(data) {
      if (data.type === "resources" || this.currentLevel === 'street') {
        this.clickAgencyItem(data)
      } else {
        // -- njjwtqk = 难解决问题情况
        // -- bmysxqk = 不满意事项情况
        // -- xqwwcqk = 需求未完成情况
        switch (data.type) {
          case 'events':
            this.mapType = "bmysxqk";
            break;
          case 'services':
            this.mapType = "xqwwcqk";
            break;
          case 'problems':
            this.mapType = "njjwtqk";
            break;
        }
        this.isShowMapDialog = true
        this.$nextTick(() => {
          this.$refs.MapDialog.open({
            orgId: data.agencyId,
            orgLevel: data.level
          }, this.mapType)
        })
      }
    },
    resourcesPointClick(data) {
      this.$refs.MapResourceInfo.open(data.id, data.dataClass)
    },

    setResourcesPoint({agencyId}) {
      this.$http.get('/actual/base/dataBoard/resource/search?keyword=&agencyId=' + agencyId).then(res => {
        let data = res.data.data;
        data = data.filter(item => item.latitude && item.longitude)
        data = data.map(item => {
          return {
            ...item,
            latitude: item.latitude * 1,
            longitude: item.longitude * 1
          }
        })
        this.$refs.map.setResourcesPoint(data)
      })
    },
    getMapCount() {
      this.$http.get('/governance/icEvent/statOrgResourceAndEventCount?agencyId=' + this.orgId).then(res => {
        let countData = res.data.data
        let orgDataids = this.orgData.children.map(item => item.id)
        countData.forEach(item => {
          let orgDataIndex = orgDataids.indexOf(item.agencyId)
          if (orgDataIndex > -1) {
            let curOrgData = this.orgData.children[orgDataIndex];
            item.data = item.data.map(item2 => {
              return {
                ...curOrgData,
                ...item2,
                agencyId: item.agencyId
              }
            })
            item.data.forEach(item3 => {
              let coordinates = spliceIntoChunks(item3.coordinates.split(",").map((coordinatesItem) => parseFloat(coordinatesItem)), 2)
              let coordinates2 = coordinates.map(item4 => {
                return [{
                  lat: item4[1],
                  lng: item4[0]
                }]
              })
              let centerLngLat = this.getCenterPoint(coordinates2)
              if (item3.hasOwnProperty("services")) {
                item3.type = 'services'
                item3.num = item3.services;
                item3.offsets = [50, 50];
                item3.latitude = centerLngLat.lat
                item3.longitude = centerLngLat.lng
              }
              if (item3.hasOwnProperty("resources")) {
                item3.type = 'resources'
                item3.num = item3.resources;
                item3.offsets = [-50, 50];
                item3.latitude = centerLngLat.lat + 0.002
                item3.longitude = centerLngLat.lng
              }
              if (item3.hasOwnProperty("problems")) {
                item3.type = 'problems'
                item3.num = item3.problems;
                item3.offsets = [50, -50];
                item3.latitude = centerLngLat.lat
                item3.longitude = centerLngLat.lng + .002
              }
              if (item3.hasOwnProperty("events")) {
                item3.type = 'events'
                item3.num = item3.events;
                item3.offsets = [-50, -50];
                item3.latitude = centerLngLat.lat + .002
                item3.longitude = centerLngLat.lng + .002
              }
              // item3.latitude = 59.62496862480762
              // item3.longitude = 126.11233377322651

            })
          }
        })
        console.log(countData, 'countData')
        this.$refs.map.setNumpoint(countData)

        // console.log(countData,'countData')

      })
    },

    //获取地图上显示的组织数据
    async getSubMapData() {
      const url = "sub_org_map";

      const {data, code, msg} = await requestPostBi(
          url,
          {
            queryParam: {
              org_id: this.orgId,
            },
          },
          {
            // mockId: 61831860,
          }
      );

      if (code === 0) {
        const {orgData} = this;
        orgData.children = data.map((item) => {
          return {
            ...item,
            id: item.org_id,
            name: item.org_name,
            latitude: parseFloat(item.latitude),
            longitude: parseFloat(item.longitude),
            coordinates: item.coordinates || "",
          };
        });
        this.orgData = {...orgData};
      } else {
        this.$message.error(msg);
      }
    },

    //加载组织数据
    async loadOrgData() {
      const url = "/gov/org/agency/maporg";
      let params = {
        orgId: this.orgId,
        level: this.orgLevel,
      };

      const {data, code, msg} = await requestPost(url, params);
      if (code === 0) {
        this.orgData = data;
        this.orgId = this.orgId;
        this.orgLevel = this.orgData.level;
      } else {
        this.$message.error(msg);
      }
    },
    handelClickRkfxPei(val) {
      console.log(val);
    },
  },
};
</script>
<style lang="scss" scoped>
.g-center {
  width: 930px !important;
}

.up-style {
  width: 51%;

  img {
    width: 12px;
    height: 12px;
  }

  img:hover {
    cursor: pointer;
  }
}

.go-back {
  position: absolute;
  z-index: 100;
  top: 24px;
  right: 0;
  left: 16px;
  width: 64px;

  img {
    width: 36px;
    height: 36px;
  }

  img:hover {
    cursor: pointer;
  }
}

.date-current-weiyi {
  background: #000;
}
</style>
<style lang="scss" scoped src="@/assets/scss/dataBoard/overview/index.scss"></style>

<style lang="scss" scoped>
.tabs {
  padding: 10px 11px 0px;
}

.sjkb-map {
  width: 930px;
}

.map-legend {
  position: absolute;
  right: 17px;
  bottom: 20px;
  width: 148px;
  color: #fff;

  .legend-title {
    font-size: 16px;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 32px;
    margin-bottom: 4px;
    background: url("@/assets/images/overview/map_legend_title.png");
  }

  .legend-list {
    box-sizing: border-box;
    width: 126px;
    margin: 0 auto;
    padding: 19px 12px;
    border: 1px solid #488CC5;
    background: rgba(#0A2351, 0.66);

    .legend-item {
      font-size: 14px;
      display: flex;
      align-items: center;
      margin-bottom: 7px;

      &:before {
        margin-right: 6px;
      }

      &.blue {
        &:before {
          display: block;
          width: 16px;
          height: 18px;
          content: '';
          background: url("@/assets/images/overview/map_legend_blue.png");
        }
      }

      &.orange {
        &:before {
          display: block;
          width: 16px;
          height: 18px;
          content: '';
          background: url("@/assets/images/overview/map_legend_orange.png");
        }
      }

      &.green {
        &:before {
          display: block;
          width: 16px;
          height: 18px;
          content: '';
          background: url("@/assets/images/overview/map_legend_green.png");
        }
      }

      &.red {
        &:before {
          display: block;
          width: 16px;
          height: 18px;
          content: '';
          background: url("@/assets/images/overview/map_legend_red.png");
        }
      }
    }
  }

}

.m-map {
  height: 970px;
}
</style>
