<!--
 * @Author: ysh
 * @Date: 2024-10-17 10:40:13
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-10-18 14:55:46
-->
<template>
  <div style="width:100%;" v-loading="loading">
    <div class="titles">设备和车辆统计</div>
    <div class="warpper">
      <div class="left">
        <div class="left-top" id="deviceYearBar"></div>
        <div class="left-top" id="deviceStatusPie"></div>
      </div>
      <div class="middle" v-loading="deviceDataLoading">
        <div class="middle-chart" id="deviceApprovalBar"></div>
      </div>
      <div class="right">
        <div class="right-top" id="carYearBar"></div>
        <div class="right-top" id="carStatusPie" v-loading="carDataLoading"></div>
      </div>
      <div class="right" v-loading="carDataLoading">
        <div class="right-top" id="carApprovalBar"></div>
        <div class="right-top" id="carDayBar"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { echartsInit } from '@/utils/echarts'
import { getCarStatistic } from '@/api/oa/car/car';
import { getDeviceStatistic } from '@/api/oa/device/device';
let deviceYearChart, deviceStatusChart, deviceApprovalChart, carYearChart, carStatusChart, carApprovalChart, carDayChart
export default {
  props: {
    deviceData: {
      type: Object,
      require: true,
    },
    carData: {
      type: Object,
      require: true,
    }
  },
  watch: {
    carUsage(){
      this.initCarUsagePie()
    },
    carApproval(){
      this.initCarApprovalBar()
    },
    carDay(){
      this.initCarDayBar()
    }
  },
  data() {
    return {
      loading: true,
      deviceApproval: {},
      deviceStatus: {},
      deviceYear: {},
      carApproval: {},
      carStatus: {},
      carYear: {},
      carUsage: {},
      carDay: {},
      deviceDataLoading: false,
      carDataLoading: false,
      isYearView: true,
      activeYear: '',
      deviceMonth: {},
      carMonth: {}
    }
  },
  created() {
    this.loading = true;
    this.initDeviceDatas();
    this.initCarDatas();
    this.loading = false;
  },
  mounted() {
    this.initDeviceYearBar();
    this.initDeviceStatusPie();
    this.initDeviceApprovalBar();
    this.initCarYearBar();
    this.initCarUsagePie();
    this.initCarApprovalBar();
    this.initCarDayBar();
  },
  methods: {
    async initDeviceDatas() {
      if (Object.keys(this.deviceData).length !== 0) {
        this.deviceApproval = this.deviceData.approval;
        this.deviceStatus = this.deviceData.status[0];
        this.deviceYear = this.deviceData.year[0];
        if (this.deviceData.month) {
          this.deviceMonth = this.deviceData.month[0];
        }
      }
    },
    async initCarDatas() {
      if (Object.keys(this.carData).length !== 0) {
        this.carApproval = this.carData.approval;
        this.carStatus = this.carData.status[0];
        this.carYear = this.carData.year[0];
        this.carUsage = this.carData.usage[0];
        this.carDay = this.carData.day;
        if (this.carData.month) {
          this.carMonth = this.carData.month[0];
        }
      }
    },
    clickDeviceYear(charts) {
      let that = this;
      charts.off('click');
      charts.on('click', function (event) {
        if (event) {
          if (event.name === '' || event.name === undefined) {
            that.isYearView = true;
            that.activeYear = '';
            that.initDeviceYearBar();
          } else {
            that.activeYear = event.name;
            that.isYearView = false;
            that.deviceDataLoading = true;
            getDeviceStatistic({ applyDate: event.name + '-01-01' }).then(res => {
              if (res.data.month) {
                that.deviceMonth = res.data.month[0];
              }
              that.deviceApproval = res.data.approval;
              that.deviceYear = res.data.year[0];
              that.deviceDataLoading = false;
              that.initDeviceYearBar();
              that.initDeviceApprovalBar();
            })
          }
        }
      })
    },
    clickCarYear(charts) {
      let that = this;
      charts.off('click');
      charts.on('click', function (event) {
        if (event) {
          if (event.name === '' || event.name === undefined) {
            that.isYearView = true;
            that.activeYear = '';
            that.initCarYearBar();
          } else {
            that.activeYear = event.name;
            that.isYearView = false;
            that.carDataLoading = true;
            getCarStatistic({ applyDate: event.name + '-01-01' }).then(res => {
              if (res.data.month) {
                that.carMonth = res.data.month[0];
              }
              that.carApproval = res.data.approval;
              that.carUsage = res.data.usage[0];
              that.carDay = res.data.day;
              that.carYear = res.data.year[0];
              that.carDataLoading = false;
              that.initCarYearBar();
              that.initCarUsagePie();
              that.initCarApprovalBar();
              that.initCarDayBar();
            })
          }
        }
      })
    },
    goBackToYear() {
      this.isYearView = true;
      this.activeYear = '';
      this.deviceMonth = {};
      this.carMonth = {};
      this.initDeviceDatas();
      this.initCarDatas();
      this.initDeviceYearBar();
      this.initDeviceApprovalBar();
      this.initCarYearBar();
      this.initCarUsagePie();
      this.initCarApprovalBar();
      this.initCarDayBar();
    },
    goBackToCarYear() {
      this.isYearView = true;
      this.activeYear = '';
      this.carMonth = {};
      this.initCarDatas();
      this.initCarYearBar();
      this.initCarUsagePie();
      this.initCarApprovalBar();
      this.initCarDayBar();
    },
    initDeviceYearBar() {
      let xData = this.isYearView ? Object.keys(this.deviceYear) : Object.keys(this.deviceMonth);
      let deviceData = this.isYearView ? Object.values(this.deviceYear) : Object.values(this.deviceMonth);
      let titleText = this.isYearView ? '设备申领次数' : this.activeYear + '年设备申领次数';
      let subtext = this.isYearView ? '设备申领次数：' + Object.values(this.deviceYear).reduce((accumulator, currentValue) => accumulator + currentValue, 0) + '次' : '设备申领次数：' + Object.values(this.deviceMonth).reduce((accumulator, currentValue) => accumulator + currentValue, 0) + '次';
      let xName = this.isYearView ? '年' : '月';
      
      let option = {
        title: {
          text: titleText,
          subtext: subtext
        },
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        graphic: this.isYearView ? [] : [{
          type: 'text',
          name: '',
          right: '0',
          top: '20%',
          style: {
            text: '返回',
            fill: '#409EFF',
            fontSize: 12,
            fontWeight: ''
          },
          onclick: () => { this.goBackToYear(); }
        }],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          name: xName,
          type: 'category',
          data: xData,
        },
        yAxis: {
          type: 'value',
          name: '单位：次'
        },
        series: [
          {
            data: deviceData,
            type: 'bar',
            smooth: true,
            label: {
              show: true,
              position: 'top'
            },
            itemStyle:{
              color:'#3498DB'
            }
          }
        ]
      };
      let charts = echartsInit(deviceYearChart, 'deviceYearBar', option);
      this.clickDeviceYear(charts);
    },
    initDeviceStatusPie() {
      let option = {
        title: {
          text: '设备和车辆状态',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          top: 'bottom'
        },
        series: [
          {
            name: '占比',
            type: 'pie',
            radius: '25%',
            center:['25%', '50%'],
            avoidLabelOverlap: false,
            data: Object.entries(this.deviceStatus).map(([key, value]) => {
              return { name: key, value: value }
            }),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              alignTo: 'none',
              minMargin: 5,
              edgeDistance: 8,
              lineHeight: 15,
              rich: {
                time: {
                  fontSize: 10,
                  color: '#999'
                }
              }
            },
          },
          
          {
            name: '占比',
            type: 'pie',
            radius: '25%',
            center:['75%', '50%'],
            avoidLabelOverlap: false,
            data: Object.entries(this.carStatus).map(([key, value]) => {
              return { name: key, value: value }
            }),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              alignTo: 'none',
              minMargin: 5,
              edgeDistance: 8,
              lineHeight: 15,
              rich: {
                time: {
                  fontSize: 10,
                  color: '#999'
                }
              }
            },
          },
        ]
      };
      echartsInit(deviceStatusChart, 'deviceStatusPie', option);
    },
    initDeviceApprovalBar() {
      let xData = this.deviceApproval.map(item => item.count)
      let yData = this.deviceApproval.map(item => item.name)
      let titleText = this.isYearView ? '设备申请次数榜' : this.activeYear + '年设备申请次数榜';
      let option = {
        title: {
          text: titleText
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        toolbox: {
          feature: {
            dataView: {
              show: true,
              optionToContent: function (opt) {
                var axisData = opt.yAxis[0].data;
                var series = opt.series;
                var table = '<table border="1" style="width:100%;text-align:center;border-collapse: collapse;"><tbody><tr>'
                  + '<td>设备名称</td>'
                  + '<td>数量</td>'
                  + '</tr>';
                for (var i = 0, l = axisData.length; i < l; i++) {
                  table += '<tr>'
                    + '<td>' + axisData[i] + '</td>'
                    + '<td>' + series[0].data[i] + '</td>'
                    + '</tr>';
                }
                table += '</tbody></table>';
                return table;
              }
            }
          }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100,
            show: true,
            yAxisIndex: 0,
          }
        ],
        grid: {
          left: '3%',
          right: '8%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
        },
        yAxis: {
          type: 'category',
          data: yData.reverse(),
          axisLabel: {
            fontSize: 12,
            width: 120,
            overflow: 'truncate',
          }
        },
        series: [
          {
            type: 'bar',
            data: xData.reverse(),
          }
        ]
      };
      echartsInit(deviceApprovalChart, 'deviceApprovalBar', option);
    },
    initCarYearBar(){
      let xData = this.isYearView ? Object.keys(this.carYear) : Object.keys(this.carMonth);
      let carData = this.isYearView ? Object.values(this.carYear) : Object.values(this.carMonth);
      let titleText = this.isYearView ? '用车申请次数' : this.activeYear + '年用车申请次数';
      let subtext = this.isYearView ? '用车申请次数：' + Object.values(this.carYear).reduce((accumulator, currentValue) => accumulator + currentValue, 0) + '次' : '用车申请次数：' + Object.values(this.carMonth).reduce((accumulator, currentValue) => accumulator + currentValue, 0) + '次';
      let xName = this.isYearView ? '年' : '月';
      
      let option = {
        title: {
          text: titleText,
          subtext: subtext
        },
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        graphic: this.isYearView ? [{
          type: 'text',
          name: '',
          right: '0',
          top: '20%',
          style: {
            text: '全部年份',
            fill: '#000',
            fontSize: 12,
            fontWeight: ''
          }
        }] : [{
          type: 'text',
          name: '',
          right: '0',
          top: '20%',
          style: {
            text: '返回',
            fill: '#409EFF',
            fontSize: 12,
            fontWeight: ''
          },
          onclick: () => { this.goBackToCarYear(); }
        }],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          name: xName,
          type: 'category',
          data: xData,
        },
        yAxis: {
          type: 'value',
          name: '单位：次'
        },
        series: [
          {
            data: carData,
            type: 'bar',
            smooth: true,
            label: {
              show: true,
              position: 'top'
            },
            itemStyle:{
              color:'#1ABC9C'
            }
          }
        ]
      };
      let charts = echartsInit(carYearChart, 'carYearBar', option);
      this.clickCarYear(charts)
    },
    initCarUsagePie(){
      let titleText = this.isYearView ? '车辆申请类型' : this.activeYear + '年车辆申请类型';
      let option = {
        title: {
          text: titleText,
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          top: 'bottom'
        },
        series: [
          {
            name: '占比',
            type: 'pie',
            radius: '40%',
            // center:['75%', '50%'],
            avoidLabelOverlap: false,
            data: Object.entries(this.carUsage).map(([key, value]) => {
              return { name: key, value: value }
            }),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              alignTo: 'none',
              minMargin: 5,
              edgeDistance: 8,
              lineHeight: 15,
              rich: {
                time: {
                  fontSize: 10,
                  color: '#999'
                }
              }
            },
          },
        ]
      };
      echartsInit(carStatusChart, 'carStatusPie', option);
    },
    initCarApprovalBar(){
      let xData = this.carApproval.map(item => item.count)
      let yData = this.carApproval.map(item => item.name)
      let titleText = this.isYearView ? '车辆使用次数榜' : this.activeYear + '年车辆使用次数榜';
      let option = {
        title: {
          text: titleText
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        toolbox: {
          feature: {
            dataView: {
              show: true,
              optionToContent: function (opt) {
                var axisData = opt.yAxis[0].data;
                var series = opt.series;
                var table = '<table border="1" style="width:100%;text-align:center;border-collapse: collapse;"><tbody><tr>'
                  + '<td>车辆名称</td>'
                  + '<td>数量</td>'
                  + '</tr>';
                for (var i = 0, l = axisData.length; i < l; i++) {
                  table += '<tr>'
                    + '<td>' + axisData[i] + '</td>'
                    + '<td>' + series[0].data[i] + '</td>'
                    + '</tr>';
                }
                table += '</tbody></table>';
                return table;
              }
            }
          }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100,
            show: true,
            yAxisIndex: 0,
          }
        ],
        grid: {
          left: '3%',
          right: '8%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
        },
        yAxis: {
          type: 'category',
          data: yData.reverse(),
          axisLabel: {
            fontSize: 12,
            width: 120,
            overflow: 'truncate',
          }
        },
        series: [
          {
            type: 'bar',
            data: xData.reverse(),
          }
        ]
      };
      echartsInit(carApprovalChart, 'carApprovalBar', option);
    },
    initCarDayBar(){
      let xData = this.carDay.map(item => item.count)
      let yData = this.carDay.map(item => item.name)
      let titleText = this.isYearView ? '车辆使用天数榜' : this.activeYear + '年车辆使用天数榜';
      let option = {
        title: {
          text: titleText
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        toolbox: {
          feature: {
            dataView: {
              show: true,
              optionToContent: function (opt) {
                var axisData = opt.yAxis[0].data;
                var series = opt.series;
                var table = '<table border="1" style="width:100%;text-align:center;border-collapse: collapse;"><tbody><tr>'
                  + '<td>车辆名称</td>'
                  + '<td>数量</td>'
                  + '</tr>';
                for (var i = 0, l = axisData.length; i < l; i++) {
                  table += '<tr>'
                    + '<td>' + axisData[i] + '</td>'
                    + '<td>' + series[0].data[i] + '</td>'
                    + '</tr>';
                }
                table += '</tbody></table>';
                return table;
              }
            }
          }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100,
            show: true,
            yAxisIndex: 0,
          }
        ],
        grid: {
          left: '3%',
          right: '8%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
        },
        yAxis: {
          type: 'category',
          data: yData.reverse(),
          axisLabel: {
            fontSize: 12,
            width: 120,
            overflow: 'truncate',
          }
        },
        series: [
          {
            type: 'bar',
            data: xData.reverse(),
          }
        ]
      };
      echartsInit(carDayChart, 'carDayBar', option);
    }
  },
}
</script>

<style lang="scss" scoped>
.titles {
  font-family: 'puhuiti';
  font-size: 16px;
  margin-bottom: 16px;
}

.warpper {
  width: 100%;
  height: 100%;
  display: flex;

  .left {
    flex: 1;

    .left-top {
      width: 100%;
      height: 300px;
      padding: 10px;
      border: 1px solid #ececec;
    }
  }

  .middle {
    flex: 1;

    .middle-chart {
      width: 100%;
      height: 600px;
      padding: 10px;
      border: 1px solid #ececec;
    }
  }

  .right {
    flex: 1;

    .right-top {
      width: 100%;
      height: 300px;
      padding: 10px;
      border: 1px solid #ececec;
    }
  }
}
</style>