import axios from 'axios';
import md5 from 'js-md5';
import store from "@/store"
import { Toast,MessageBox,Indicator  } from 'mint-ui';
import router from '../router'
import Cookie from '../util/cookie'
// 默认超时设置
axios.defaults.timeout = 50000;

// 相对路径设置
axios.defaults.baseURL ='';
//http request 拦截器
axios.interceptors.request.use(
  config => {
    // 获取token
    const token = localStorage.getItem('cc_token');
    // 设置参数格式
    if(!config.headers['Content-Type']){
      config.headers = {
        'Content-Type':'application/json',
      };
    }
    // 添加token到headers
    if(token){
      config.headers.token = token
    }
    // 鉴权参数设置
    if(config.method === 'get' && config.url !== '/api/admin/login'){
      config.params = config.params || {};
      let json = JSON.parse(JSON.stringify(config.params));
      for(let k in json)
      {
        if(json[k] === null){
          json[k] = ''
        }
        if(typeof json[k] === "string"){
          config.params[k]=config.params[k].replace(/(^\s*)|(\s*$)/g, "");
          json[k]=json[k].replace(/(^\s*)|(\s*$)/g, "");
        }
        json[k] = md5(json[k].toString())
      }
      json.sing = "singsingenglish21000";
      if(process.env.NODE_ENV === 'development' ){
        config.params.special_token="uncle.cyan.cyan";
      }
      config.params.param_token = md5(JSON.stringify(json));
    }else if(config.url !== '/api/admin/login'){
      config.data = config.data || {};
      let json2 = JSON.parse(JSON.stringify(config.data));
      for(let k in json2)
      {

        if(json2[k] === null){
          json2[k] = ''
        }

        if(typeof json2[k] === "string"){
          config.data[k]=config.data[k].replace(/(^\s*)|(\s*$)/g, "");
          json2[k]=json2[k].replace(/(^\s*)|(\s*$)/g, "");
        }
        json2[k] = md5(json2[k].toString())
      }
      json2.sing = "singsingenglish21000";
      if(process.env.NODE_ENV === 'development' ){
        config.data.special_token="uncle.cyan.cyan";
      }
      config.data.param_token = md5(JSON.stringify(json2));
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    if(response.data.code === 501){
      // 登录验证
      router.push({
        name:'author',//从哪个页面跳转
        query:{
          retUrl:window.location.href.split('#')[1] || '',
          is_new_user_url:1
        }
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
);


/**
 * 封装upload方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function upload(url,json) {
  return new Promise((resolve,reject) => {
    //开启分片
    let size = parseInt(Number(json.file.size)/Number(process.env.MAX_FILESIZE) +1);
    let y = 0;
    let fun = function(){
      let formData = new FormData();
      let file = json.file.slice(y*process.env.MAX_FILESIZE,(y+1)*process.env.MAX_FILESIZE);
      formData.append('chunk', y);
      formData.append('file_name', json.file.name);
      formData.append('count', size);
      formData.append('type', json.type);
      formData.append('file', file);
      axios.post(url,formData,{ headers: {
          'Content-Type': 'multipart/form-data'
        },timeout:10000000,
        onUploadProgress: progressEvent => {
          // if(store.state.progressList.find(i=>{return i.id === json.file.uid})){
          //   let progress =  ((Number(progressEvent.loaded) + Number(y*process.env.MAX_FILESIZE)) / Number(json.file.size) * 100| 0);
          //   store.dispatch('setProgress',{type: 'change',id: json.file.uid ,num: progress});
          // }
        },})
        .then(response => {
          if(response.data.code === 200){
            if(y+1<size){
              y++;
              fun()
            }else{
              y=0;
              resolve(response.data.data);
            }
          }else{
            Toast(response.data.msg)
          }
        })
        .catch(err => {
          Indicator.close();
          reject(err);
        })
    };
    fun()
  })
}

/**
 * 封装get方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function fetch(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
      .then(response => {
        if(response.data.code === 200){
          resolve(response.data.data);
        }else if(response.data.code === 501){
          reject(response.data);
          router.push({
            name:'author',//从哪个页面跳转
            query:{
              retUrl:window.location.href.split('#')[1] || '',
              is_new_user_url:1
            }
          })
        }else if(response.data.code === 503){
          reject(response.data);
        }else{
          reject(response.data);
          Toast(response.data.msg)
        }
      })
      .catch(err => {
        reject(err);
      })
  })
}
export function ret2(url){
  return new Promise((resolve,reject) => {
    axios.get(url)
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err);
      })
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.post(url,data)
      .then(response => {
        if(response.data.code === 200){
          resolve(response.data.data);
        }else if(response.data.code === 501){
          reject(response.data);
          router.push({
            name:'author',//从哪个页面跳转
            query:{
              retUrl:window.location.href.split('#')[1] || '',
              is_new_user_url:1
            }
          })
        }else if(response.data.code === 503){
          reject(response.data);
        }else{
          reject(response.data);
          Toast(response.data.msg)
        }
      },err => {
        reject(err);
      })
  })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(url,data)
      .then(response => {
        if(response.data.code === 200){
          resolve(response.data.data);
        }else if(response.data.code === 501){
          reject(response.data);
          router.push({
            name:'author',//从哪个页面跳转
            query:{
              retUrl:window.location.href.split('#')[1] || '',
              is_new_user_url:1
            }
          })
        }else if(response.data.code === 503){
          reject(response.data);
        }else{
          reject(response.data);
          Toast(response.data.msg)
        }
      },err => {
        reject(err);
      })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(url,data)
      .then(response => {
        if(response.data.code === 200){
          resolve(response.data.data);
        }else if(response.data.code === 501){
          reject(response.data);
          router.push({
            name:'author',//从哪个页面跳转
            query:{
              retUrl:window.location.href.split('#')[1] || '',
              is_new_user_url:1
            }
          })
        }else if(response.data.code === 503){
          reject(response.data);
        }else{
          reject(response.data);
          Toast(response.data.msg)
        }
      },err => {
        reject(err);
      })
  })
}

export function del(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.delete(url,data)
      .then(response => {
        if(response.data.code === 200){
          resolve(response.data.data);
        }else if(response.data.code === 501){
          reject(response.data);
          router.push({
            name:'author',//从哪个页面跳转
            query:{
              retUrl:window.location.href.split('#')[1] || '',
              is_new_user_url:1
            }
          })
        }else if(response.data.code === 503){
          reject(response.data);
        }else{
          reject(response.data);
          Toast(response.data.msg)
        }
      },err => {
        reject(err);
      })
  })
}
