<template>
  <div class="div_main">

    <div class="card-title">

      <div class="title-label">
        <span>所属组织：</span>
        <el-cascader class="customer_cascader"
                     style="margin-left:10px"
                     size="small"
                     filterable
                     ref="myCascader"
                     v-model="agencyIdArray"
                     :options="orgOptions"
                     :props="orgOptionProps"
                     :show-all-levels="false"
                     @change="handleChangeAgency"></el-cascader>

        <el-button style="margin-left:30px"
                   size="small"
                   class="diy-button--search"
                   @click="handleSearch">查询</el-button>
      </div>
    </div>
    <div class="card-echart">
      <div class="card-left">
        <div class="card-left-title">辖区疫苗接种情况</div>

        <div class="echart-wr">

          <screen-echarts-frame class="echart-org"
                                @myChartMethod="pieInitOks"
                                ref="eduChart"></screen-echarts-frame>

        </div>

      </div>
      <div class="card-left">
        <div class="card-left-title">近7天核酸检测人数</div>

        <div class="echart-wr">
          <screen-echarts-frame class="echart-org"
                                @myChartMethod="lineInitOk"
                                ref="lineChart"></screen-echarts-frame>

        </div>

      </div>
    </div>
    <el-dialog  :visible.sync="dialogVisible"
               width="50%"
               @close="diaClose"
               >
               <vaccine-Count ref="ref_vaccineCount"
              :seriesNum="seriesNum"
              :tableData="tableData"
              >
               </vaccine-Count>
               <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="pageNo"
                       :page-sizes="[10, 20, 60, 100]"
                       :page-size="pageSize"
                       layout="sizes, prev, pager, next, total"
                       :total="total">
        </el-pagination>
    </el-dialog>
  </div>
</template>

<script>
import { requestPost, requestGet } from "@/js/dai/request";
import vaccineCount from "./vaccineCountTable.vue"
import nextTick from "dai-js/tools/nextTick";
import screenEchartsFrame from "@c/screen-echarts-frame";

import { pieOption } from './options'
import { lineOption } from './lineOption'
import { mapGetters } from 'vuex'

