import Taro from "@tarojs/taro";
import { Component } from "react";
import { Provider } from "mobx-react";
import { compose, initial } from "@dage/service";

import store from "./store";
import { TOKEN_KEY } from "./utils";
import { $fetch } from "./utils/fetch";

import "./app.scss";
import "./taro-ui.scss";

declare global {
  interface DageRequestMeta {
    showLoading?: boolean;
    showError?: boolean;
  }
}

initial({
  // @ts-ignore
  fetch: $fetch,
  baseURL: process.env.TARO_APP_API as string,
  interceptor: compose(
    (request, next) => {
      const token = Taro.getStorageSync(TOKEN_KEY);
      if (token) {
        request.headers["token"] = token;
      }
      return next();
    },
    async (request, next) => {
      const { showLoading, showError } = request.meta;
      try {
        if (showLoading) {
          Taro.showLoading({
            title: "加载中...",
          });
        }

        const response = await next();

        if (showLoading && showError) {
          Taro.hideLoading();
        }

        if (response.code !== 0) {
          // @ts-ignore
          const message = response.msg ?? "系统出差中";
          response.errorMessage = message;
          if (showError) {
            Taro.showToast({
              title: message,
              icon: "none",
              duration: 2000,
            });
          }
        }

        return response;
      } finally {
        if (showLoading && !showError) {
          Taro.hideLoading();
        }
      }
    }
  ),
});

class App extends Component {
  componentDidMount() {}

  componentDidShow() {}

  componentDidHide() {}

  componentDidCatchError() {}

  // this.props.children 就是要渲染的页面
  render() {
    return <Provider store={store}>{this.props.children}</Provider>;
  }
}

export default App;
