<template>
  <cpt-card>
    <div class="title">
      <div class="card-title">
        <img src="@/assets/img/shuju/title-tip.png" />
        <span>项目分布分析</span>
      </div>
      <div class="second-title">
        <div class="second-title-label">不同事件类别在不同时间段的变化和分布</div>
        <div class="second-select cascader">

          <el-cascader class="customer_cascader"
                       ref="myCascader"
                       v-model="agencyIdArray"
                       :key="iscascaderShow"
                       :options="casOptions"
                       :props="optionProps"
                       :show-all-levels="false"
                       @change="handleChangeAgency"></el-cascader>
        </div>
        <div class="second-select">
          <el-date-picker v-model="timeRange"
                          type="daterange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          prefix-icon="el-icon-caret-bottom"
                          value-format="yyyy-MM-dd"
                          @change="handleSelectChange">
          </el-date-picker>

        </div>
      </div>

    </div>

    <div class="g-cpt-resi">
      <div class="g-l">
        <screen-echarts-frame class="echart-line"
                              @myChartMethod="lineInitOk"
                              ref="lineChart"></screen-echarts-frame>
        <!-- <div class="table-status"
             v-if="loading">
          <screen-loading>加载中</screen-loading>
        </div>
        <div class="table-status"
             v-if="lineList.length == 0 && !loading">
          <div class="no-data">
            <img src="../../../../assets/img/modules/visual/noData.png"
                 class="no-data-img" />
          </div>
        </div> -->

      </div>
      <div class="g-r">
        <div class="r-map">
          <screen-map class="map"
                      ref="map"
                      :showPolygonLayer="true"></screen-map>

          <div class="r-legend">
            <div class="legend_item"
                 v-for="(item,index) in legendArray"
                 :key="index">
              <div :class="['color','color'+index]"></div>
              <span>{{item.name}}</span>
            </div>

          </div>

        </div>

      </div>
    </div>
  </cpt-card>
</template>

<script>
import { Loading } from "element-ui"; //引入Loading服务
import { requestPost } from "@/js/dai/request";
import cptCard from "@/views/modules/visual/cpts/card";
import cptTb from "@/views/modules/visual/cpts/tb";
import screenEchartsFrame from "@/views/modules/visual/components/screen-echarts-frame";
import screenMap from "@/views/modules/visual/components/screen-map";
import { lineOption } from './distributionLineOption.js'
import * as echarts from 'echarts'
import nextTick from 'dai-js/tools/nextTick'
import ScreenLoading from "@/views/modules/visual/components/screen-loading";

