<template>
  <div>
    <cpt-bread
      @tap="clickBreadItem"
      v-if="breadList.length > 1"
      :bread-list="breadList"
    />
    <div class="g-row">
      <div class="g-left">
        <div class="bgImg">
          <Title text="房屋概览"/>
          <fwgl ref="fwgl" :orgId="orgId"></fwgl>
        </div>
        <div class="bgImg">
          <Title text="居民概览"/>
          <jmgl ref="jmgl" :orgId="orgId"></jmgl>
        </div>
        <div class="bgImg">
          <Title text="图谱画像"/>
          <jdtphx :id="orgId" :current-level-data="{orgId:orgId, orgLevel:orgLevel}"/>
        </div>
      </div>

      <div class="g-center">
        <div class="m-map">
          <div class="m-per">
            <div class="item" @click="jumpPath('normal', 'aged', '老年人')">
              <div class="item-info">
                <div>
                  <img
                      src="~@/assets/images/shuju/renfang/index/per/lnr.png"
                  />老年人
                </div>
                <div>
                  <b>{{ perInfo.OLD_PEOPLE_FLAG }}</b>
                  %
                </div>
              </div>
            </div>
            <div class="item" @click="jumpPath('normal', 'aged', '低保人员')">
              <div class="item-info">
                <div>
                  <img
                    src="~@/assets/images/shuju/renfang/index/per/qsn.png"
                  />低保人员
                </div>
                <div>
                  <b class="blue">{{ perInfo.SUBSISTENCE_ALLOWANCE_FLAG }}</b>
                  %
                </div>
              </div>
            </div>
            <div class="item" @click="jumpPath('normal', 'aged', '志愿者')">
              <div class="item-info">
                <div>
                  <img
                      src="~@/assets/images/shuju/renfang/index/per/syry.png"
                  />失业人员
                </div>
                <div>
                  <b class="blue">{{ perInfo.UNEMPLOYED_FLAG }}</b>
                  %
                </div>
              </div>
            </div>
            <div class="item" @click="jumpPath('normal', 'aged', '党员')">
              <div class="item-info">
                <div>
                  <img
                      src="~@/assets/images/shuju/renfang/index/per/dy.png"
                  />党员
                </div>
                <div>
                  <b class="orange">{{ perInfo.PARTY_FLAG }}</b>
                  %
                </div>
              </div>
            </div>
            <div class="item" @click="jumpPath('normal', 'aged', '志愿者')">
              <div class="item-info">
                <div>
                  <img
                      src="~@/assets/images/shuju/renfang/index/per/zyz.png"
                  />志愿者
                </div>
                <div>
                  <b class="red">{{ perInfo.VOLUNTEER_FLAG }}</b>
                  %
                </div>
              </div>
            </div>
            <div class="item" @click="jumpPath('normal', 'aged', '特殊人群')">
              <div class="item-info">
                <div>
                  <img
                      src="~@/assets/images/shuju/renfang/index/per/tsrq.png"
                  />特殊人群
                </div>
                <div>
                  <b>{{ perInfo.SPECIAL_CROWD_FLAG }}</b>
                  %
                </div>
              </div>
            </div>
          </div>

          <grid-map
              ref="map"
              :srcGridData="orgData"
              @clickAgency="clickAgencyItem"
              @clickDotBtn="handleClickDotBtn"
          />
          <mapRight :orgData="orgData" @clickAgency="clickAgencyItem"/>
        </div>

        <div class="m-search">
          <div class="btn" @click="searchModule.displayedCard = true">
            <img
                class="btn-bg"
                src="~@/assets/images/shuju/renfang/index/search/btn-bg.png"
            />
            <img
                class="btn-bg-hover"
                src="~@/assets/images/shuju/renfang/index/search/btn-bg-hover.png"
            />
            <span>点击搜索</span>
          </div>

          <div v-show="searchModule.displayedCard" class="card">
            <div class="card-input">
              <div class="card-btn" @click="handleSearch">
                <img
                    src="~@/assets/images/shuju/renfang/index/search/search.png"
                />
              </div>

              <input
                  v-model="searchModule.keyword"
                  placeholder="搜索本组织及下级的居民、小区、楼栋、房屋"
                  type="text"
                  @keyup.enter="handleSearch"
              />

              <div class="i-div"></div>

              <div class="card-btn" @click="searchModule.displayedCard = false">
                <img
                    src="~@/assets/images/shuju/renfang/index/search/close.png"
                />
              </div>
            </div>
            <div class="card-show">
              <div class="card-tabs">
                <div
                    :class="{
                    'z-on': searchModule.resultTab == '0',
                  }"
                    @click="searchModule.resultTab = '0'"
                >
                  全部
                </div>
                <div
                    :class="{
                    'z-on': searchModule.resultTab == '1',
                  }"
                    @click="searchModule.resultTab = '1'"
                >
                  居民
                </div>
                <div
                    :class="{
                    'z-on': searchModule.resultTab == '2',
                  }"
                    @click="searchModule.resultTab = '2'"
                >
                  小区
                </div>
                <div
                    :class="{
                    'z-on': searchModule.resultTab == '3',
                  }"
                    @click="searchModule.resultTab = '3'"
                >
                  楼栋
                </div>
                <div
                    :class="{
                    'z-on': searchModule.resultTab == '4',
                  }"
                    @click="searchModule.resultTab = '4'"
                >
                  房屋
                </div>
              </div>

              <div v-if="searchModule.result.length > 0" class="card-list">
                <div
                    v-for="(item, index) in searchModule.result"
                    :key="item.title + index"
                    class="card-item"
                    @click="handleClickSearchItem(item)"
                >
                  <span>{{ item.title }}</span>
                  <img
                      class="i-arrow"
                      src="~@/assets/images/shuju/renfang/index/search/arrow.png"
                  />
                  <img
                      class="i-arrow z-on"
                      src="~@/assets/images/shuju/renfang/index/search/arrow-on.png"
                  />
                </div>
              </div>

              <div v-else class="card-empty">
                <img src="~@/assets/images/shuju/renfang/index/empty.png"/>
                <span>没有找到搜索结果～</span>
              </div>
            </div>
          </div>
        </div>

        <div class="bgImg m-box m-cate map-bottom">
          <div class="box-title">
            <Title v-if="!displayedForecast" text="居民分类统计">
              <template>
              <div
              class="box-title-btn"
              @click="displayedForecast = true"
              >
              <img src="~@/assets/images/shuju/renfang/index/znyc.png"/>
              <span>智能预测</span>

              <el-tooltip placement="top">
              <div slot="content">
              根据智能分类设置规则，预测来年育龄妇女、老年人、空巢老人、独居老人分别有多少人
              </div>
              <img src="~@/assets/images/shuju/renfang/index/i-hint.png"/>
              </el-tooltip>
              </div>
              </template>
            </Title>
            <Title v-else text="居民分类统计-智能预测">
              <template>
              <div
              class="box-title-btn"
              @click="displayedForecast = false"
              >
              <img src="~@/assets/images/shuju/renfang/index/znyc.png"/>
              <span>居民分类统计</span>
              </div>
              </template>
            </Title>
          </div>

          <div v-if="!displayedForecast">
            <div v-if="resiCategoryData.length > 0" class="list">
              <div
                  v-for="(item, index) in resiCategoryData"
                  :key="item.code + index"
                  class="item"
                  @click="toResiClassPage('normal', item.code, item.name)"
              >
                <div>{{ ("0" + (index + 1)).substr(-2) }}.</div>
                <div class="item-name">{{ item.name }}</div>
                <div class="item-count">
                  <b>{{ item.count }}</b> 人
                </div>
                <div class="item-progress">
                  <b :style="{ width: item.ratio + '%' }"></b>
                </div>
                <div class="item-per">
                  <span>较上月</span>
                  <img
                      v-if="item.growth >= 0"
                      src="~@/assets/images/shuju/renfang/index/up.png"
                  />
                  <img
                      v-else
                      src="~@/assets/images/shuju/renfang/index/down.png"
                  />
                  <b>{{ item.growthAbs }}</b>
                  <span>人</span>
                </div>
              </div>
            </div>

            <div v-else class="empty">
              <img src="~@/assets/images/shuju/renfang/index/empty.png"/>
            </div>
          </div>
          <div v-else>
            <div v-if="resiCategoryForecastData.length > 0" class="list">
              <div
                  v-for="(item, index) in resiCategoryForecastData"
                  :key="item.code + index"
                  class="item"
                  @click="toResiClassPage('ai', item.code, item.name)"
              >
                <div>{{ ("0" + (index + 1)).substr(-2) }}.</div>
                <div class="item-name">{{ item.name }}</div>
                <div class="item-count">
                  <b>{{ item.count }}</b> 人
                </div>
                <div class="item-progress">
                  <b :style="{ width: item.ratio + '%' }"></b>
                </div>

                <div class="item-per">
                  <span>较上一年</span>
                  <img
                      v-if="item.growth >= 0"
                      src="~@/assets/images/shuju/renfang/index/up.png"
                  />
                  <img
                      v-else
                      src="~@/assets/images/shuju/renfang/index/down.png"
                  />
                  <b>{{ item.growthAbs }}</b>
                  <span>人</span>
                </div>
              </div>
            </div>

            <div v-else class="empty">
              <img src="~@/assets/images/shuju/renfang/index/empty.png"/>
            </div>
          </div>
        </div>
      </div>

      <div class="g-right">
        <div class="bgImg">
          <Title text="信息采集统计"></Title>
          <rfsjtj :currentLevelData="{orgId:orgId, orgLevel:orgLevel}"/>
        </div>
        <div class="bgImg">
          <Title text="人口预警"></Title>

          <div
              :class="{
              'z-shrink':
                orgLevel == 'district' ||
                orgLevel == 'street' ||
                orgLevel == 'city'
            }"
              class="m-subbox m-rkyj"
          >
            <rkyj :orgId="orgId"/>
          </div>
        </div>
        <div class="bgImg">
          <Title text="人口分析"></Title>
          <rkfx :orgId="orgId" @handelClickRkfxPei="handelClickRkfxPei"/>
        </div>
      </div>

      <cpt-loading v-show="false" />
    </div>

    <resi-details
        v-if="popupShow"
        :popupShow='popupShow'
        :resi-id="displayedResiId"
        @close="popupShow = false"
    />

    <house-details
        v-if="displayedHouseId"
        :house-id="displayedHouseId"
        @close="displayedHouseId = ''"
    />
  </div>
