import { md5 } from 'js-md5';
import { ssoHost } from '@/utils/env';
import { LoginRes } from '@/api/interface';

export function post(url: string, params: Record<string, any>) {
  const temp = document.createElement('form');
  temp.action = url;
  temp.method = 'post';
  temp.style.display = 'none';
  Object.keys(params).forEach(key => {
    const opt = document.createElement('textarea');
    opt.name = key;
    opt.value = params[key];
    temp.appendChild(opt);
  });
  document.body.appendChild(temp);
  temp.submit();
  return temp;
}

export const ssoLogin = ({ username, password }: Record<string, any>) => {
  // 模拟表单提交
  const ssoUri = `${ssoHost}/api/blade-auth/oauth/form`;
  return post(ssoUri, {
    tenant_id: '000000',
    username,
    password: md5(password),
    client_id: 'isdp2',
    // 统一认证的地址
    sso_uri: `${ssoHost || window.location.origin}/api/blade-auth`,
    // 必须加/
    redirect_uri: `${window.location.origin}/`
  });
};

export const verify = ({ username, password }): Promise<LoginRes> => {
  return fetch('/api/user-center/verify', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ username, password: md5(password) })
  }).then(async (res) => {
    const data = await res.json();
    // 登录成功后设置用户状态
    if (data && res.status === 200) {
      localStorage.setItem('userStatus', 'login');
    }
    return data;
  });
};