<template>
  <div class="dashboard-line-box">
    <div class="dashboard-line-title">
      公司费用
    </div>
    <div
      ref="echart"
      class="dashboard-line"
    />
  </div>
</template>
<script setup>
import * as echarts from 'echarts'
import { nextTick, onMounted, onUnmounted, ref } from 'vue'
import { useWindowResize } from '@/hooks/use-windows-resize'
import { querySurplus } from '@/api/cost'

const queryData = async() => {
  await querySurplus().then(res => {
    console.log(res.data)
    for (let i = 0; i < res.data.length; i++) {
      dataAxis.push(res.data[i].FeeTime)
      expenditureData.push(res.data[i].ExpenditureAmountSum)
      depositData.push(res.data[i].DepositAmountSum)
      surplusData.push(res.data[i].Surplus)
    }
  })
}

var dataAxis = []
var expenditureData = []
var depositData = []
var surplusData = []

let chart = null
const echart = ref(null)

useWindowResize(() => {
  if (!chart) {
    return
  }
  chart.resize()
})

const initChart = () => {
  if (chart) {
    chart = null
  }
  chart = echarts.init(echart.value)
  setOptions()
}
const setOptions = () => {
  chart.setOption({
    legend: {
      data: ['支出', '支入', '盈余']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dataAxis,
    },
    yAxis: {
      type: 'value'
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ],
    series: [
      {
        name: '支出',
        type: 'line',
        stack: 'Total',
        data: expenditureData,
        smooth: true,
      },
      {
        name: '支入',
        type: 'line',
        stack: 'Total',
        data: depositData,
        smooth: true,
      },
      {
        name: '盈余',
        type: 'line',
        stack: 'Total',
        data: surplusData,
        smooth: true,
      },
    ],
  })
}

onMounted(async() => {
  await nextTick()
  await queryData()
  initChart()
})

onUnmounted(() => {
  if (!chart) {
    return
  }
  chart.dispose()
  chart = null
})
</script>
<style lang="scss" scoped>
.dashboard-line-box {
  .dashboard-line {
    background-color: #fff;
    height: 360px;
    width: 90%;
  }
  .dashboard-line-title {
    font-weight: 600;
    margin-bottom: 12px;
  }
}
</style>