</template>

<script>
import gridMap from "@/views/dataBoard/cpts/map/index";
import fwgl from "@/views/dataBoard/renfang/cpts/fwgl";
import jmgl from "@/views/dataBoard/renfang/cpts/jmgl";
import rkfx from "@/views/dataBoard/renfang/cpts/rkfx";
import rkyj from "@/views/dataBoard/renfang/cpts/rkyj";
import szsq from "@/views/dataBoard/renfang/cpts/szsq";
import mapRight from "@/views/dataBoard/renfang/cpts/map-right.vue";
import cptBread from "@/views/dataBoard/renfang/cpts/bread";
import cptLoading from "@/views/dataBoard/cpts/loading";
import houseDetails from "@/views/dataBoard/cpts/house-details";
import resiDetails from "@/views/dataBoard/cpts/resi-details";
import {requestPostBi} from "@/js/dai/request-bipass";
import {requestPost} from "@/js/dai/request";
import getQueryPara from "dai-js/modules/getQueryPara";
import {requestGet} from "@/js/dai/request";
import resiCategoryMap from "@/views/business/resi-category-map.js";
import Title from "@/views/dataBoard/satisfactionEval/components/Title/index.vue";
import rfsjtj from "@/views/dataBoard/overview/components/rfsjtj.vue";
import jdtphx from "@/views/dataBoard/overview/components/jdtphx.vue";

