import axios from 'axios';
import md5 from 'js-md5';
import store from "@/store"
import { Toast,MessageBox  } from 'mint-ui';
import router from '../router'
import Cookie from '../util/cookie'
// 默认超时设置
axios.defaults.timeout = 5000;
// 相对路径设置
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));
      json.sing = "singsingenglish21000";
      console.log(json)
      config.params.param_token = md5(JSON.stringify(json));
    }else if(config.url !== '/api/admin/login'){
      config.data = config.data || {};
      let json = JSON.parse(JSON.stringify(config.data));
      json.sing = "singsingenglish21000";
      config.data.param_token = md5(JSON.stringify(json));
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    if(response.data.code === 501){
      // 登录验证
      router.push({
        name:'login'//从哪个页面跳转
      })
    }
    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);
        console.log(json.file);
        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:60000,
          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 => {
            reject(err);
            let message = '请求失败！请检查网络';
            if(err.response)message=err.response.data.message;
            MessageBox({
              title:'错误！',
              message:message,
            })
          })
      };
      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{
          Toast(response.data.msg)
        }
      })
      .catch(err => {
        reject(err);
        let message = '请求失败！请检查网络';
        if(err.response)message=err.response.data.message;
        MessageBox({
          title:'错误！',
          message:message,
        })
      })
  })
}


/**
 * 封装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{
          Toast(response.data.msg)
        }
      },err => {
        reject(err);
        let message = '请求失败！请检查网络';
        if(err.response)message=err.response.data.message;
        MessageBox({
          title:'错误！',
          message:message,
        })
      })
  })
}

/**
 * 封装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{
          Toast(response.data.msg)
        }
      },err => {
        reject(err);
        let message = '请求失败！请检查网络';
        if(err.response)message=err.response.data.message;
        MessageBox({
          title:'错误！',
          message:message,
        })
      })
  })
}

/**
 * 封装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{
          Toast(response.data.msg)
        }
      },err => {
        reject(err);
        let message = '请求失败！请检查网络';
        if(err.response)message=err.response.data.message;
        MessageBox({
          title:'错误！',
          message:message,
        })
      })
  })
}

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{
          Toast(response.data.msg)
        }
      },err => {
        reject(err);
        let message = '请求失败！请检查网络';
        if(err.response)message=err.response.data.message;
        MessageBox({
          title:'错误！',
          message:message,
        })
      })
  })
}