export default {
  name: "HomeMap",
  data () {
    return {
      showNoData: false,
      timer: null,

      casOptions: [],
      agencyIdArray: [],
      customerList: [],
      iscascaderShow: 0,

      optionProps: {
        multiple: false,
        value: 'agencyId',
        label: 'agencyName',
        children: 'subAgencyList',
        checkStrictly: true
      },

      lineChart: '',
      lineOption: {},
      lineInitState: false,
      lineColorArray: [],
      xaxis: [],
      series: [],
      legend: [],
      lineData: [820, 932, 901, 934, 1290, 1330, 1320],
      lineList: [
        //   {
        //     time: '4:00',
        //     categoryList: [
        //       {
        //         categoryCode: '001',
        //         count: 100,
        //         color: '#1B51FF',
        //         name: '分类1'
        //       },
        //       {
        //         categoryCode: '002',
        //         count: 200,
        //         color: '#00E5ED',
        //         name: '分类2'
        //       }
        //     ]
        //   },
        //   {
        //     time: '5:00',
        //     categoryList: [
        //       {
        //         categoryCode: '001',
        //         count: 20,
        //         color: '#1B51FF',
        //         name: '分类1'
        //       },
        //       {
        //         categoryCode: '002',
        //         count: 400,
        //         color: '#00E5ED',
        //         name: '分类2'
        //       }
        //     ]
        //   },
        //   {
        //     time: '6:00',
        //     categoryList: [
        //       {
        //         categoryCode: '001',
        //         count: 50,
        //         color: '#1B51FF',
        //         name: '分类1'
        //       },
        //       {
        //         categoryCode: '002',
        //         count: 10,
        //         color: '#00E5ED',
        //         name: '分类2'
        //       }
        //     ]
        //   }
      ],

      timeRange: [],
      orgId: '',

      isfirstInit: true,
      mapList: [
        {
          orgId: '3115fc83f1db431008a73c553eef1eb5',
          count: 169
        },
        {
          orgId: '7e57419e6afcdc910d08124c0a1b4eb9',
          count: 149
        },
        {
          orgId: 'e56ac695b01d9eed8723bde718071df5',
          count: 219
        }
      ],
      agencyInfo: {},
      subAgencyArray: [],
      colorArray: ['#DD2719', '#EDBE00', '#00E5ED'],
      colorFillArray: ['rgba(221, 39, 25, 0.24)', 'rgba(237, 190, 0, 0.25)', 'rgba(0, 229, 237, 0.16)'],
      legendArray: [],
      under: null,
      above: null

    };
  },
  // mixins: [animate]
  beforeDestroy () {
    this.timer && clearInterval(this.timer)
  },

  async mounted () {
    this.userId = this.uid;
    this.initData()
    await this.getAgencylist()//获取组织级别
    await nextTick(500)
    await this.loadOrgData()
    await this.getApiData();

  },

  methods: {
    initData () {
      let yesterday = new Date((new Date).getTime() - 24 * 60 * 60 * 1000)

      let year = yesterday.getFullYear()
      let month = yesterday.getMonth() + 1 //月
      let day = yesterday.getDate() //日

      var days = new Date(year, month, 0);
      days = days.getDate(); //获取当前月的天数
      var year2 = year;
      var month2 = parseInt(month) - 1;
      if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
      }
      var day2 = day;
      var days2 = new Date(year2, month2, 0);
      days2 = days2.getDate();
      if (day2 > days2) {
        day2 = days2;
      }
      if (month2 < 10) {
        month2 = '0' + month2;
      }
      var t2 = year2 + '-' + month2 + '-' + day2;
      var t1 = year + '-' + month + '-' + day;
      // let t3 = formate(t2, style);

      this.timeRange = [t2, t1]

    },

    handleSelectChange () {
      this.getApiData();
    },

    async getApiData () {

      await this.getLine()
      await this.loadMapData();
    },

    // 获取当前登录人员信息及组织信息
    getAgencylist () {
      const url = '/gov/org/customeragency/staffinagencylist'
      let params = {}
      window.app.ajax.post(
        url,
        params,
        (data, rspMsg) => {
          this.agencyInfo = data.agencyList
          this.orgId = this.agencyInfo.agencyId
          if (!this.agencyInfo.latitude) {
            this.agencyInfo.latitude = 36.072227
          }
          if (!this.agencyInfo.longitude) {
            this.agencyInfo.longitude = 120.389455
          }
          if (!this.agencyInfo.level) {
            this.agencyInfo.level = 'street'
          }

          //组织级联数据
          ++this.iscascaderShow
          this.casOptions = []
          this.agencyIdArray.length = []

          if (data.subAgencyList) {
            data.agencyList.subAgencyList = data.subAgencyList
            this.casOptions.push(data.agencyList)
            this.agencyIdArray.push(this.orgId)
          }

        },
        (rspMsg, data) => {
          this.$message.error(rspMsg)
        }
      )

    },

    handleChangeDate (value) {
      this.dateId = value
      this.getApiData()
    },

    //加载组织数据
    async loadOrgData () {
      const url = "/gov/org/agency/maporg"
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/org/agency/maporg"
      let params = {
        orgId: this.orgId,
        level: 'agency'
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {

        // this.agencyInfo = data
        // if (!data.latitude) {
        //   this.agencyInfo.latitude = 36.072227
        // }
        // if (!data.longitude) {
        //   this.agencyInfo.longitude = 120.389455
        // }
        // if (!data.level) {
        //   this.agencyInfo.level = 'street'
        // }
        this.subAgencyArray = []
        if (data.children && data.children.length > 0) {
          this.subAgencyArray = data.children
        } else {
          this.subAgencyArray = []
        }

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

    },

    async loadMapData () {
      const _that = this
      // this.$refs.lineChart.showLoading()
      const url = "/gov/project/project/projectdistributionanalysisright";
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/project/project/projectdistributionanalysisright";
      let params = {
        orgId: this.orgId,
        startDate: this.timeRange.length > 0 && this.timeRange[0] || '',
        endDate: this.timeRange.length > 0 && this.timeRange[1] || ''
      };

      const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {

        this.legendArray = []
        if (data.under) {
          this.under = data.under
          this.legendArray.push(
            {
              color: this.colorArray[0],
              name: data.under + '以下'
            }
          )
        }

        if (data.above) {
          this.above = data.above
          this.legendArray.push(
            {
              color: this.colorArray[1],
              name: data.under + '-' + data.above
            }
          )
          this.legendArray.push(
            {
              color: this.colorArray[2],
              name: data.above + '以上'
            }
          )
        }
        if (data.list && data.list.length > 0) {
          this.mapList = data.list


        } else {
          this.mapList = []
        }

        this.mapList.forEach(item => {

          for (let i = 0; i < this.subAgencyArray.length; i++) {
            let agencyItem = this.subAgencyArray[i]
            if (item.orgId === agencyItem.id) {
              item.longitude = agencyItem.longitude
              item.latitude = agencyItem.latitude
              item.coordinates = agencyItem.coordinates

              if (this.under) {
                if (item.count < this.under || item.count === this.under) {
                  item.color = this.colorArray[0]
                  item.fillColor = this.colorFillArray[0]
                } else {
                  if (this.above) {
                    if (item.count > this.under && item.count < this.above) {
                      item.color = this.colorArray[1]
                      item.fillColor = this.colorFillArray[1]
                    } else {
                      item.color = this.colorArray[2]
                      item.fillColor = this.colorFillArray[2]
                    }
                  }
                }


              }
              break
            }

          }

        });

        console.log(this.mapList)
        this.loadMap()
        this.isfirstInit = false

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

    loadMap () {

      if (this.isfirstInit) {
        //mapInfo, polygonArray, polIconUrlArray, iconArrays, iconUrlArray
        this.$refs.map.loadMap(this.agencyInfo, this.mapList, null, null, null, null,)
      } else {
        this.$refs.map.refreshMap(this.mapList, null)


      }
    },

    lineInitOk (dom) {
      this.lineInitState = true

    },
    getLine () {
      if (this.lineInitState) {
        this.getLineChart()
      } else {
        setTimeout(() => {
          this.getLine()
        }, 500)
      }
    },
    // 获取折线图
    async getLineChart () {
      this.$refs.lineChart.clear()
      const _that = this
      this.$refs.lineChart.showLoading()
      const url = "/gov/project/project/projectdistributionanalysisleft";
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/project/project/projectdistributionanalysisleft";
      let params = {
        orgId: this.orgId,
        startDate: this.timeRange.length > 0 && this.timeRange[0] || '',
        endDate: this.timeRange.length > 0 && this.timeRange[1] || ''
      };

      const { data, code, msg } = await requestPost(url, params);
      this.$refs.lineChart.hideLoading()
      if (code === 0) {
        // 获取pieChart配置
        this.lineOption = lineOption()

        if (data && data.length > 0) {
          this.lineList = data
          this.loadCategoryData()



          this.$refs.lineChart.setOption(this.lineOption, true)
          this.$refs.lineChart.setOption({
            xAxis: { data: this.xaxis },
            legend: { data: this.legend },
            series: this.series
          }, true)
        } else {
          this.lineList = []
        }



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

    },

    //解析折线图数据
    loadCategoryData () {

      this.xaxis = []
      this.series = []
      this.legend = []
      let num = this.lineList[0].categoryList.length

      let dataArray = new Array(num)
      //遍历每个分类
      this.lineList[0].categoryList.forEach((categoryItem, index) => {
        this.legend.push(categoryItem.categoryName)
        dataArray[index] = []

      });


      //遍历每个时间
      this.lineList.forEach(item => {
        this.xaxis.push(item.time)

        //遍历每个分类
        item.categoryList.forEach((categoryItem, index) => {
          dataArray[index].push(categoryItem.count)
        });

      });

      //遍历第一组的分类
      this.lineList[0].categoryList.forEach((categoryItem, index) => {

        let object = {
          name: categoryItem.categoryName,
          type: 'line',
          smooth: true,
          barWidth: 15,
          areaStyle: {},
          itemStyle: {
            color: new echarts.graphic.LinearGradient(
              0, 1, 0, 0,
              [
                { offset: 0, color: 'rgba(121, 55, 255, 0)' },
                { offset: 1, color: categoryItem.color }
              ]
            )
          },
          data: dataArray[index]
        }

        this.series.push(object)


      });

    },

    handleChangeAgency (value) {
      this.agencyName = this.$refs["myCascader"].getCheckedNodes()[0].label
      this.orgId = this.agencyIdArray.length > 0 ? this.agencyIdArray[this.agencyIdArray.length - 1] : ''
      this.getApiData()

    },


    toUserInfo (uid) {
      this.$router.push({ path: `/main-shuju/visual-basicinfo-people/${uid}` });
    },
  },
  props: {
    uid: {
      type: String,
      default: "",
      // default: "8ada68cb6f1e4b9a8333348a39ef3aee",
    },
  },

  computed: {

  },

  components: {
    cptCard,
    cptTb,
    screenEchartsFrame,
    screenMap,
    ScreenLoading
  },

  watch: {
    uid (id) {
      this.userId = id;
    },
    userId () {
      this.getApiData();
      window.scrollTo(0, 0);
    },
  },
};
</script>

<style
  lang="scss"
  src="@/assets/scss/modules/visual/distributionAnalyze.scss"
  scoped
></style>

<style lang=scss scoped>
</style>
