import { defineAppConfig, history, defineDataLoader } from "ice";
import { defineAuthConfig } from "@ice/plugin-auth/types";
import { defineStoreConfig } from "@ice/plugin-store/types";
import { defineRequestConfig } from "@ice/plugin-request/types";
import { registerValidateRules } from "@formily/core";
import { Button, Result } from "antd";
import { proxyApi } from "./apis";
import { defineLoginStateConfig } from "../plugins/plugin-login-state/type";

registerValidateRules({
  phoneWhenWrite(value, _rule, ctx) {
    const field = ctx.field;
    // 在只读模式
    if (
      field.readPretty ||
      !value ||
      /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)
    ) {
      return "";
    }
    return "手机号码格式不正确";
  },
  emailWhenWrite(value, _rule, ctx) {
    const field = ctx.field;
    if (
      field.readPretty ||
      !value ||
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
        value
      )
    ) {
      return "";
    }
    return "邮箱格式不正确";
  },
});

// App config, see https://v3.ice.work/docs/guide/basic/app
export default defineAppConfig(() => ({
  app: {
    rootId: "chuntianxiaozhu",
  },
  router: {
    type: "hash",
  },
}));

export const authConfig = defineAuthConfig(async (appData) => {
  const { userInfo } = appData;

  if (!userInfo) {
    history?.push(`/login?redirect=${window.location.pathname}`);
  }

  const auth = {};

  userInfo?.roles?.forEach((authName) => {
    auth[authName] = true;
  });

  return {
    initialAuth: auth,
    NoAuthFallback: () => {
      return (
        <Result
          status="403"
          title="403"
          subTitle="当前页面无权访问"
          extra={
            <Button
              type="primary"
              onClick={() => {
                history?.replace("/settlein");
              }}
            >
              入驻春天小猪设计者
            </Button>
          }
        />
      );
    },
  };
});

export const loginStateConfig = defineLoginStateConfig(async (appData) => {
  const { userInfo } = appData;

  if (!userInfo) {
    history?.push(`/login?redirect=${window.location.pathname}`);
  }
  return {
    initialLoginState: !!userInfo,
    NoLoginFallback: () => {
      return (
        <Result
          status="403"
          title="403"
          subTitle="您还未登录,无法访问当前页面"
          extra={
            <Button
              type="primary"
              onClick={() => {
                history?.replace(`/login?redirect=${window.location.pathname}`);
              }}
            >
              去登录
            </Button>
          }
        />
      );
    },
  };
});

export const storeConfig = defineStoreConfig(async (appData) => {
  const { userInfo = {} } = appData;
  return {
    initialStates: {
      user: {
        currentUser: userInfo,
      },
    },
  };
});

export const request = defineRequestConfig(() => ({
  baseURL: "/api",
}));

export const dataLoader = defineDataLoader(async () => {
  const userInfo = await getUserInfo();
  return {
    userInfo,
  };
});

async function getUserInfo() {
  try {
    const userInfo = await proxyApi.auth.queryUserInfo();
    userInfo.roles = userInfo.roles?.split(",") || [];
    return userInfo;
  } catch (error) {
    return;
  }
}