import * as echarts from 'echarts';
export default {
  name: "warning-box",
  components: {
    vaccineCount,
    screenEchartsFrame,

  },
 
  data () {
    return {
      disabled: true,
      agencyIdArray: [],
      orgOptions: [],
      dialogVisible:false,
      seriesNum:{},
      tableData:[],
      orgOptionProps: {
        multiple: false,
        value: 'agencyId',
        label: 'agencyName',
        children: 'subAgencyList',
        checkStrictly: true
      },
      noEduInit: false,

      agencyId: '',
      grid: '',

      pieItem: [
        {
          name: '接种0针人数',
          value: 0,
          color: 'rgba(27, 81, 255, 1)'
        }, {
          name: '接种1针人数',
          value: 1,
          color: 'rgba(0, 229, 237, 1)'
        }, {
          name: '接种2针人数',
          value: 2,
          color: 'rgba(120, 0, 255, 1)'
        }, {
          name: '接种3针人数',
          value: 3,
          color: 'rgba(255, 120, 0, 1)'
        }, {
          name: '接种4针人数',
          value: 4,
          color: 'rgba(255, 186, 0, 1)'
        }
      ],
      pageNo:1,
      pageSize:10,
      total:1,
      resiVaccineNum:"",
      pieEduChartSs: null,
      pieEduOptions: null,
      lineChart: "",
      lineOption: {},
      lineInitState: false,
      lineXaxis: [],
      lineSeriesData: [],
      state:false
    };
  },
  computed: {
    tableHeight () {
      return this.$store.state.inIframe ? this.clientHeight - 500 + this.iframeHeight : this.clientHeight - 500
    },

    ...mapGetters(['clientHeight', 'iframeHeight'])
  },
  async mounted () {
    await nextTick(100);
    await this.getOrgTreeList()
    this.getPieData()
    this.getLineChart()
    this.getLine()
    // this.clickEduPie()

  },
  async created () {

  },
  methods: {
    handleSearch (val) {
      this.getPieData()
    },

    pieInitOks (dom) {
      console.log('pies准备好了', dom)
      this.pieEduChartS = dom
      // this.pieInitState = true

    },
    handleSizeChange (val) {
      this.pageSize = val
      this.clickPieShowTable(true)
    },
    handleCurrentChange (val) {
      this.pageNo = val
      this.clickPieShowTable(true)
    },
    async getPieData () {
      // const url = "/epmetuser/icresiuser/partymembereducationstatistics";
      const url = '/epmetuser/epidemicPrevention/vaccinePie'
      let params = {}
      if(this.gridId){
         params = {
        gridId: this.gridId,
    
      }
      }else{
        params = {
        agencyId:this.agencyId 
      }
      }
     
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        this.pieItem = data.map(item => {
          return {
            ...item,
            name: item.label,
            isClick: false
          }
        })
        this.initEduCharts()
      } else {
      }
    },

    initEduCharts () {

      let legend = {
        show: true,
        // orient: 'vertical',
        bottom: 10,
        // right: 0,
        textStyle: {
          width: 90,
          // color: '#fff',
          rich: {
            a: {
              width: 90
            }
          }
        },
        formatter: name => {
          for (let a = 0; a < this.pieItem.length; a++) {

            // this.data  这个数据中有名称和次数
            if (this.pieItem[a].name === name) {
              //两个名称进行对比，取出对应的次数
              let params1 = name + "\n"; //然后return你需要的legend格式即可
              console.log(params1);
              let tmp = params1.split("\n");
              let res = "" + params1;
              for (let i in tmp) {
                res = res.replace(tmp[i], "");
              }
              return res + params1;
            }
          }
        }
      }
      this.pieEduOptions = pieOption(this.pieEduChartS)
      this.pieEduOptions.legend = { ...legend }

      const maxValue = Math.max(...this.pieItem.map(i => Number(i.value)));
      const maxIndex = this.pieItem.findIndex(a => Number(a.value) == maxValue);
      this.clickEduPie(maxIndex)
      // console.log('----------------------最大值', maxValue, maxIndex)
      let fun = params => {
        this.clickEduPie(params.dataIndex)
      }
      this.$refs.eduChart.handleClick(fun)
      this.clickPieShowTable(false)
    },
    diaClose () {
      this.dialogVisible = false
      this.pageNo = 1
      this.resiVaccineNum = ''
    },

    async clickPieShowTable(flag){
      this.dialogVisible = flag
      let url = "/epmetuser/epidemicPrevention/page"
     let params = {}
      if(this.gridId){
         params = {
        pageNo:this.pageNo,
        pageSize:this.pageSize,
        vaccineCount: this.resiVaccineNum,
        gridId:this.gridId
      }
      }else{
       params = {
        pageNo:this.pageNo,
        pageSize:this.pageSize,
        vaccineCount: this.resiVaccineNum,
        agencyId:this.agencyId,
      }
      }
      let {data,code,msg} = await requestPost(url,params)
      if(code==0){
        this.total = data.total || 0;
        this.tableData = data.list
      }else{
        this.$message.error(msg);
      }
    },
    clickEduPie (seriesIndex) {
      let _code = ''
      let isClick = true
      this.pieItem.forEach((element, index) => {
        if (index === seriesIndex) {
          _code = element.code
          this.resiVaccineNum = _code
          if (!this.noEduInit) isClick = false
          else {
            element.isClick = !element.isClick
            isClick = element.isClick
          }

          element.label = {
            show: true,

          };
          element.labelLine = {
            show: true,
            lineStyle: {
              opacity: 1,
            }

          };

        } else {
          element.isClick = false
          element.label = {
            show: false,

          };
          element.labelLine = {
            show: false,
            lineStyle: {
              opacity: 0,
              color: 'rgba(255,255,255,0)'
            }

          };

        }
      });

      this.pieEduOptions.series[0].data = this.pieItem
      // this.$refs.pieChart.hideLoading()
      this.$refs.eduChart.setOption(this.pieEduOptions)
      setTimeout(() => {
        this.state = true
      }, 1000);
      if (!this.state) return
      this.clickPieShowTable(true)
    },
    lineInitOk () {
      this.lineInitState = true;
    },
    getLine () {
      if (this.lineInitState) {
        this.assignLineChart();
      } else {
        setTimeout(() => {
          this.getLine();
        }, 500);
      }
    },
    // 获取折线图
    async getLineChart () {
      //获取当前年月日
      let date = new Date();
      let base = Date.parse(date); // 转换为时间戳
      let year = date.getFullYear(); //获取当前年份
      let mon = date.getMonth() + 1; //获取当前月份
      let day = date.getDate(); //获取当前日

      let oneDay = 24 * 3600 * 1000

      let daytimeArr = []

      for (let i = 6; i > 0; i--) { //前七天的时间
        let now = new Date(base - oneDay * i);
        let myear = now.getFullYear();
        let month = now.getMonth() + 1;
        let mday = now.getDate()
        daytimeArr.push([myear, month >= 10 ? month : '0' + month, mday >= 10 ? mday : '0' + mday].join('/'))
      }
      daytimeArr.push([year, mon >= 10 ? mon : '0' + mon, day >= 10 ? day : '0' + day].join('/'))

      console.log(daytimeArr)

      this.lineXaxis = daytimeArr;
      this.lineSeriesData = [0, 0, 0, 0, 0, 0, 0];

    },

    assignLineChart () {
      this.lineOption = lineOption();
      this.$refs.lineChart.setOption(this.lineOption, true);
      this.$refs.lineChart.setOption(
        {
          xAxis: { data: this.lineXaxis },
          series: [{ data: this.lineSeriesData }],
        },
        true
      );
    },

    getOrgTreeList () {
      const { user } = this.$store.state
      this.$http
        .post('/gov/org/customeragency/agencygridtree', {})
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取组织树成功', res.data)
            this.orgOptions = []
            this.orgOptions.push(res.data)
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },

    handleChangeAgency (val) {
      let obj = this.$refs["myCascader"].getCheckedNodes()[0].data
      if (obj) {
        if (obj.level === 'grid') {
          this.gridId = this.agencyIdArray.length > 0 ? this.agencyIdArray[this.agencyIdArray.length - 1] : '';
          this.agencyId = ''
        } else {
          this.agencyId = this.agencyIdArray.length > 0 ? this.agencyIdArray[this.agencyIdArray.length - 1] : '';
          this.gridId = ''
        }

      } else {
        this.agencyId = ''
        this.gridId = ''
      }
      this.agencyId = obj.agencyId
    },


  },
};
</script>

