import { ImportCore } from "@cqsjjb/jjb-common-decorator/module";
import { theme as antdTheme, App, ConfigProvider } from "antd";
import language from "antd/locale/zh_CN";
import React from "react";

import { InjectContext } from "~/enumerate/context";

const ANT_PREFIX = process.env.app.antd?.["ant-prefix"] || "ant";

export default class Container extends React.Component {
  state = window?.base?.themeConfig || {
    algorithm: "defaultAlgorithm",
    borderRadius: 6,
    colorPrimary: "#0b6cff",
  };

  get token() {
    const { colorPrimary, borderRadius } = this.state;
    return {
      colorPrimary,
      borderRadius,
      fontFamily: "Microsoft YaHei, PingFang SC, sans-serif",
    };
  }

  get algorithm() {
    return antdTheme[this.state.algorithm] || antdTheme.defaultAlgorithm;
  }

  componentDidMount() {
    if (window.__IN_BASE__) {
      // eslint-disable-next-line react-web-api/no-leaked-event-listener
      window.base.addEventListener("EVENT_THEME_CONTROL", (e) => {
        const config = e.data;
        this.setState({ [config.field]: config.value });
      });
    }
  }

  render() {
    return (
      <ConfigProvider
        prefixCls={ANT_PREFIX}
        theme={{
          token: this.token,
          algorithm: this.algorithm,
        }}
        locale={language}
      >
        <App style={{ height: "100%" }}>
          <AppMiddle {...this.props} />
        </App>
      </ConfigProvider>
    );
  }
}

function AppMiddle(props) {
  return (
    <InjectContext.Provider value={App.useApp()}>
      {process.env.NODE_ENV === "development"
        ? props.children
        : (
            <Interceptor>
              {props.children}
            </Interceptor>
          )}
    </InjectContext.Provider>
  );
}

class Interceptor extends React.Component {
  state = {
    Component: undefined,
  };

  componentDidMount() {
    if (process.env.app.appKey) {
      ImportCore({
        name: "$",
        from: "https://cdn.cqjjb.cn/jcloud/use/plugin/b31c9840a57f11ef91cf7f3cabbb7484/latest",
      }).then(async (res) => {
        if (res.status) {
          this.setState({ Component: res.module?.PageCover });
        }
      });
    }
  }

  render() {
    const { Component } = this.state;
    return (Component && process.env.app.appKey && process.env.NODE_ENV === "development")
      ? (
          <Component appKey={process.env.app.appKey}>
            {this.props.children}
          </Component>
        )
      : this.props.children;
  }
}
