<template>
    <div ref="chartRef" class="app-hqchart" :style="{ width, height }"></div>
</template>
  
<script lang="ts" setup>
import { shallowRef, onMounted, onUnmounted } from 'vue'
import { Chart } from 'hqchart'
import { timerInterceptor } from '@/utils/timer'
import ResizeObserver from 'resize-observer-polyfill'

const props = defineProps({
    // 图表宽度
    width: {
        type: String,
        default: '100%',
    },
    // 图表高度
    height: {
        type: String,
        default: '100%',
    },
    // 图表配置项
    option: {
        type: Object
    },
    dataIndex: {
        type: Number,
        default: 0,
    }
})

const emit = defineEmits(['ready', 'update:dataIndex'])
const chartRef = shallowRef()

const resource = Chart.JSChart.GetResource()
resource.FrameLogo.Text = ''

// https://blog.csdn.net/jones2000/article/details/104122774
Chart.JSConsole.Chart.Log = () => ({})
Chart.JSConsole.Complier.Log = () => ({})

// 默认配置项
const defaultOption = {
    Symbol: 'default', // 股票代码(必填)
    IsAutoUpdate: false,
    IsApiPeriod: true, // 每次切换周期请求接口数据
}

onMounted(() => {
    const el = chartRef.value
    const chartInstance = Chart.JSChart.Init(el)
    chartInstance.SetOption(props.option ?? defaultOption)

    // 自适应图表大小
    const resize = timerInterceptor.setDebounce(() => {
        chartInstance.OnSize()
    }, 50)

    // 监听元素变化
    const resizeObserver = new ResizeObserver(resize)
    resizeObserver.observe(el)

    emit('ready', chartInstance)

    onUnmounted(() => {
        resizeObserver.unobserve(el)
        chartInstance.ClearChart()
    })
})
</script>