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

export default {
  name: "HomeJscgjfbPanel",
  data() {
    return {
      searchForm: {
        rootPackageSendPackageDeptId:null,
        settleNotifyTimeRange:[dayjs().startOf('year').toDate(), dayjs().toDate()],
      },
      rootScorePackageSenders:[],
      metricName:'score',
      metrics:[{label:'积分',value:'score'},{label:'金额',value:'amount'}],
      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:{},
      totalUsers:0,
    };
  },
  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.settleNotifyTimeRange) {
          const timeDiff=this.searchForm.settleNotifyTimeRange[1].getTime()-this.searchForm.settleNotifyTimeRange[0].getTime()
          statUnit=autoDetectStatUnit(timeDiff)
        } else {
          statUnit = 'year'
        }
      }
      this.realStatUnit=statUnit
      const params = {
        statUnit,
        rootPackageSendPackageDeptId: this.searchForm.rootPackageSendPackageDeptId,
        settleNotifyTimeGe: this.searchForm.settleNotifyTimeRange ? formatStartDate(this.searchForm.settleNotifyTimeRange[0]) : null,
        settleNotifyTimeLe: this.searchForm.settleNotifyTimeRange ? formatEndDate(this.searchForm.settleNotifyTimeRange[1]) : null,
      }
      const data=await getSettledTimeStatByParams(params)
      this.totalUsers=data.totalUsers
      this.data = fixMissingTimeSeriesData(data.list,statUnit,{
        totalScore: 0,
        totalAmount: 0,
        totalPackages: 0,
        totalUsers: 0,
        totalActualAmount:0,
      })
      this.drawChart()
    },
    getStatUnitName(value){
      return this.statUnits.find(item => item.value === value).label
    },
    drawChart(){
      const categoryData=[]
      const seriesDataForTotalScore=[]
      const seriesDataForTotalPackages=[]
      const seriesDataForTotalAmount=[]
      const seriesDataForTotalActualAmount=[]
      const seriesDataForTotalUsers=[]
      const totalStat={
        totalScore:0,
        totalAmount:0,
        totalPackages:0,
        totalActualAmount:0,
      }
      for(const item of this.data){
        categoryData.push(item.timeKey)
        if(this.metricName==='score'){
          seriesDataForTotalScore.push(item.totalScore)
          seriesDataForTotalPackages.push(item.totalPackages)
        }else{
          seriesDataForTotalAmount.push(item.totalAmount)
          seriesDataForTotalActualAmount.push(item.totalActualAmount)
          seriesDataForTotalUsers.push(item.totalUsers)
        }
        totalStat.totalScore+=item.totalScore
        totalStat.totalPackages+=item.totalPackages
        totalStat.totalAmount+=item.totalAmount
        totalStat.totalActualAmount+=item.totalActualAmount
      }
      this.totalStat=totalStat
      this.chart1 = echarts.init(this.$refs.chart1, "macarons");
      this.chart1.setOption({
        grid:{
          top:60,
          left:80,
          bottom:30,
          right:40
        },
        xAxis: {
          type: 'category',
          data: categoryData,
          name: this.getStatUnitName(this.realStatUnit)
        },
        yAxis: this.metricName==='score'?[
          {
            type: 'value',
            name: '积分'
          },
          {
            type: 'value',
            name: '个数'
          }
        ]:[
          {
            type: 'value',
            name: '金额'
          },
          {
            type: 'value',
            name: '人数'
          }
        ],
        tooltip: {
          show: 'true',
          trigger: 'axis',
        },
        legend: {
          show:true
        },
        toolbox: {
          show: true,
          feature: {
            dataView: {
              show: true,
              readOnly: false
            },
            restore: {
              show: true
            },
            saveAsImage: {
              show: true
            }
          }
        },
        series: this.metricName==='score'?[
          {
            data: seriesDataForTotalScore,
            type: 'line',
            name: '积分',
            label:{
              show:true,
              formatter:params=>{
                return formatNumber(params.value)
              }
            }
          },
          {
            data: seriesDataForTotalPackages,
            type: 'line',
            name: '个数',
            yAxisIndex: 1,
            label:{
              show:true,
              formatter:params=>{
                return formatNumber(params.value)
              }
            }
          }
        ]:[
          {
            data: seriesDataForTotalAmount,
            type: 'line',
            name: '结算金额',
            label:{
              show:true,
              formatter:params=>{
                return formatMoney(params.value)
              }
            }
          },
          {
            data: seriesDataForTotalActualAmount,
            type: 'line',
            name: '支付金额',
            label:{
              show:true,
              formatter:params=>{
                return formatMoney(params.value)
              }
            }
          },
          {
            data: seriesDataForTotalUsers,
            type: 'line',
            name: '人数',
            yAxisIndex: 1,
            label:{
              show:true,
              formatter:params=>{
                return formatNumber(params.value)
              }
            }
          }
        ]
      })
    },
    onWindowResize(){
      if(this.chart1){
        this.chart1.resize()
      }
    },
    formatNumber:formatNumber,
    formatMoney:formatMoney
  }
}
</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.settleNotifyTimeRange" 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.totalScore)}}分 {{formatNumber(totalStat.totalPackages)}}个</span>
      <span style="font-weight: bold;margin-right: 50px;">结算成功金额 {{formatMoney(totalStat.totalAmount)}}元 {{formatNumber(totalUsers)}}人</span>
      <span style="font-weight: bold">支付成功金额 {{formatMoney(totalStat.totalActualAmount)}}元</span>
    </div>
    <div ref="chart1" style="height: 261px;"></div>
  </el-card>
</template>

<style scoped lang="scss">

</style>
