import md5 from 'js-md5';
import store from "@/store"
import router from '../router'
import Cookie from '../util/cookie'
import * as qiniu from 'qiniu-js'
// 默认超时设置

axios.defaults.timeout = 50000;

// 相对路径设置
axios.defaults.baseURL ='';
//http request 拦截器
axios.interceptors.request.use(
  config => {
    // 获取token
    const token = Cookie.get('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)
      {
        let reg = /^[0-9]+$/u;
        if(reg.test(json[k])){
          json[k]= Number(json[k])
        }
        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="changchangenglish";
      }
      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)
      {
        let reg = /^[0-9]+$/u;
        if(reg.test(json2[k])){
          json2[k]= Number(json2[k])
        }
        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="changchangenglish";
      }
      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:'login'//从哪个页面跳转
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
);


/**
 * 封装upload方法
 * @param url
 * @param json
 * @returns {Promise}
 */
export function upload(url,json) {
  return new Promise((resolve,reject) => {
    if(json.type === 'local'){
      axios.get('/api/public/qiniu/token',{
        params:{
          file_name:json.file.name
        }
      }).then(res =>
        {
          let putExtra = {
            fname: json.file.name,
            mimeType:json.mimeType || null
          };
          let congif = {};
          let observable = qiniu.upload(json.file,res.data.data.new_name,res.data.data.token,putExtra,congif);
          let observer = {
            next(res){
              let progress =  Number(res.total.percent.toFixed(0));
              if(json.obj){
                json.obj.file.percent = progress;
                json.obj.onProgress(json.obj.file);
              }
              if(store.state.progressList.find(i=>{return i.id === json.file.uid})){
                store.dispatch('setProgress',{type: 'change',id: json.file.uid ,num: progress});
              }
            },
            error(err){
              reject(err);
              let message = '请求失败！请检查网络';
              if(err.response)message=err.response.data.message;
              Vue.prototype.$alert({
                title:'错误！',
                message:message,
                type:'error',
              })
            },
            complete(res){
              res.url = res.key;
              res.name = json.file.name;
              resolve(res);
            }
          };
          let subscription = observable.subscribe(observer)
        }
      );
    }else{
// 开启分片
      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{
              Vue.prototype.$message.error(response.data.msg)
            }
          })
          .catch(err => {
            reject(err);
            let message = '请求失败！请检查网络';
            if(err.response)message=err.response.data.message;
            Vue.prototype.$$msgbox({
              title:'错误！',
              message:message,
              type:'error',
            })
          })
      };
      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 || response.data.code === 504){
          Vue.prototype.$message.error(response.data.msg)
          router.push({
            name:'login'//从哪个页面跳转
          })
        }else if(response.data.code === 503){
          // Vue.prototype.$message.error('请勿频繁操作')
        }else{
          Vue.prototype.$message.error(response.data.msg)
          reject()
        }
      })
      .catch(err => {
        reject(err);
        let message = '请求失败！请检查网络';
        if(err.response)message=err.response.data.message;
        Vue.prototype.$msgbox({
          title:'错误！',
          message:message,
          type:'error',
        })
      })
  })
}


/**
 * 封装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 || response.data.code === 504){
          Vue.prototype.$message.error(response.data.msg)
          router.push({
            name:'login'//从哪个页面跳转
          })
        }else if(response.data.code === 503){
          // Vue.prototype.$message.error('请勿平凡操作')
        }else{
          Vue.prototype.$message.error(response.data.msg)
        }
      },err => {
        reject(err);
        let message = '请求失败！请检查网络';
        if(err.response)message=err.response.data.message;
        Vue.prototype.$msgbox({
          title:'错误！',
          message:message,
          type:'error',
        })
      })
  })
}

/**
 * 封装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){
          router.push({
            name:'login'//从哪个页面跳转
          })
        }else if(response.data.code === 503 || response.data.code === 504){
          Vue.prototype.$message.error(response.data.msg)
          // Vue.prototype.$message.error('请勿平凡操作')
        }else{
          Vue.prototype.$message.error(response.data.msg)
        }
      },err => {
        reject(err);
        let message = '请求失败！请检查网络';
        if(err.response)message=err.response.data.message;
        Vue.prototype.$msgbox({
          title:'错误！',
          message:message,
          type:'error',
        })
      })
  })
}

/**
 * 封装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 || response.data.code === 504){
          Vue.prototype.$message.error(response.data.msg)
          router.push({
            name:'login'//从哪个页面跳转
          })
        }else if(response.data.code === 503){
          // Vue.prototype.$message.error('请勿平凡操作')
        }else{
          Vue.prototype.$message.error(response.data.msg)
        }
      },err => {
        reject(err);
        let message = '请求失败！请检查网络';
        if(err.response)message=err.response.data.message;
        Vue.prototype.$msgbox({
          title:'错误！',
          message:message,
          type:'error',
        })
      })
  })
}

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 || response.data.code === 504){
          Vue.prototype.$message.error(response.data.msg)
          router.push({
            name:'login'//从哪个页面跳转
          })
        }else if(response.data.code === 503){
          // Vue.prototype.$message.error('请勿平凡操作')
        }else{
          Vue.prototype.$message.error(response.data.msg)
        }
      },err => {
        reject(err);
        let message = '请求失败！请检查网络';
        if(err.response)message=err.response.data.message;
        Vue.prototype.$msgbox({
          title:'错误！',
          message:message,
          type:'error',
        })
      })
  })
}
