/* eslint-disable new-cap */
import type { ChartingLibraryWidgetOptions, IChartingLibraryWidget } from "#/charting_library";
import type { ResolutionString } from "#/datafeed-api";
import type { CSSProperties } from "vue";
import { mergeWith } from "lodash-es";
import { RWADatafeed } from "./datafeed";

const { VITE_TRADINGVIEW_LIBRARY_URL, VITE_API_URL } = useEnv();

const datafeed = new RWADatafeed(`${VITE_API_URL}/api/udf`);

const defaultOptions = {
  container: "tradingview_chart_container",
  locale: "zh",
  library_path: `${VITE_TRADINGVIEW_LIBRARY_URL}/charting_library/`,
  datafeed,
  interval: "1D" as ResolutionString,
  symbol: "",
  debug: true,
  autosize: true,
  // 禁用移动端不友好的功能
  disabled_features: [
    "left_toolbar", // 隐藏左侧绘图工具栏
    "timeframes_toolbar", // 隐藏底部时间框架工具栏
    "volume_force_overlay", // 禁用成交量覆盖在价格图表上
    // "header_widget", // 禁用顶部工具栏
    "header_compare", // 禁用比较功能
    "header_symbol_search", // 禁用符号搜索
    // "header_fullscreen_button", // 禁用全屏按钮
    // "header_settings", // 禁用设置按钮
    "header_screenshot", // 禁用截图功能
    "header_undo_redo", // 禁用撤销/重做按钮
    "header_saveload", // 禁用保存/加载按钮
    "control_bar", // 禁用底部控制栏
    "edit_buttons_in_legend", // 禁用图例中的编辑按钮
    "border_around_the_chart", // 移除图表边框
    "main_series_scale_menu", // 禁用主序列比例菜单
    "display_market_status", // 禁用市场状态显示
    // "create_volume_indicator_by_default", // 默认不创建成交量指标
    // "go_to_date", // 禁用跳转到日期功能
    "pane_context_menu", // 禁用窗格右键菜单
    // "legend_context_menu", // 禁用图例右键菜单
    // "legend_inplace_edit", // 禁用图例内联编辑
    // "legend_widget", // 禁用图例小部件
  ],
  // 启用移动端友好的功能
  enabled_features: [
    "show_zoom_and_move_buttons_on_touch", // 在触摸设备上显示缩放和移动按钮
    "adaptive_logo", // 在小屏幕设备上隐藏 TradingView logo
    "hide_left_toolbar_by_default", // 默认隐藏左侧工具栏
    "items_favoriting", // 启用收藏功能
  ],
  // 图表样式配置
  overrides: {
    "paneProperties.backgroundType": "solid",
    "paneProperties.background": "#000000",
    "paneProperties.vertGridProperties.color": "transparent", // 隐藏垂直网格线
    "mainSeriesProperties.candleStyle.upColor": "#0ecb81", // 涨（绿色）
    "mainSeriesProperties.candleStyle.downColor": "#f6465d", // 跌（红色）
    "mainSeriesProperties.candleStyle.borderUpColor": "#0ecb81",
    "mainSeriesProperties.candleStyle.borderDownColor": "#f6465d",
    "mainSeriesProperties.candleStyle.wickUpColor": "#0ecb81",
    "mainSeriesProperties.candleStyle.wickDownColor": "#f6465d",
  },
  // 时间刻度配置
  time_scale: {
    min_bar_spacing: 6,
  },
} satisfies ChartingLibraryWidgetOptions;

export const TradingViewChart = defineComponent({
  name: "TradingViewChart",
  props: {
    symbol: {
      type: String,
      required: true,
    },
    width: {
      type: [String, Number] as PropType<string | number>,
      required: false,
    },
    height: {
      type: [String, Number] as PropType<string | number>,
      required: false,
    },
    options: {
      type: Object as PropType<Partial<ChartingLibraryWidgetOptions>>,
      required: false,
    },
  },
  setup(props) {
    const el = ref<HTMLDivElement | null>(null);
    const { isDark } = useTheme();
    const widget = ref<IChartingLibraryWidget | null>(null);

    function applyThemeOverrides(isDarkTheme: boolean) {
      if (!widget.value)
        return;
      widget.value?.applyOverrides({
        "paneProperties.backgroundType": "solid",
        "paneProperties.background": isDarkTheme ? "#000000" : "#FFFFFF",

        "paneProperties.horzGridProperties.color": isDarkTheme ? "#222831" : "#e6e6e6",
        "scalesProperties.textColor": isDarkTheme ? "#FFFFFF" : "#131722",
      });
    }

    const opts = mergeWith({}, defaultOptions, props.options);
    opts.symbol = props.symbol;

    const styles = computed(() => {
      const style: CSSProperties = {};
      if (props.width !== undefined)
        style.width = typeof props.width === "number" ? `${props.width}px` : props.width;
      if (props.height !== undefined)
        style.height = typeof props.height === "number" ? `${props.height}px` : props.height;
      style["--themed-color-text-primary"] = isDark.value ? "#FFFFFF" : "#000000";
      return style;
    });

    onMounted(() => {
      widget.value = new TradingView.widget({
        ...opts,
        theme: isDark.value ? "dark" : "light",
        container: el.value!,
      });

      widget.value.onChartReady(() => {
        console.log("[TradingView]: Chart is ready");
        applyThemeOverrides(isDark.value);
      });
    });

    // 监听主题变化，动态更新图表主题
    watch(isDark, (newValue) => {
      if (!widget.value)
        return;
      widget.value.changeTheme(newValue ? "dark" : "light");
      useTimeoutFn(() => {
        applyThemeOverrides(newValue);
      }, 0);
    });

    return () => h("div", { ref: el, class: "w-full", style: styles.value });
  },
});