<style
  lang="scss"
  src="@/assets/scss/modules/visual/warning.scss"
  scoped
></style>
<style lang="scss" scoped>
.div_main {
  background: #fff;
  margin: 10px;
  padding: 10px;
}
.card-title {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-bottom: 10px;
  padding: 4px 2px;
  .title-icon {
    display: block;
    width: 46px;
    height: 34px;
    box-sizing: border-box;
    margin-right: 6px;
  }

  .title-time {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    margin-left: 30px;
    font-size: 14px;
    color: #fff;
    .title-time-label {
      margin-right: 10px;
    }
  }
  .title-label {
    font-size: 16px;
    font-family: PingFang SC;
    // font-weight: 800;
  }
}
.card-echart {
  display: flex;
  margin-top: 40px;
  height: 100%;
  .card-left {
    position: relative;
    flex: 1;
    // display: flex;
    height: 100%;
    .card-flex {
      width: 100%;
      display: flex;
    }
  }
}
.card-left-title {
  position: relative;
  padding-left: 40px;
  font-size: 16px;
  font-weight: 500;
}
.card-left-title::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 20px;
  width: 12px;
  height: 12px;
  box-sizing: border-box;
  margin-top: -6px;
  background: #2865fa;
  border-radius: 50%;
}
.echart-wr {
  position: relative;
  flex-shrink: 0;
  width: 90%;
  height: 520px;
  box-sizing: border-box;
  .echart-org {
    width: 100%;
    height: 100%;
  }
}
</style>
