import Taro, { request } from "@tarojs/taro";
import store from "../store/index";
import {
  BASE_SERVER_URL,
  CUSTOMER_SERVER_URL,
  LogoutCode,
  SuccessCode,
  OLD_BASE_SERVER_URL,
  SHOWER_APP_URL,
  SMPRO_URL,
  GX_URL,
  APP_HOME_URL,
  WSAHING_MACHINE_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",
            ...entity.header
          }
        : {
            reqSource: "wxmini",
            ...entity.header
          },
      url: basePath + entity.url
    }).then(
      ({ data }: ResponseEntity): ResponseDataEntity<any> => {
        if (data.code === SuccessCode) {
          return data;
        }
        if (data.code === LogoutCode) {
          Taro.reLaunch({
            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 appHomeFetch = createFetch(APP_HOME_URL);
export const showerFetch = createFetch(SHOWER_APP_URL);
export const smaproFetch = createFetch(SMPRO_URL);
export const gxFetch = createFetch(GX_URL);
export const wmFetch = createFetch(WSAHING_MACHINE_URL);

export default createFetch;
