<template>
  <div class="chart-box">
    <div class="title-top">
      <span>订单来源</span>
      <el-select v-model="dateValue" size="mini" class="select" placeholder="请选择" @change="dateChange">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
        </div>
    <div class="chart" :id="id"></div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import * as echarts from 'echarts';
type EChartsOption = echarts.EChartsOption;

@Component
export default class Pie02 extends Vue {
  id=this.randomString();
  dateValue=30
  options:Array<any>=[{
    label:'今日',
    value:1
  },{
    label:'7天',
    value:7
  },{
    label:'30日',
    value:30
  }]
  mounted(){
    this.getData()
  }

  randomString(){
    const str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let result = '';
    for (let i = 10; i > 0; --i) 
      result += str[Math.floor(Math.random() * str.length)];
    return result;
  }
  dateChange(){
    this.getData()
  }
  getData() {
    (this as any).$request({
      url:'/omsOrder/report/upSourceCount',
      method: 'GET',
      params:{
        days:this.dateValue
      }
    }).then((res:any) => {
      if(res.data) {
        this.initChart(res.data)
      }
    }).catch(() =>{})
  }
  initChart(data:Array<any>){
    let chartDom:any = document.getElementById(this.id);
    let myChart = echarts.init(chartDom);
    let option: EChartsOption;
    let _data:Array<any>=[]
    for(const item of data) {
      _data.push({
        name: item.up_source_name,
        value:item.total
      })
    }
    option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        show:true,
        bottom:0
      },
      series: [
        {
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            formatter: '{b}:\n {d}' + '%',
            position:'inside'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: _data
        }
      ]
    };

    option && myChart.setOption(option);
  }

}
</script>

<style lang="scss" scoped>
.chart-box{
  height: 100%;
  width: 100%;
  .title-top{
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    width: 100%;
    >span{
      font-size: 16px;
      font-weight: 700;
    }
    .select{
      width: 100px;
      position: absolute;
      top: 6px;
      right: 0;
    }
  }
}
.chart{
  height: calc(100% - 40px);
  width: 100%;
}
</style>>