import React, { useState, useRef, useLayoutEffect } from 'react';
import Taro from '@tarojs/taro';
import { View, Canvas } from '@tarojs/components';
import uChartsClass from '../lib/u-charts-original';
import type { ChartsConfig, TouchEvent } from '../types/u-charts-original';
import type { ExtendedCanvasContext } from '../types';

/**
 * RingChartFCExample 组件
 *
 * FC 示例组件（环形图版本）
 * 使用原始 u-charts.js + Canvas 2D API
 *
 * 用于与 BaseChartOriginal2D 进行对比调试
 */
interface RingChartFCExampleProps {
  /** Canvas 元素的 ID，必须唯一 */
  canvasId?: string;
  /** 图表宽度（像素），默认为屏幕宽度 */
  width?: number;
  /** 图表高度（像素），默认根据宽高比计算 */
  height?: number;
}

function RingChartFCComponent(props: RingChartFCExampleProps) {
  const { canvasId = 'RingChartFCExample', width = 750, height = 500 } = props;

  const [cWidth, setCWidth] = useState(750);
  const [cHeight, setCHeight] = useState(500);
  const [pixelRatio, setPixelRatio] = useState(1);

  // 使用 ref 存储图表实例
  const uChartsInstanceRef = useRef<Record<string, any>>({});

  const drawCharts = (id: string, data: any) => {
    const query = Taro.createSelectorQuery();
    query.select('#' + id).fields({ node: true, size: true }).exec(res => {
      if (res[0]) {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d') as ExtendedCanvasContext;
        const chart = new uChartsClass({
          type: "ring",
          context: ctx,
          width: canvas.width,
          height: canvas.height,
          series: data.series,
          animation: true,
          background: "#FFFFFF",
          color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
          padding: [5,5,5,5],
          enableScroll: false,
          dataLabel: true,
          legend: {
            show: true,
            position: "right",
            lineHeight: 25
          },
          title: {
            name: "在职状态",
            fontSize: 15,
            color: "#666666"
          },
          subtitle: {
            name: "70%",
            fontSize: 25,
            color: "#7cb5ec"
          },
          extra: {
            ring: {
              ringWidth: 60,
              activeOpacity: 0.5,
              activeRadius: 10,
              offsetAngle: 0,
              labelWidth: 15,
              border: false,
              borderWidth: 3,
              borderColor: "#FFFFFF"
            }
          }
        } as ChartsConfig);
        uChartsInstanceRef.current[id] = chart;
        const series = data.series;
        console.log('[RingChartFCExample] 图表初始化完成:', id, {
          cWidth, cHeight,
          canvasWidth: canvas.width,
          canvasHeight: canvas.height,
          seriesLength: series.length,
          series,
        });
      } else {
        console.error("[RingChartFCExample]: 未获取到 context");
      }
    });
  }

  const getServerData = () => {
    //模拟从服务器获取数据时的延时
    setTimeout(() => {
      //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
      let res = {
        series: [
          {
            data: [{"name":"在职","value":24},{"name":"离职","value":8},{"name":"试用期","value":5},{"name":"停薪留职","value":2}]
          }
        ]
      };
      drawCharts(canvasId, res);
    }, 500);
  }

  const tap = (e: any) => {
    uChartsInstanceRef.current[e.currentTarget.id]?.touchLegend(e);
    uChartsInstanceRef.current[e.currentTarget.id]?.showToolTip(e);
  }

  useLayoutEffect(() => {
    console.debug('[RingChartFCExample] useLayoutEffect')
    const sysInfo = Taro.getSystemInfoSync();
    const pr = sysInfo.pixelRatio;
    //这里的第一个 750 对应 css .charts 的 width
    const cw = width / 750 * sysInfo.windowWidth;
    //这里的 500 对应 css .charts 的 height
    const ch = height / 750 * sysInfo.windowWidth;
    setCWidth(cw);
    setCHeight(ch);
    setPixelRatio(pr);

    // 直接在这里获取数据
    getServerData();
  }, [width, height, canvasId]);

  const canvasProps = { style: { width: cWidth, height: cHeight } };
  return (
    <View>
      <Canvas
        {...canvasProps}
        canvas-id={canvasId}
        id={canvasId}
        type="2d"
        className="charts"
        onTouchEnd={tap}
      />
    </View>
  );
}

// 默认导出
export default RingChartFCComponent;

// 命名导出，保持向后兼容
export const RingChartFCExample = RingChartFCComponent;
