import { routerRedux } from 'dva/router';
import { notification } from "antd";
import Cookies from 'js-cookie';
import store from '../global';

import breadFetch, { myFetch } from './myFetch';

const CUSTOMER_KEY = '_A_P_customer';
const CURRENCY_KEY = '_A_P_currency';
const USERID_KEY = '_A_P_userId';
const GOTOLOGIN = "/gotoLogin";
const WBALONE_URL = "/wbalone/pages/login/login.html";

const gotoLogin = () => {
  const res = myFetch(WBALONE_URL)
  .then(res => {
    if (res.headers.get('Content-Type').indexOf('text') >= 0) {
      return res.text();
    } else if (res.headers.get('Content-Type').indexOf('json') >= 0) {
      return res.json();
    }
  })
  .then(response => {
    if (response.indexOf("<div class=\"login-con-box\">") >= 0) {
      const { dispatch } = store;
      dispatch(routerRedux.push(GOTOLOGIN));
    } else {
      const { dispatch } = store;
      dispatch(routerRedux.push(GOTOLOGIN));
    }
  })
  .catch(e => {
    console.log(e);
    const { dispatch } = store;
    dispatch(routerRedux.push(GOTOLOGIN));
    // window.location.href = WBALONE_URL;
  });
};

const getCustomer = () => {
  let customer = localStorage.getItem(CUSTOMER_KEY);
  // 转换为JSON
  if (customer && customer != 'undefined' && customer != 'null') {
    customer = JSON.parse(customer);
  }
  if (!customer) {
    gotoLogin();
    return {};
  } else {
    return customer;
  }
};
const setCustomer = customer => {
  localStorage.setItem(CUSTOMER_KEY, customer);
};
const getDefaultCurrency = () => {
  let currency = localStorage.getItem(CURRENCY_KEY);
  // 转换为JSON
  if (currency && currency != 'undefined' && currency != 'null') {
    currency = JSON.parse(currency);
  }
  if (!currency || currency.message) {
    gotoLogin();
    return {};
  } else {
    return currency;
  }
};
const setDefaultCurrency = currency => {
  localStorage.setItem(CURRENCY_KEY, currency);
};
const getUserId = () => {
  const userId = Cookies.get(USERID_KEY);
  // const userId = Cookies.get('_A_P_userLoginName');
  return userId;
  // return "52f10e37eb9d459e89fb8877e13d1365"
};


function checkStatus(response, request) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  let errortext = codeMessage[response.status] || response.statusText;
  return response.json().then(data => {
    errortext = data.message || errortext;
    if (!request.options.dontShowErrMsg) {
      notification.error({
        message: `${request.options.description || ''} 请求异常`,
        description: errortext,
      });
    }
    return {};
  });
}

const checkUser = () => {
  const userId = Cookies.get(USERID_KEY);
  return !!userId;
};
const checkCustomer = () => {
  const customer = getCustomer();
  return !!customer;
};

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
const WHITELIST = [
  WBALONE_URL,
  '/occ-base/base/channel/customers/find-by-userId',
  '/wbalone/open/getEncryptParam',
  '/wbalone/account/login',
];
breadFetch.interceptors.push((req, next) => {
  let inWhiteList = false;
  for (const item of WHITELIST) {
    if (req.url.startsWith(item)) {
      inWhiteList = true;
      break;
    }
  }
  if (inWhiteList) {
    next(checkStatus);
  } else if (checkUser() && checkCustomer()) {
    next(checkStatus);
  } else {
    gotoLogin();
  }
});

export default function request(url, options) {
  const defaultOptions = {
    credentials: "include"
  };
  const newOptions = { ...defaultOptions, ...options };
  if (newOptions.method === "POST" || newOptions.method === "PUT") {
    newOptions.headers = {
      Accept: "application/json",
      "Content-Type": "application/json; charset=utf-8",
      ...newOptions.headers
    };
    newOptions.body = JSON.stringify(newOptions.body);
  } else {
    // 默认为 get 请求
    const body = Object.keys(newOptions.body || {})
      .map(key => `${key}=${newOptions.body[key]}`)
      .join("&");
    if (body && url.indexOf("?") > 0) {
      url += `&${body}`;
    } else if (body) {
      url += `?${body}`;
    }
  }
  // 补充请求地址
  if (url.startsWith("/b2b")) {
    url = `/occ-b2b-order${url}`;
  } else if (url.startsWith("/buyer")) {
    url = `/occ-b2b-buyer${url}`;
  }
  if ((!newOptions.method || newOptions.method === 'GET' || newOptions.method === 'HEAD') && newOptions.body) {
    // console.log(`TypeError: Body not allowed for GET or HEAD requests===${JSON.stringify(newOptions.body)}`);
    delete newOptions[`body`];
  }
  return myFetch(url, newOptions)
    .then(res => {
      // if (res.status < 200 || res.status >= 300) {
      //   return {};
      // } else
      if (res.headers.get('Content-Type').indexOf('text') >= 0) {
        return res.text();
      } else if (res.headers.get('Content-Type').indexOf('json') >= 0) {
        return res.json();
      }
    })
    .catch(e => {
      console.log(e);
    });
  }
    //   const { dispatch } = store;
    //   const status = e.name;
    //   if (status === 401) {
    //     dispatch({
    //       type: 'login/logout',
    //     });
    //     return;
    //   }
    //   if (status === 403) {
    //     dispatch(routerRedux.push('/exception/403'));
    //     return;
    //   }
    //   if (status <= 504 && status >= 500) {
    //     dispatch(routerRedux.push('/exception/500'));
    //     return;
    //   }
    //   if (status >= 404 && status < 422) {
    //     dispatch(routerRedux.push('/exception/404'));
    //   }
    // });

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

export {
  getCustomer,
  setCustomer,
  getDefaultCurrency,
  setDefaultCurrency,
  getUserId
};
