import { login as _login } from './wx/open-api'
import { Get } from './request/method';

const TOKEN: Pick<WechatMiniprogram.SetStorageOption, 'key' | 'data' | 'encrypt'> = {
  key: 'token',
  encrypt: true,
  data: '',
};

export function token() {
  return TOKEN.data || wx.getStorageSync(TOKEN.key)
}

export async function login(force?: boolean) {
  const _token = force ? '' : await wx.checkSession().then(() => token(), () => '');
  if (_token) return _token;
  const show = setTimeout(() => wx.showLoading({ title: '登录中' }), 300);
  try {
    const { code } = await _login();

    TOKEN.data = await Get<string, { access_token: string }>(`/authManage/login`, {
      params: { code },
      transform({ data }) {
        return data.access_token
      },
      shareRequest: !force,
      meta: { ignoreToken: true }
    });

    wx.setStorageSync(TOKEN.key, TOKEN.data);
    return TOKEN.data;
  } catch (error) {
    throw error
  } finally {
    clearTimeout(show);
    wx.hideLoading();
  }
}



