/**
 * 全局http工具集
 * YangXB 2021.11.24
 * */
import { base, http } from './config';
import { IIsLogin, Subscribe } from './subscribe';
import { getStorage, isArray, setStorage, toArray, toastError } from './util';
/**
 * 请求
 */
const request = (url: string, options: any, config = { showLoading: true, showError: true }) => {
  // 获取缓存cookie
  const header: any = { ...http.header };
  const cookie = getStorage(base.cookieKey);

  if (cookie && !header['Cookie']) {
    header['Cookie'] = cookie;
  }
  if (options['content-type']) {
    header['content-type'] = options['content-type'];
  }

  return new Promise((resolve, reject) => {
    if (config.showLoading != false) {
      wx.showLoading({ title: '加载中' });
    }

    url = `${url}`.startsWith('http') ? url : urlAddBaseUrl(url);
    wx.request({
      url: url,
      method: options.method,
      data: options.data,
      header,
      success(request: any) {
        if (config.showLoading != false) {
          wx.hideLoading();
        }
        // 写入缓存
        if (!cookie) {
          setStorage(base.cookieKey, request.header['Set-Cookie']);
        }

        if (request.data?.err_code === 0) {
          //
          resolve(request.data);
        } else {
          if (config.showError != false) {
            wx.showToast({ title: request.data.err_msg, icon: 'none' });
          }
          if (request.data.err_code == 110000) {
            Subscribe.set<IIsLogin>('isLogin', false);

            // const currentPage = getCurrentPage();
            // console.log(currentPage);
            // if (
            //   !['pages/index/index', 'pages/processEntry/processEntry', 'pages/my/my'].includes(
            //     currentPage.route,
            //   )
            // ) {
            // goIndexPage();
            // }
          }
          reject(request.data);
        }
      },
      fail(error: any) {
        if (config.showLoading != false) {
          wx.hideLoading();
        }
        reject({ err_code: 44444, err_msg: error.data });
      },
    });
  });
};

// 封装get方法
export const get = (url: string, data = {}, config?: any) => {
  return request(url, { method: 'GET', data }, config);
};

// 封装post方法
export const post = (url: string, data = {}, config?: any) => {
  return request(url, { method: 'POST', data }, config);
};

export const wxLogin = (config?: any) => {
  wx.login({
    success: (res) => {
      post('Applet/code2Sess', { code: res.code, name: 'ch' }, config)
        .then((res: any) => {
          // 记录sessionKey
          setStorage('session', {
            openid: res.openid,
            unionid: res.unionid,
            time: Date.now() + 1000 * 3600 * 24, // 缓存一天过期
          });
        })
        .catch((err: any) => {
          toastError('服务失败:' + err.err_code);
        });
    },
  });
};

// 检验微信前端登录状态
export const checkSession = () => {
  wx.checkSession({
    // 没有过期
    success: () => {
      // const session = wx.getStorageSync("session");
      // console.log("checkSession生效", session);
      // // 没有缓存，或者缓存已过期
      // if (!session) {
      //   console.log("session缓存已不存在");
      //   wxLogin();
      // } else {
      //   const time = session.time || 0;
      //   if (Date.now() > time) {
      //     console.log("session缓存已过期");
      //     wxLogin();
      //   }
      // }
    },
    fail: () => {
      console.log('checkSession失效');
      // 已过期，重新登录获取session_key
      wxLogin();
    },
  });
};

const getUsersConfigList = () => {
  post('ErpConfig/ErpConfigList').then((res: any) => {
    toArray(res?.data?.list).forEach((el) => {
      wx.setStorageSync(el.config_type_en, el.config_value);
    });
  });
};

export const loginStatus = () => {
  return new Promise((resolve, reject) => {
    post('Applet/loginStatus', {}, { showLoading: false })
      .then((res: any) => {
        setStorage('user_info', res.user_info);
        setStorage('user_id', res.user_info?.user_id);
        setStorage('company_info', res.company_info);
        setStorage('auth_info', res.auth_info);
        setStorage('session_id', res.session_id);
        getUsersConfigList();
        Subscribe.set<IIsLogin>('isLogin', true);
        resolve(res);
      })
      .catch((err: any) => {
        login('', '', 4)
          .then((res: any) => {
            if (isArray(res.data)) {
              post('Applet/loginOut').then(() => {
                checkSesskey({ showLoading: false, showError: false })
                  .then(() => {
                    Subscribe.set<IIsLogin>('isLogin', false);
                  })
                  .catch((err) => {
                    console.log('checkSesskey', err);
                  });
              });
              reject(res);
            } else {
              resolve(res);
            }
          })
          .catch(() => {
            reject(err);
          });
      });
  });
};

