<!--
    tips:属性：1.moduleParam:传id 以及宽高的对象 2.optionData:传渲染数据
 -->
<template>
  <view class="content">
    <!-- #ifdef APP-PLUS || H5 -->
    <view
      @click="echarts.onClick"
      :style="{ width: moduleParam.width, height: moduleParam.height }"
      :prop="optionData"
      :moduleParamProp="moduleParam"
      :change:moduleParamProp="echarts.moduleParamUp"
      :change:prop="echarts.updateEcharts"
      :id="moduleParam.id"
      class="echarts"
    ></view>
    <!-- #endif -->
    <!-- #ifndef APP-PLUS || H5 -->
    <view>非 APP、H5 环境不支持</view>
    <!-- #endif -->
  </view>
</template>
<script>
export default {
  data() {
    return {};
  },
  props: {
    moduleParam: {
      type: Object,
      default: () => {
        return {
          id: "myCharts",
          width: "100%",
          height: "374rpx",
        };
      },
    },
    optionData: {
      type: Object,
      default: () => {},
    },
  },
  methods: {
    onViewClick(options) {
      this.$emit("getClickData", options);
    },
  },
};
</script>
<script module="echarts" lang="renderjs">
let myChart
export default {
    data() {
        return {
            clickData: null
        }
    },
    mounted() {
        if (typeof window.echarts === 'function') {
            this.initEcharts()
        } else {
            // 动态引入较大类库避免影响页面展示
            const script = document.createElement('script')
            // view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
            script.src = 'static/js/echarts.min.js'
            script.onload = this.initEcharts.bind(this)
            document.head.appendChild(script)
        }
    },
    methods: {
        initEcharts() {
            myChart = echarts.init(document.getElementById(this.moduleParam.id), "echartsConfig")
            // 观测更新的数据在 view 层可以直接访问到
            myChart.setOption(this.optionData)
            // 点击传参
            myChart.on('click', params => {
                this.clickData = params
            })
        },
        updateEcharts(newValue, oldValue, ownerInstance, instance) {
            // 监听 service 层数据变更
            try {
                myChart = echarts.init(document.getElementById(this.moduleParam.id), "echartsConfig")
                myChart.setOption(newValue)
            } catch (error) {}
        },
        moduleParamUp(newvalue, oldvalue) {},
        onClick(event, ownerInstance) {
            ownerInstance.callMethod('onViewClick', {
                value: this.clickData.value,
                name: this.clickData.name,
                dataIndex: this.clickData.dataIndex,
                seriesName: this.clickData.seriesName
            })
        }
    }
}
</script>
<style scoped>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
