import Taro, { request } from '@tarojs/taro';
import store from '../store/index';
import {
  BASE_SERVER_URL,
  CUSTOMER_SERVER_URL,
  SCHOOL_MAIN_URL,
  LogoutCode,
  SuccessCode,
  OLD_BASE_SERVER_URL,
  SHOWER_APP_URL,
  SMPRO_URL,
  GX_URL,
} from '../constants/index';

export type ResponseDataEntity<T> = {
  code: number;
  msg: string;
  data: T;
  [propName: string]: any;
};

type ResponseEntity = {
  data: ResponseDataEntity<any>;
  [propName: string]: any;
};

const createFetch = (basePath: string) => {
  return (entity: request.Param) => {
    const token = store.getState().userinfo.token;
    return Taro.request({
      ...entity,
      header: token
        ? {
            token: token,
            reqSource: 'wxmini',
          }
        : {
            reqSource: 'wxmini',
          },
      url: basePath + entity.url,
    }).then(
      ({ data }: ResponseEntity): ResponseDataEntity<any> => {
        if (data.code === SuccessCode) {
          return data;
        }
        if (data.code === LogoutCode) {
          Taro.redirectTo({
            url: '/pages/Login/Login',
          });
          throw data;
        }
        Taro.showToast({
          title: data.msg || '网络错误',
          icon: 'none',
        });
        throw data;
      },
    );
  };
};

export const baseFetch = createFetch(BASE_SERVER_URL);
export const oldBaseFetch = createFetch(OLD_BASE_SERVER_URL);
export const customerFetch = createFetch(CUSTOMER_SERVER_URL);
export const schoolMainFetch = createFetch(SCHOOL_MAIN_URL);
export const showerFetch = createFetch(SHOWER_APP_URL);
export const smaproFetch = createFetch(SMPRO_URL);
export const gxFetch = createFetch(GX_URL);

export default createFetch;
