<script>
import * as echarts from "echarts";
import {getScoreTimeStatByParams, listRootScorePackageSenders} from "@/api/score_package";
import {autoDetectStatUnit, fixMissingTimeSeriesData, formatEndDate, formatNumber, formatStartDate} from "@/utils";
import dayjs from "@/plugins/dayjs";

export default {
  name: "HomeXfjfbPanel",
  data() {
    return {
      searchForm: {
        rootPackageSendPackageDeptId:null,
        rootPackageCreateTimeRange:[dayjs().startOf('year').toDate(), dayjs().toDate()],
      },
      rootScorePackageSenders:[],
      metricName:'score',
      metrics:[{label:'积分',value:'score'},{label:'个数',value:'count'}],
      statUnit:'auto',
      realStatUnit:'auto',
      statUnits:[
        {label:'天',value:'day'},
        {label:'周',value:'week'},
        {label:'月',value:'month'},
        {label:'季度',value:'quarter'},
        {label:'年',value:'year'},
        {label:'自动',value:'auto'}
      ],
      data:[],
      totalStat:{}
    };
  },
  created() {
    window.addEventListener('resize',this.onWindowResize)
    this.loadRootScorePackageSenders()
    this.loadData()
  },
  destroyed() {
    window.removeEventListener('resize',this.onWindowResize)
  },
  activated() {
    this.onWindowResize()
  },
  watch:{
    metricName(val){
      this.drawChart()
    },
    searchForm:{
      deep:true,
      handler(){
        this.loadData()
      }
    },
    statUnit(){
      this.loadData()
    }
  },
  methods:{
    async loadRootScorePackageSenders() {
      this.rootScorePackageSenders = await listRootScorePackageSenders()
    },
    async loadData(){
      let statUnit=this.statUnit
      if (statUnit === 'auto') {
        if (this.searchForm.rootPackageCreateTimeRange) {
          const timeDiff=this.searchForm.rootPackageCreateTimeRange[1].getTime()-this.searchForm.rootPackageCreateTimeRange[0].getTime()
          statUnit=autoDetectStatUnit(timeDiff)
        } else {
          statUnit = 'year'
        }
      }
      this.realStatUnit=statUnit
      const params = {
        statUnit,
        rootPackageSendPackageDeptId: this.searchForm.rootPackageSendPackageDeptId,
        rootPackageCreateTimeGe: this.searchForm.rootPackageCreateTimeRange ? formatStartDate(this.searchForm.rootPackageCreateTimeRange[0]) : null,
        rootPackageCreateTimeLe: this.searchForm.rootPackageCreateTimeRange ? formatEndDate(this.searchForm.rootPackageCreateTimeRange[1]) : null,
      }
      this.data = fixMissingTimeSeriesData(await getScoreTimeStatByParams(params),statUnit,{
        entScore: 0,
        userScore: 0,
        cso1Score:0,
        cso2Score:0,
        entCount: 0,
        userCount: 0,
        cso1Count:0,
        cso2Count:0,
      })
      this.drawChart()
    },
    getStatUnitName(value){
      return this.statUnits.find(item => item.value === value).label
    },
    drawChart(){
      const color=['#5B7BE3','#73B5BE','#DC99AD','#D25D46']
      const categoryData=[]
      const seriesDataEnt=[]
      const seriesDataUser=[]
      const seriesDataCso1=[]
      const seriesDataCso2=[]
      const totalStat={
        entScore:0,
        userScore:0,
        cso1Score:0,
        cso2Score:0,
        entCount:0,
        userCount:0,
        cso1Count:0,
        cso2Count:0,
      }
      for(const item of this.data){
        categoryData.push(item.timeKey)
        if(this.metricName==='score'){
          seriesDataEnt.push(item.entScore)
          seriesDataUser.push(item.userScore)
          seriesDataCso1.push(item.cso1Score)
          seriesDataCso2.push(item.cso2Score)
        }else{
          seriesDataEnt.push(item.entCount)
          seriesDataUser.push(item.userCount)
          seriesDataCso1.push(item.cso1Count)
          seriesDataCso2.push(item.cso2Count)
        }
        totalStat.entScore+=item.entScore
        totalStat.userScore+=item.userScore
        totalStat.cso1Score+=item.cso1Score
        totalStat.cso2Score+=item.cso2Score
        totalStat.entCount+=item.entCount
        totalStat.userCount+=item.userCount
        totalStat.cso1Count+=item.cso1Count
        totalStat.cso2Count+=item.cso2Count
      }
      this.totalStat=totalStat
      this.chart1 = echarts.init(this.$refs.chart1, "macarons");
      this.chart1.setOption({
        color:color,
        grid:{
          top:40,
          left:80,
          bottom:30,
          right:40
        },
        xAxis: {
          type: 'category',
          data: categoryData,
          name: this.getStatUnitName(this.realStatUnit)
        },
        yAxis: {
          type: 'value',
          name: this.metricName==='score'?'积分':'个数'
        },
        tooltip: {
          show: 'true',
          trigger: 'axis',
        },
        legend: {
          show:true
        },
        toolbox: {
          show: true,
          feature: {
            dataView: {
              show: true,
              readOnly: false
            },
            restore: {
              show: true
            },
            saveAsImage: {
              show: true
            }
          }
        },
        series: [
          {
            data: seriesDataEnt,
            type: 'line',
            name: '企业包',
            label:{
              show:true,
              formatter:params=>{
                return formatNumber(params.value)
              }
            }
          },
          {
            data: seriesDataCso1,
            type: 'line',
            name: 'CSO1包',
            label:{
              show:true,
              formatter:params=>{
                return formatNumber(params.value)
              }
            }
          },
          {
            data: seriesDataCso2,
            type: 'line',
            name: 'CSO2包',
            label:{
              show:true,
              formatter:params=>{
                return formatNumber(params.value)
              }
            }
          },
          {
            data: seriesDataUser,
            type: 'line',
            name: '个人包',
            label:{
              show:true,
              formatter:params=>{
                return formatNumber(params.value)
              }
            }
          }
        ]
      })
    },
    onWindowResize(){
      if(this.chart1){
        this.chart1.resize()
      }
    },
    formatNumber:formatNumber
  }
}
</script>

