import axios from 'axios'
import appConst from './appConst'
import * as qiniu from 'qiniu-js'
// var qiniu = require('qiniu-js')
//请求mongodb的get
window.axios=axios
export const get = (url, query) => {
  const token = 'Bearer ' + window.localStorage.token
  const loginId = window.localStorage.loginId

  let _url
  if (query) {
    _url = `${appConst.BACKEND_DOMAIN}${url}?${query}`
  } else {
    _url = `${appConst.BACKEND_DOMAIN}${url}`
  }
  return axios.get(_url, {
    headers: { authorization: token, loginId: loginId }
  })
    .then((res) => {
      if (res.status >= 200 && res.status < 300) {
        return res.data
      }
    })
    .catch((err) => {
      errorProcess(err)
      return Promise.reject(err)
    })
}

export const post = (url, query) => {
  const token = 'Bearer ' + window.localStorage.token
  const loginId = window.localStorage.getItem('loginId')
  let _url = `${appConst.BACKEND_DOMAIN}${url}`
  return axios.post(_url, query, {
    headers: { authorization: token, loginId: loginId  }
  })
    .then((res) => {
      if (res.status >= 200 && res.status < 300) {
        return res.data
      }
    })
    .catch((err) => {
      console.log(err)
      errorProcess(err)
      return Promise.reject(err)
    })
}
export const uploadPsd = (url, query) => {
  // url = url + 'psd'
  const token = 'Bearer ' + window.localStorage.token
  const loginId = window.localStorage.getItem('loginId')
  let _url = `${appConst.BACKEND_DOMAIN}${url}`
  return axios.post(_url, query, {
    headers: { authorization: token, loginId: loginId  }
  })
    .then((res) => {
      if (res.status >= 200 && res.status < 300) {
        return res.data
      }
    })
    .catch((err) => {
      errorProcess(err)
      return Promise.reject(err)
    })
}

export const put = (url, query) => {
  const token = 'Bearer ' + window.localStorage.token
  const loginId = window.localStorage.loginId
  let _url = `${appConst.BACKEND_DOMAIN}${url}`
  return axios.put(_url, query, {
    headers: { authorization: token, loginId: loginId  }
  })
    .then((res) => {
      if (res.status >= 200 && res.status < 300) {
        return res.data
      }
    })
    .catch((err) => {
      errorProcess(err)
      return Promise.reject(err)
    })
}

export const patch = (url, query) => {
  const token = 'Bearer ' + window.localStorage.token
  const loginId = window.localStorage.getItem('loginId')
  let _url = `${appConst.BACKEND_DOMAIN}${url}`
  return axios.patch(_url, query, {
    headers: { authorization: token, loginId: loginId  }
  })
    .then((res) => {
      if (res.status >= 200 && res.status < 300) {
        return res.data
      }
    })
    .catch((err) => {
      errorProcess(err)
      return Promise.reject(err)
    })
}

export const del = (url, article) => {
  const token = 'Bearer ' + window.localStorage.token
  const loginId = window.localStorage.getItem('loginId')
  let _url = `${appConst.BACKEND_DOMAIN}${url}/${article._id}`
  return axios.delete(_url, {
    headers: { authorization: token, loginId: loginId  }
  })
    .then((res) => {
      if (res.status >= 200 && res.status < 300) {
        return res.data
      }
    })
    .catch((err) => {
      errorProcess(err)
      return Promise.reject(err)
    })
}

const errorProcess = (err) => {
  if (err.response.status === 401) {
    window.location.href = '#/login'
  }
}


/**
 * 获取七牛云的token
 * @param url  路由
 * @param query 参数
 * @returns {Promise<any>}
 */
export const getQiniuToken = (url, query) => {
  let _url = `${appConst.QINIU_DOMAIN}${url}`
  return axios.post(_url, query)
    .then((res) => {
      if (res.status >= 200 && res.status < 300) {
        return res.data
      }
    })
    .catch((err) => {
      errorProcess(err)
      return Promise.reject(err)
    })
}

/**
 * 为了保证每张图片不一样采取的随机UUID的做法
 * @returns {string} 类似java中的String.getUUID方法所返回的值
 */
function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    return v.toString(16);
  });
}

/**
 * 上传文件
 * @param file  具体文件
 * @param complete 上传完执行的回调方法
 * @param progress 上传过程中的回调方法
 */
export const uploadMaterielFile = (file,complete, progress) => {
    getQiniuToken('/elab-marketing-file/upload/getUploadToken').then(res => {
    var token = res.single.token;
    var resultUrl =  res.single.resultUrl;
    var prefix = 'launchTemplate/'+getUUID() + '-';
    var fileName = prefix + file.name.replace(/\s+/g,"");
    var putExtra = {
      fname: "",
      params: {},
      mimeType: null
    };
    var config = {
      useCdnDomain: true,
      disableStatisticsReport: false,
      retryCount: 6,
      region: qiniu.region.z0
    };
    var tp=file.name.substring(file.name.indexOf('.'));
    if(tp==".jpeg"||tp==".jpg"||tp==".gif"||tp==".png"||tp==".icon"){
      console.log('图片')
    }
    else if(tp==".mp4"||tp==".ogg"||tp==".fly"||tp==".mp3"){
      console.log('音视频')
    }

    var observable = qiniu.upload(file, fileName, token, putExtra, config);
    observable.subscribe(function(res){
      console.log('next------' + JSON.stringify(res))
      progress(res);
    }, function(res){
      console.log('error-----' + JSON.stringify(res))
    }, function(res){
      console.log('complete--------' + JSON.stringify(res))
      let addressUrl = resultUrl + res.key;
      complete(addressUrl)
      return addressUrl ;
    });
  }).catch((err) => {
    errorProcess(err)
    return Promise.reject(err)
  })

}
// base 64
export const uploadBase64=(data)=>{
  // return axios.post(appConst.QINIU_DOMAIN+'/elab-marketing-file/upload/uploadBase64',data)
    return  new Promise(function (resolve,reject) {
      var base64Str = data.base64Str
      getQiniuToken('/elab-marketing-file/upload/getUploadToken').then(res => {
        var token = res.single.token;
        var resultUrl =  res.single.resultUrl;
        var pic = base64Str.replace(/^.*?,/, '');
        var url = "https://upload.qiniup.com/putb64/-1"; //非华东空间需要根据注意事项 1 修改上传域名
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange=function(){
          if (xhr.readyState==4){
            let response = JSON.parse(xhr.response)
            let data={}
            if(xhr.status == 200){
              data={
                "success": true,
                "errorCode": null,
                "message": null,
                "single": {
                  "filePath": resultUrl+response.key ,
                }
              }
            }else{

              data={
                "success": false,
                "errorCode": xhr.status,
                "message": response.error,
                "single": {
                  "filePath": null ,
                }
              }
            }
            resolve({data})
          }
        }
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.setRequestHeader("Authorization",  "UpToken " + token);
        xhr.send(pic);
      }).catch((err) => {
        var data={
          "success": false,
          "errorCode": 'faild',
          "message": err,
          "single": {
            "filePath": null ,
          }
        }
        reject({data})
      })
  })
}
