import { jsx } from 'react/jsx-runtime';
import { Canvas } from '@tarojs/components';
import Taro, { useReady } from '@tarojs/taro';
import { useState, useRef } from 'react';
import WxCanvas from './wx-canvas.js';

let ctx;
/**
 * @public
 */
var EChartsCanvas = (props) => {
    const { echarts, ec, canvasId = 'ec-canvas', forceUseOldCanvas = false } = props;
    const [useNewCanvas, setUseNewCanvas] = useState(true);
    const chartRef = useRef();
    const canvasNodeRef = useRef();
    const init = (callback) => {
        const version = Taro.getSystemInfoSync().SDKVersion;
        const canUseNewCanvas = compareVersion(version, '2.9.0') >= 0;
        const isUseNewCanvas = canUseNewCanvas && !forceUseOldCanvas;
        setUseNewCanvas(isUseNewCanvas);
        if (forceUseOldCanvas && canUseNewCanvas) {
            console.warn('开发者强制使用旧canvas,建议关闭');
        }
        if (isUseNewCanvas) {
            // console.log('微信基础库版本大于2.9.0，开始使用<canvas type="2d"/>');
            // 2.9.0 可以使用 <canvas type="2d"></canvas>
            Taro.nextTick(() => {
                initByNewWay(callback);
            });
        }
        else {
            const isValid = compareVersion(version, '1.9.91') >= 0;
            if (!isValid) {
                console.error('微信基础库版本过低，需大于等于 1.9.91。' +
                    '参见：https://github.com/ecomfe/echarts-for-weixin' +
                    '#%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC%E8%A6%81%E6%B1%82');
            }
            else {
                console.warn('建议将微信基础库调整大于等于2.9.0版本。升级后绘图将有更好性能');
                Taro.nextTick(() => {
                    initByOldWay(callback);
                });
            }
        }
    };
    useReady(() => {
        // Disable prograssive because drawImage doesn't support DOM as parameter
        // See https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.drawImage.html
        echarts.registerPreprocessor((option) => {
            if (option && option.series) {
                if (option.series.length > 0) {
                    option.series.forEach((series) => {
                        series.progressive = 0;
                    });
                }
                else if (typeof option.series === 'object') {
                    option.series.progressive = 0;
                }
            }
        });
        if (!ec) {
            console.warn('组件需绑定 ec 变量，例：<ec-canvas id="mychart-dom-bar" ' +
                'canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>');
            return;
        }
        if (!ec.lazyLoad) {
            init();
        }
    });
    function initByNewWay(callback) {
        // version >= 2.9.0：使用新的方式初始化
        const query = Taro.createSelectorQuery();
        query
            .select('.ec-canvas')
            .fields({ node: true, size: true })
            .exec((res) => {
            var _a;
            const canvasNode = (_a = res[0]) === null || _a === void 0 ? void 0 : _a.node;
            canvasNodeRef.current = canvasNode;
            const canvasDpr = Taro.getSystemInfoSync().pixelRatio;
            const canvasWidth = res[0].width;
            const canvasHeight = res[0].height;
            const canvasCtx = canvasNode.getContext('2d');
            const canvas = new WxCanvas(canvasCtx, canvasId, true, canvasNode);
            echarts.setCanvasCreator(() => {
                return canvas;
            });
            if (typeof callback === 'function') {
                chartRef.current = callback(canvas, canvasWidth, canvasHeight, canvasDpr);
            }
            else if (ec && typeof ec.onInit === 'function') {
                chartRef.current = ec.onInit(canvas, canvasWidth, canvasHeight, canvasDpr);
            }
            // else {
            //   this.triggerEvent('init', {
            //     canvas,
            //     width: canvasWidth,
            //     height: canvasHeight,
            //     dpr: canvasDpr,
            //   });
            // }
        });
    }
    function initByOldWay(callback) {
        // 1.9.91 <= version < 2.9.0：原来的方式初始化
        ctx = Taro.createCanvasContext(canvasId);
        const canvas = new WxCanvas(ctx, canvasId, false);
        echarts.setCanvasCreator(() => {
            return canvas;
        });
        // const canvasDpr = wx.getSystemInfoSync().pixelRatio // 微信旧的canvas不能传入dpr
        const canvasDpr = 1;
        const query = Taro.createSelectorQuery();
        query
            .select('.ec-canvas')
            .boundingClientRect((res) => {
            if (typeof callback === 'function') {
                chartRef.current = callback(canvas, res.width, res.height, canvasDpr);
            }
            else if (ec && typeof ec.onInit === 'function') {
                chartRef.current = ec.onInit(canvas, res.width, res.height, canvasDpr);
            }
            // else {
            //   this.triggerEvent('init', {
            //     canvas,
            //     width: res.width,
            //     height: res.height,
            //     canvasDpr, // 增加了dpr，可方便外面echarts.init
            //   });
            // }
        })
            .exec();
    }
    const handleOnTouchStart = (e) => {
        if (chartRef.current && e.touches.length > 0) {
            const touch = e.touches[0];
            const { handler } = chartRef.current.getZr();
            handler.dispatch('mousedown', {
                zrX: touch.x,
                zrY: touch.y,
                preventDefault: () => { },
                stopImmediatePropagation: () => { },
                stopPropagation: () => { },
            });
            handler.dispatch('mousemove', {
                zrX: touch.x,
                zrY: touch.y,
                preventDefault: () => { },
                stopImmediatePropagation: () => { },
                stopPropagation: () => { },
            });
            handler.processGesture(wrapTouch(e), 'start');
        }
    };
    const handleOnTouchMove = (e) => {
        if (chartRef.current && e.touches.length > 0) {
            const touch = e.touches[0];
            const { handler } = chartRef.current.getZr();
            handler.dispatch('mousemove', {
                zrX: touch.x,
                zrY: touch.y,
                preventDefault: () => { },
                stopImmediatePropagation: () => { },
                stopPropagation: () => { },
            });
            handler.processGesture(wrapTouch(e), 'change');
        }
    };
    const handleOnTouchEnd = (e) => {
        if (chartRef.current) {
            const touch = e.changedTouches ? e.changedTouches[0] : { x: 0, y: 0 };
            const { handler } = chartRef.current.getZr();
            handler.dispatch('mouseup', {
                zrX: touch.x,
                zrY: touch.y,
                preventDefault: () => { },
                stopImmediatePropagation: () => { },
                stopPropagation: () => { },
            });
            handler.dispatch('click', {
                zrX: touch.x,
                zrY: touch.y,
                preventDefault: () => { },
                stopImmediatePropagation: () => { },
                stopPropagation: () => { },
            });
            handler.processGesture(wrapTouch(e), 'end');
        }
    };
    return (jsx(Canvas, { type: useNewCanvas ? '2d' : 'webgl', className: "ec-canvas", style: { width: '100%', height: '100%' }, canvasId: canvasId, onTouchStart: ec.disableTouch ? undefined : handleOnTouchStart, onTouchMove: ec.disableTouch ? undefined : handleOnTouchMove, onTouchEnd: ec.disableTouch ? undefined : handleOnTouchEnd }));
};
function compareVersion(v1, v2) {
    v1 = v1.split('.');
    v2 = v2.split('.');
    const len = Math.max(v1.length, v2.length);
    while (v1.length < len) {
        v1.push('0');
    }
    while (v2.length < len) {
        v2.push('0');
    }
    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i], 10);
        const num2 = parseInt(v2[i], 10);
        if (num1 > num2) {
            return 1;
        }
        else if (num1 < num2) {
            return -1;
        }
    }
    return 0;
}
function wrapTouch(event) {
    for (let i = 0; i < event.touches.length; ++i) {
        const touch = event.touches[i];
        touch.offsetX = touch.x;
        touch.offsetY = touch.y;
    }
    return event;
}

export { EChartsCanvas as default };
//# sourceMappingURL=index.js.map
