import { query, queryLogin } from '@/modules';
import { basename } from '@/modules/basename';
import { message } from '@/modules/message';
import { create } from 'zustand';

// 如果自己是在iframe中登录，需要调用这个方法
export const postLoginInIframe = (token: string) => {
  console.log('window.parent !== window', window.parent !== window);
  if (window.parent === window) {
    return;
  }
  // 获取父窗口的来源
  const parentOrigin = window.location.ancestorOrigins ? window.location.ancestorOrigins[0] : document.referrer;

  // 检查父窗口的来源是否合法
  const allowedOrigins = ['http://localhost', /^https?:\/\/(.+\.)?on-ai\.ai$/, /^https?:\/\/(.+\.)?xiongxiao\.me$/];

  let targetOrigin: string | null = null;

  // 根据来源动态选择 targetOrigin
  if (allowedOrigins.some((origin) => (typeof origin === 'string' ? parentOrigin.includes(origin) : origin.test(parentOrigin)))) {
    targetOrigin = parentOrigin; // 使用合法来源作为 targetOrigin
  }
  // 如果找到合法的 targetOrigin，则发送消息
  if (targetOrigin) {
    const message = { type: 'login-from-iframe', data: { token } };
    parent.postMessage(message, targetOrigin);
  } else {
    console.warn('Parent origin is not allowed:', parentOrigin);
  }
};

type LoginStore = {
  loading: boolean;
  setLoading: (loading: boolean) => void;
  formData: any;
  setFormData: (formData: any) => void;
  login: () => Promise<void>;
  register: () => Promise<void>;
  isLogin: boolean;
  setIsLogin: (isLogin: boolean) => void;
};
export const useLoginStore = create<LoginStore>((set, get) => {
  return {
    loading: false,
    setLoading: (loading) => set({ loading }),
    formData: {},
    setFormData: (formData) => set({ formData }),
    login: async () => {
      const { formData } = get();
      const { username, password } = formData;
      if (!username || !password) {
        message.error('Please input username and password');
        return;
      }
      set({ loading: true });
      const res = await queryLogin.login({ username, password });
      if (res.code === 200) {
        message.success('Success');
        set({ isLogin: true });
        await new Promise((resolve) => setTimeout(resolve, 1000));
        if (window.parent !== window) {
          postLoginInIframe(res.data?.accessToken || '');
          await new Promise((resolve) => setTimeout(resolve, 3000));
        }
        const search = new URLSearchParams(window.location.search);
        const redirect = search.get('redirect');
        if (redirect) {
          window.location.href = redirect;
        } else {
          window.location.href = basename ? basename + '/' : '/';
        }
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    register: async () => {
      set({ loading: true });
      const res = await query.post({ path: 'user', key: 'register' });
      if (res.code === 200) {
        message.success('Success');
        // 跳到某一个页面
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    isLogin: false,
    setIsLogin: (isLogin) => set({ isLogin }),
  };
});
