<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"
                       @change="handleChangeAgency"
                       clearable></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>
      <div class="g-r">111
        <!-- <screen-echarts-frame class="echart-wr"
                              @myChartMethod="lineInitOk"
                              ref="lineChart"></screen-echarts-frame> -->

      </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 { lineOption } from './distributionLineOption.js'
import * as echarts from 'echarts'


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: '',



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

  async mounted () {
    this.userId = this.uid;
    this.initData()
    await this.getAgencylist()//获取组织级别
    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.getTable();
    },

    async getAgencylist () {
      const url = '/gov/org/customeragency/agencylist'
      // const url = 'http://yapi.elinkservice.cn/mock/102/gov/org/agency/agencylist'

      const params = {
        // customerId: '613cc61a6b8ce4c70d21bd413dac72cc'
        customerId: '0c41b272ee9ee95ac6f184ad548a30eb'
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        ++this.iscascaderShow
        this.casOptions = []
        this.agencyIdArray.length = []

        if (data) {
          this.casOptions.push(data)
        }

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

    handleChangeDate (value) {

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


    lineInitOk (dom) {
      console.log('line准备好了', 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);

      if (code === 0) {
        // 获取pieChart配置
        this.lineOption = lineOption()

        if (data && data.length > 0) {

          this.loadCategoryData()

        } else {

        }
        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.$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.name)
        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.name,
          type: 'line',
          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)


      });
      console.log(this.series)
    },

    handleChangeAgency (value) {

      this.agencyName = this.$refs["myCascader"].getCheckedNodes()[0].label
      this.orgId = this.agencyIdArray.length > 0 ? this.agencyIdArray[this.agencyIdArray.length - 1] : ''
      this.getApiData()
      console.log(this.agencyIdArray)
    },


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

  computed: {},

  components: {
    cptCard,
    cptTb,
    screenEchartsFrame,
  },

  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>
