import amosRequest, { commonGet as get, commonPost as post, commonPut as put, commonDelete as del, singleFetch } from 'amos-processor/lib/fetch/amosRequest';
import { AmosFetch as oaf, XssAmosFetch as oxaf } from 'amos-processor';
import * as xar from 'amos-processor/lib/fetch/xssRequest';
import { asyncRedux, xssAsyncRedux } from 'amos-processor/lib/fetch/asyncRedux';
import actionCreator, { xssActionCreator } from 'amos-processor/lib/redux/actionCreator';
import { utils, Store } from 'amos-tool';
import formatUrl from 'amos-processor/lib/utils/urlFormat';
import toFormData from 'amos-processor/lib/utils/toFormData';
import { UNIFIED_PLATFORM } from './../consts';

const lsTool = Store.lsTool;

const defaultPageable = {
  page: 0,
  size: 10
};

const successStatus = 200;

const defaultHeaders = {
  // appKey: 'YH-PATROL',
  // product: 'YH-PATROL_WEB'
};

const compleHeaders = () => {
  return {
    ...defaultHeaders,
    token: getToken()
  };
};

// 统一平台处理数据结果
function payload(data) {
  return new Promise((resolve, reject) => {
    if (data.state) {
      resolve(data);
    } else {
      if (data && data.status === successStatus) {
        resolve(data.result);
      } else {
        if (data) {
          reject(data.message);
        } else {
          reject(data);
        }
      }
    }
  });
}

/**
 * 获取 token
 */
const getToken = () => {
  return lsTool.read(sysConsts.token);
}


/**
 * 设置 token
 * @param {*} $token
 */
const setToken = (token) => {
  return lsTool.write(sysConsts.token, token);
}

/**
 * 构建分页
 */
const buildPageable = (url, pageable = defaultPageable) => {
  let { page, size } = pageable;
  return `${url}?page=${page}&size=${size}`;
};

/**
 * 转换指定值为 JSON
 * @param {array} dataList
 * @param {string} key
 */
const convertDatalist = (dataList = [], key = 'content') => {
  const newDL = dataList.map(d => {
    if (!utils.isNil(d[key]) && utils.isString(d[key])) {
      d[key] = JSON.parse(d[key]);
    }
    return d;
  });
  return newDL;
};

export const commonGet = url => {
  return get(url, {
    payload,
    hasCookie: true,
    headers: compleHeaders()
  });
};

export const commonPost = (url, data) => {
  return post(url, data, {
    payload,
    hasCookie: true,
    headers: compleHeaders()
  });
};

export const commonPut = (url, data) => {
  return put(url, data, {
    payload,
    hasCookie: true,
    headers: compleHeaders()
  });
};

export const commonDelete = (url, data) => {
  return del(url, data, {
    payload,
    hasCookie: true,
    headers: compleHeaders()
  });
};

export const xssAmosRequest = {
  _request(type) {
    return (url, data) => {
      if (!xar[type]) {
        throw new Error(`xssAmosRequest: 错误的请求[${type}]`);
      }
      return xar[type](url, data, {
        payload,
        hasCookie: true,
        headers: compleHeaders()
      });
    };
  },
  commonGet(url) {
    return xar.commonGet(url, {
      payload,
      hasCookie: true,
      headers: compleHeaders()
    });
  },
  commonPost(url, data) {
    return xssAmosRequest('commonPost')(url, data);
  },
  commonPut(url, data) {
    return xssAmosRequest('commonPut')(url, data);
  },
  commonDelete(url, data) {
    return xssAmosRequest('commonDelete')(url, data);
  }
};

export const AmosFetch = {
  _fetch(type) {
    return (url, params, data) => {
      if (!oaf[type]) {
        throw new Error(`AmosFetch: 错误的请求[${type}]`);
      }
      const newParams = utils.merge(
        {
          headers: {
            ...defaultHeaders,
            token: getToken()
          },
          // 启用 cookie， `include, same-origin, *omit`
          credentials: 'include'
        },
        params
      );
      return oaf[type](url, { params: newParams, data });
    };
  },
  get(url, { params, data } = {}) {
    return AmosFetch._fetch('get')(url, params, data);
  },
  put(url, { params, data } = {}) {
    return AmosFetch._fetch('put')(url, params, data);
  },
  post(url, { params, data } = {}) {
    return AmosFetch._fetch('post')(url, params, data);
  },
  del(url, { params, data } = {}) {
    return AmosFetch._fetch('del')(url, params, data);
  }
};

export const XssAmosFetch = {
  _fetch(type) {
    return (url, params, data) => {
      if (!oxaf[type]) {
        throw new Error(`XssAmosFetch: 错误的请求[${type}]`);
      }
      const newParams = utils.merge(
        {
          headers: {
            ...defaultHeaders,
            token: getToken()
          },
          // 启用 cookie， `include, same-origin, *omit`
          credentials: 'include'
        },
        params
      );
      return oxaf[type](url, { params: newParams, data });
    };
  },
  get(url, { params, data } = {}) {
    return AmosFetch._fetch('get')(url, params, data);
  },
  put(url, { params, data } = {}) {
    return AmosFetch._fetch('put')(url, params, data);
  },
  post(url, { params, data } = {}) {
    return AmosFetch._fetch('post')(url, params, data);
  },
  del(url, { params, data } = {}) {
    return AmosFetch._fetch('del')(url, params, data);
  }
};

/**
 * 清空所有
 */
export const clearAll = () => {
  // 清空 cookie 记住密码信息在cookie中，不宜执行全部清空
  // Store.clearAllCookie();
  // 清空 ls 部分 强缓存资源文件存放在 localStorage 中，不宜执行全部清空
  // lsTool.clearAll();
  // 清空 sessiong
  Store.session.clearAll();
};

export {
  amosRequest,
  singleFetch,
  convertDatalist,
  buildPageable,
  formatUrl,
  getToken,
  setToken,
  asyncRedux,
  xssAsyncRedux,
  actionCreator,
  xssActionCreator,
  toFormData
};