export const loginStatusPage = (that: WechatMiniprogram.Page.Instance<any, any>) => {
  that.setData({ loading: true });
  return new Promise<void>((resolve, reject) => {
    loginStatus()
      .then(() => {
        that.setData({ isLogin: true, loading: false });
        that?.init?.();
        resolve();
      })
      .catch((err) => {
        that.setData({ isLogin: false, loading: false });
        reject(err);
        console.log('调用登录状态请求失败', err);
      });
  });
};

/**
 * 页面初始化
 */
export const onPageLoadInitAuth = (
  that: WechatMiniprogram.Page.Instance<any, any>,
  initFun: () => Promise<void>,
) => {
  if (typeof initFun == 'function') {
    that.setData({ loading: true });
    initFun()
      .then((_res) => {
        // console.log('onPageLoadInitAuth', res);
        Subscribe.set<IIsLogin>('isLogin', true);
        that.setData({ isLogin: true, loading: false });
        that.init?.();
      })
      .catch((_res) => {
        // console.log('onPageLoadInitAuth catch', res);
        that.setData({ isLogin: false, loading: false });
      });
  }
};

/**
 *
 * @param {*} config  { showLoading: true, showError: true }
 */
export const checkSesskey = (config?: any) => {
  return new Promise<any>((resolve, reject) => {
    post('Applet/checkSesskey', {}, config)
      .then((res: any) => {
        resolve(res);
      })
      .catch((err: any) => {
        wxLogin(config);
        reject(err);
      });
  });
};

// 后端登录
export const login = (encryptedData: any, iv: any, type?: any, company_id?: any) => {
  return new Promise<any>((resolve, reject) => {
    const data: any = { type: 2, encryptedData, iv };

    if (company_id) {
      data.companyID = company_id;
    }

    post('Applet/login', type == 4 ? { type } : data)
      .then((res: any) => {
        if (isArray(res.data)) {
          resolve(res);
        } else {
          setStorage('user_info', res.user_info);
          setStorage('user_id', res.user_info?.user_id);
          setStorage('company_info', res.companys_info);
          setStorage('auth_info', res.auth_info);
          loginStatus();
          resolve(res);
        }
      })
      .catch((err: any) => {
        // 签名失败，重新登录
        // if (err.err_code == 41444) {
        // wxLogin();
        // showModal("登录结果", "服务器开小差了，请重试");
        // } else {
        // showModal("登录结果", err.err_msg);
        // }
        // wx.removeStorageSync("loginExp");
        if (type == 4) {
          checkSesskey()
            .then(() => {})
            .catch(() => {});
          reject(err);
        } else {
          reject(err);
        }
      });
  });
};

export const makeURL = (url: string, redirect = false, openID = false) => {
  return (
    base.apiHost +
    (redirect ? 'applet-wv?url=' : '') +
    encodeURIComponent(url + (openID ? '?openID=' + wx.getStorageSync('session')['openid'] : '')) +
    (redirect ? '&' : '?') +
    'cookie=' +
    encodeURI(wx.getStorageSync(base.cookieKey))
  );
};

export const urlAddBaseUrl = (url: string) => {
  if (typeof url == 'string') {
    if (url.startsWith('/')) {
      url = url.substring(1);
    }
  }
  return base.apiHost + url;
};

export const urlAddWebViewBaseUrl = (url: string) => {
  if (typeof url == 'string') {
    if (url.startsWith('/')) {
      url = url.substring(1);
    }
  }
  return base.webViewBaseUrl + url;
};

/** formData请求 */
export const formDataRequest = (url: string, formData: any, config?: any) => {
  let data = formData.getData();
  return request(
    url,
    {
      method: 'POST',
      data: data.buffer,
      'content-type': data.contentType,
    },
    config,
  );
};
