import { amosRequest } from 'amos-processor';
import sysConsts from 'amos-processor/lib/config';
import { Store } from 'amos-tool';
import { message } from 'amos-framework';
import payload from './payload';

const lsTool = Store.lsTool;

const defaultHeaders = () => {
  return window.isIotPluginsToAmos ? window.iotRequestInfo.staticHeader : {
    appKey: 'AMOS_IOT',
    product: 'AMOS_IOT_WEB'
  };
}

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


export function commonGet(url) {
  return amosRequest(url, {
     method: 'GET',
     headers: compleHeaders(),
     reject(error){
      console.log('请求失败，服务器错误！');
      message.danger(error.message || '请求失败，服务器错误！');
    }
    }).then(data => payload(data));
}

export function commonPost(url, data, params) {
  return amosRequest(url, {
    headers: compleHeaders(),
    method: 'POST',
    body: data,
    reject(error){
      console.log('请求失败，服务器错误！');
      message.danger(error.message || '请求失败，服务器错误！');
    }
  }).then(data => payload(data));
}

export function commonPut(url, data, params) {
  return amosRequest(url, {
    headers: compleHeaders(),
    method: 'PUT',
    body: data,
    reject(error){
      console.log('请求失败，服务器错误！');
      message.danger(error.message || '请求失败，服务器错误！');
    }
  }).then(data => payload(data));
}

export function commonDelete(url, data, params) {
  return amosRequest(url, {
    headers: compleHeaders(),
    method: 'DELETE',
    body: data,
    reject(error){
      console.log('请求失败，服务器错误！');
      message.danger(error.message || '请求失败，服务器错误！');
    }
  }).then(data => payload(data));
}

export function getToken(){
  return lsTool.read(sysConsts.token);
}

export function setToken(token){
  return lsTool.write(sysConsts.token, token);
}

export function getUser(){
  return lsTool.read(sysConsts.userId);
}

export function setUser(userId){
  return lsTool.write(sysConsts.userId, userId);
}