function iniGetPerInfo() {
  return {
    OLD_PEOPLE_FLAG: "--",
    PARTY_FLAG: "--",
    UNEMPLOYED_FLAG: "--",
    VOLUNTEER_FLAG: "--",
    SUBSISTENCE_ALLOWANCE_FLAG: "--",
    SPECIAL_CROWD_FLAG: "--",
  };
}

export default {
  name: "renfang",

  components: {
    Title,
    gridMap,
    fwgl,
    jmgl,
    rkfx,
    rkyj,
    szsq,
    cptLoading,
    cptBread,
    houseDetails,
    resiDetails,
    mapRight,
    rfsjtj,
    jdtphx
  },

  data() {
    return {
      loading: false,

      orgData: {
        children: [],
      }, //当前组织对象
      orgId: "",
      orgLevel: "",

      breadList: [
        {
          orgId: "",
          orgLevel: "",
          meta: {title: "人房总览"},
        },
      ],

      resiCategoryData: [], // 居民分类分析
      resiCategoryForecastData: [], // 居民分类预测
      displayedForecast: false, //显示居民分类分析 还是居民分类预测

      searchModule: {
        displayedCard: false,
        keyword: "",
        resultTab: "0", // 0所有 1，居民；2，小区；3，楼栋；4，房屋
        result: [
          // {
          // 	id: 1,
          // 	title: "四季景园",
          // },
        ],
      },

      perInfo: iniGetPerInfo(),

      displayedResiId: "",
      displayedHouseId: "",

      pandectData: {},

      popupShow: false
    };
  },

  mounted() {
    const queryOrgId = getQueryPara("orgId");
    const queryOrgLevel = getQueryPara("orgLevel");
    this.init(queryOrgId, queryOrgLevel);
  },

  watch: {},

  methods: {
    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.loadOrgData();
      await this.getMapData();
      this.getResiCategoryData();
      this.getPerInfo();
      this.getPandectData()

      await this.getResiCategoryForecastData();
      this.loading = true;
    },
    //加载组织数据
    async getPandectData() {
      // const {agencyId} = this.$store.state.user;
      const url = "/actual/base/residentHouseMerge/communityOverview";
      let params = {
        agencyId:this.orgId,
        orgId:this.orgId ,
        level: 'agency',
      };
      console.log(params);
      const {data, code, msg} = await requestGet(url, params);
      if (code === 0) {
        if (data) {
          this.$nextTick(() => {
                this.$refs['fwgl'].pandectData = data
                this.$refs['jmgl'].pandectData = data
              }
          )
        }
      } else {
        this.$message.error(msg);
      }
    },
    jumpPath(pageType, type_id = "", type_name) {
      this.$router.push({
        path: "/dataBoard/renfang/visualizing",
        query: {
          org_id: this.orgId,
          type_id,
          type_name,
          pageType,
        },
      });
    },
    toResiClassPage(pageType, type_id = "", type_name) {
      if (type_id) {
        this.$router.push({
          path: "/dataBoard/renfang/resi-class",
          query: {
            org_id: this.orgId,
            type_id,
            type_name,
            pageType,
          },
        });
      } else {
        this.$message.error("该人员暂无居民信息！");
      }
    },

    handleClickDotBtn(type, info) {
      if (type == "watch-resi") {
        this.$router.push({
          path: "/dataBoard/renfang/resident",
          query: {
            user_id: info.user_id,
          },
        });
        // this.displayedResiId = info.user_id;
        // this.popupShow = true
      } else if (type == "watch-house") {
        this.displayedHouseId = info.house_id;
      }
    },

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

    clickAgencyItem(item) {
      console.log(item);
      if (item.level === 'neighborHood') {
        this.$router.push('/homeDetails/index?id='+item.id)
      } else {
        this.toBread({
          orgId: item.id,
          orgLevel: item.agencyLevel,
          meta: {title: item.name},
        });
      }
    },

    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);
        this.breadList = breadList;
      }
      this.init(item.orgId, item.orgLevel);
    },

    // 点击搜索结果条目，在地图上显示点和详情弹窗
    handleClickSearchItem(item) {
      if (!item.longitude) {
        return this.$message.error("请先设置坐标");
      }
      this.$refs.map.setDotMarker(item, [
        parseFloat(item.longitude),
        parseFloat(item.latitude),
      ]);
    },

    // 根据类别搜索
    async handleSearch() {
      this.searchModule.result = [];
      const { searchModule } = this;

      const url = [
        "search_all",
        "search_resident",
        "search_village",
        "search_building",
        "search_house",
      ][searchModule.resultTab];

      const {data, code, msg} = await requestPostBi(
          url,
          {
            queryParam: {
              org_id: this.orgId,
              name: this.searchModule.keyword,
            },
          },
          {
            // mockId: 60044224,
            // mockId: 60048067,
          }
      );

      if (code === 0) {
        this.searchModule.result = data.map((item) => {
          let type = item.type || searchModule.resultTab;
          let title = "";
          let detailJson = {};
          if (searchModule.resultTab == 0) {
            title = item.name;
            if (typeof item.detail_json == "string") {
              try {
                detailJson = JSON.parse(item.detail_json);
              } catch (e) {
                console.log(e);
              }
            }
          } else if (type == "1") {
            title = item.user_name;
          } else if (type == "2") {
            title = item.village_name;
          } else if (type == "3") {
            title = item.village_name + "-" + item.building_name;
          } else if (type == "4") {
            title = item.building + "-" + item.unit + "-" + item.door;
          }
          return {
            title,
            type,
            ...item,
            ...detailJson,
          };
        });
      } else {
        this.$message.error(msg);
      }
    },

    //地图上居民分类百分比数据 ps:感觉有点重复显示
    async getPerInfo() {
      const url = "/actual/base/resiCategory/categoryCountPartList";
      let params = {
          orgId: this.orgId,
          agencyId: this.orgId,
          level: this.orgLevel,
        };
      const { data, code, msg } = await requestGet(
        url,
        params
      );
      if (code === 0 && data) {
        // this.perInfo = {
        //   ...iniGetPerInfo(),
        //   ...data[0],
        // };
        const resiCount = data.resiCount;
        Object.keys(data.categoryList).forEach((key) => {
            const category = data.categoryList[key];
            const categoryName = category.categoryName;
            const categoryCount = category.categoryCount;
            const radio = categoryCount/resiCount * 100;
            if(categoryName == "OLD_PEOPLE_FLAG"){
              this.perInfo.OLD_PEOPLE_FLAG=radio.toFixed(2);
            }else if(categoryName == "PARTY_FLAG"){
              this.perInfo.PARTY_FLAG=radio.toFixed(2);
            }else if(categoryName == "UNEMPLOYED_FLAG"){
              this.perInfo.UNEMPLOYED_FLAG=radio.toFixed(2);
            }else if(categoryName == "VOLUNTEER_FLAG"){
              this.perInfo.VOLUNTEER_FLAG=radio.toFixed(2);
            }else if(categoryName == "SUBSISTENCE_ALLOWANCE_FLAG"){
              this.perInfo.SUBSISTENCE_ALLOWANCE_FLAG=radio.toFixed(2);
            }else if(categoryName == "SPECIAL_CROWD_FLAG"){
              this.perInfo.SPECIAL_CROWD_FLAG=radio.toFixed(2);
            }
        });

      } else {
        this.$message.error(msg);
      }
    },

    //居民分类分析数据
    async getResiCategoryData() {
      const {agencyId} = this.$store.state.user;
      console.log(agencyId);
      const url = "/actual/base/resiCategory/categoryCountList";
      let params = {
        agencyId: agencyId,
        orgId: this.orgId,
        level: this.orgLevel,
        // id: this.orgId,
        // level: "agency",
      };
      const { data, code, msg } = await requestGet(url, params);
      if (code === 0) {
        if (data) {
          this.resiCategoryData = data.categoryList.map((item) => {
            return {
              code: item.categoryName,
              name: resiCategoryMap[item.categoryName] || "",
              count: item.categoryCount,
              ratio: ((100 * item.categoryCount) / data.resiCount).toFixed(0),
              growth: 0,
              growthAbs: Math.abs(item.growth) || '--',
            };
          });
        }
      } else {
        this.$message.error(msg);
      }
    },

    //居民分类预测数据
    async getResiCategoryForecastData() {
      const {agencyId} = this.$store.state.user;
      const url = "/actual/base/resiCategory/intelligentPredictioncategoryCountList";
      let params = {
        agencyId:agencyId,
        orgId:this.orgId,
        level: this.orgLevel,
      };
      const {data, code, msg} = await requestGet(url, params);
      if (code === 0) {
          this.resiCategoryForecastData = data.categoryList.map((item) => {
            return {
              code: item.categoryName,
              name: resiCategoryMap[item.categoryName] || "",
              count: item.categoryCountNext,
              // name:item.categoryCountName,
              per: parseInt(
                (100 * item.categoryCount) / data.resiCount
              ),
              // per: item.change_ratio,
              growth: item.change_ratio,
              growthAbs: Math.abs(item.categoryCountNext - item.categoryCount)
            };
          });
      } else {
        this.$message.error(msg);
      }
    },

    //获取地图上显示的组织数据
    async getMapData() {

      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);
      }
    },

    //加载组织数据
    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>
@import "@/assets/scss/dataBoard/renfang/index.scss";

.bgImg {
  margin-bottom: 7px;
  background: url('@/assets/images/shuju/overview/box-bg.png') no-repeat;
  background-size: 100% 100%;
}

.m-box {
  height: 323px;
}
.map-bottom {
  margin: 0 17px;
}
</style>
