<template>
  <el-card v-loading="loading" shadow="never" style="margin-bottom: 5px; border-radius:0;">
    <div style="height: 350px;" ref="chartRef"></div>
  </el-card>
</template>

<script lang="ts" setup>
import { ref,onMounted, onBeforeUnmount, watch, computed } from 'vue'
import * as echarts from 'echarts'
import { GetLineList } from './api'
import { parseQueryParams } from '/@/views/adManage/utils/tools.js'

interface Props {
  query: any
}
const props = defineProps<Props>()
const chartRef = ref()
let chartObj:any
const loading = ref(true)
const queryParams = computed(() => parseQueryParams(props.query))

const resizeChart = () => { chartObj.resize() }
const addResize = () => { window.addEventListener('resize', resizeChart) }
const removeResize = () => { window.removeEventListener('resize', resizeChart) }
onMounted(() => {
  addResize()
  setTimeout(() => { initLine() }, 0)
})
onBeforeUnmount(() => {
	if(chartObj) {
		chartObj.dispose()
    chartObj = null
	}
  removeResize()
})

const initLine = async () => {
  chartObj = echarts.init(chartRef.value)
  const option = {
    dataset: {
      source: []
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    grid: { top: 30, bottom: 30, left: 30, right: 30 },
    xAxis: {
      type: 'category'
    },
    yAxis: {
      type: 'value',
      name: '预算',
      axisLine: {
        show: true,
				lineStyle: { color: '#0085ff' }
      },
    },
    series: [
      {
        type: 'line',
        encode: {
          x: 'date',
          y: 'campaignBudgetAmount'
        },
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        lineStyle: { width: 2 },
        itemStyle: {
          color: '#0085ff',
          borderColor: '#0085ff'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#0085ff93' },
            { offset: 1, color: '#0085ff03' },
          ]),
        },
      }
    ]
  }
  const items = await getDataset()
  option.dataset.source = items
  chartObj.setOption(option)
  loading.value = false
}
const getDataset = async () => {
  const resp = await GetLineList(queryParams.value)
  return resp.data
}
watch(
  props.query,
  async () => {
    loading.value = true

    const dataset = await getDataset()
    chartObj.setOption({
      dataset: {
        source: dataset
      }
    })

    loading.value = false
  },
  { deep: true }
)
</script>

<style scoped>

</style>