<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>下发积分包情况</span>
      <el-form style="float: right;" inline>
        <el-form-item>
          <el-select
            v-model="searchForm.rootPackageSendPackageDeptId"
            multiple
            filterable
            reserve-keyword
            placeholder="源头包发包对象" style="width: 300px;">
            <el-option
              v-for="item in rootScorePackageSenders"
              :key="item.deptId"
              :label="item.name"
              :value="item.deptId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="metricName" placeholder="指标" style="width: 80px;">
            <el-option v-for="item in metrics" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker v-model="searchForm.rootPackageCreateTimeRange" type="daterange" style="width: 230px;" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select v-model="statUnit" placeholder="间隔" style="width: 80px;">
            <el-option v-for="item in statUnits" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <span>总值：</span>
      <span style="font-weight: bold;margin-right: 50px;">企业包 {{formatNumber(totalStat.entScore)}}分 {{formatNumber(totalStat.entCount)}}个</span>
      <span style="font-weight: bold;margin-right: 50px;">CSO1包 {{formatNumber(totalStat.cso1Score)}}分 {{formatNumber(totalStat.cso1Count)}}个</span>
      <span style="font-weight: bold;margin-right: 50px;">CSO2包 {{formatNumber(totalStat.cso2Score)}}分 {{formatNumber(totalStat.cso2Count)}}个</span>
      <span style="font-weight: bold">个人包 {{formatNumber(totalStat.userScore)}}分 {{formatNumber(totalStat.userCount)}}个</span>
    </div>
    <div ref="chart1" style="height: 261px;"></div>
  </el-card>
</template>

<style scoped lang="scss">

</style>
