<template>
    <vue3-echarts ref="echarts" :options="localOption" :canvas-id="canvasId" :style="style"/>
</template>

<script setup>
import {ref, computed, onActivated, onDeactivated, watch} from 'vue'
/* NOTE: 因为vue3-echarts在页面快速切换过程中渲染时会报错，用这个组件包装一下，加强容错性*/
import {createPropDefine} from "@/utils";
import {empty} from "@/uni_modules/uv-ui-tools/libs/function/test";
import {sleep} from "@/uni_modules/uv-ui-tools/libs/function";

const props = defineProps({
    option: createPropDefine(null, Object),
    canvasId: createPropDefine('mx-echarts'),
    style: createPropDefine({height: '240px'}, Object)
})

const localOption = ref({})
const echarts = ref(null)
const paused = ref(false)

const success = computed(() => echarts.value?.chart)

const syncOption = async () => {
    const option = props.option
    if (empty(option)) return

    const valid = () => {
        if (paused.value) return false
        // 渲染成功也不用管了，如果要更精细控制，这里也要考虑
        if (success.value && option == localOption.value) return false
        return true
    }

    if (!valid()) return
    await sleep(500)
    // 双重判定
    if (!valid()) return

    localOption.value = option
}

onActivated(() => {
    paused.value = false
    syncOption()
})
onDeactivated(() => {
    paused.value = true
})
// TODO：我们的业务场景一般都是一次性赋值，所以这里没有开启深度监听
// Cannot access 'syncOption' before initialization // watch.immediate只能放在定义之后
watch(() => props.option, () => syncOption(), {immediate: true})
</script>

<style scoped>

</style>