import request from '@/utils/request'
import {getDataByKey} from '@/api/system';

// 登录
export function login(data) {
  return request({
    url: '/login',
    method: 'post',
    data
  })
};

// 生成验证码 
export function getCode() {
  return request({
    url: "/captchaImage",
    method: 'get'
  })
};

// 获取 用户信息
export function getUserInfo() {
  return request({
    url: '/getInfo',
    method: 'get'
  })
};

// 获取验证码 图片
export function getCodeimg() {
  return request({
    url: '/captchaImage',
    method: 'get'
  })
};

export async function loginAndUserinfo(data) {
  const transition = (fn, res) => {
    if (res == null) [res, fn] = [fn];
    if (res.ResultCode !== 0) throw res.ResultInfo;
    return typeof fn === 'function' ? fn(res.Data, res.ResultInfo) : res.Data;
  };
  const token = await login(data).then(transition.bind(null, (data) => data.token));
  localStorage.setItem('token', token);

  const userInfo = await getUserInfo().then(transition);
  const defaultHomePage = await getDataByKey({key: 'defaultHomePage', organizationid: userInfo.organizationid});

  return {token, userInfo, defaultHomePage };
}