import { Toast } from 'antd-mobile'
import cookie from 'react-cookies'
import axios from 'axios'
import md5 from 'md5'
import showdown from 'showdown'

const opens = "79e33abd4b6588941ab7622aed1e67e8"
let timestamp
let checkSubmitFlg = false
let debugType = ""
let message501 = false

if (process.env.NODE_ENV === "development") {
  const search = window.location.search;
  debugType = search.indexOf('debug=t') != -1 ? 'teacher' :
    search.indexOf('debug=s') != -1 ? 'student' :
      search.indexOf('debug=a') != -1 ? 'admin' : 'admin'
}
window._debugType = debugType

async function requestTimestamp(proxy) {
  if (checkSubmitFlg === false) {
    const response = await fetch(proxy)
    const data = await response.json();
    if (data.status === 0) {
      timestamp = data.message;
    }
    checkSubmitFlg = true
    window.setTimeout(function () {
      checkSubmitFlg = false;
    }, 2000);
  }
}

export function setCookie(Cookies) {
  Cookies.map((item, key) => {
    if (item.id === 'educoder_session') {
      cookie.save('_educoder_session', item.value, { path: '/' });
      cookie.save('_educoder_session', item.value, { domain: '.educoder.net', path: '/' });

    } else {
      cookie.save('autologin_trustie', item.value, { path: '/' });
      cookie.save('autologin_trustie', item.value, { domain: '.educoder.net', path: '/' });
    }
  })

}

/* 新版很多接口只是改了接口名字，参数和请求类型并没有修改，只需要建立一个map来处理这个改动就行。 */

function setRequestProxy(config) {
  const normalRequestMap = {}
  // 有些url里面包含了可变的参数，需要遍历一遍，用正则找到对应的url
  const paramRequestOldUrlArray = [/\/api\/v1\/games\/(\w*)\/choose_build/i]
  const paramRequestNewUrlArray = [
    (matchResult) => {
      const stageId = matchResult[1]
      return `/tasks/${stageId}/choose_build.json`
    },
  ]
  const url = config.url;
  if (url.indexOf('.json') !== -1) { // 已经是新接口了
    return config
  }
  config.withCredentials = false
  const oldUrlSplitPathArray = url.split('?');
  let oldPath = oldUrlSplitPathArray[0]
  let newPath, newUrl;
  newPath = normalRequestMap[oldPath];
  if (!newPath) { // 是带参的restful风格的url
    paramRequestOldUrlArray.forEach((item, index) => {
      const matchResult = oldPath.match(item);
      if (matchResult) {  // 找到了对应的restful api url
        const newUrlGenerator = paramRequestNewUrlArray[index];
        newPath = newUrlGenerator && newUrlGenerator(matchResult)

        newUrl = `${newPath}?${oldUrlSplitPathArray[1]}`
        config.url = newUrl
        return config;
      }
    });
  }
  return config;
}

export function initAxiosInterceptors() {
  let proxy = "https://test-newweb.educoder.net"
  // 在这里使用requestMap控制，避免用户通过双击等操作发出重复的请求；
  // 如果需要支持重复的请求，考虑config里面自定义一个allowRepeat参考来控制
  const requestMap = {}
  window.setfalseInRequestMap = function (keyName) {
    requestMap[keyName] = false;
  }

  axios.interceptors.request.use(async function (config) {
    if (config.url.indexOf(proxy) != -1 || config.url.indexOf(':') != -1) {
      return config
    }
    setRequestProxy(config)
    let url = `/api${config.url}`;
    //qq登录去掉api
    if (config.params && config.params.redirect_uri != undefined) {
      if (config.params.redirect_uri.indexOf('otherloginqq') != -1) {
        url = `${config.url}`;
      }
    }
    await requestTimestamp(`${proxy}/api/main/first_stamp.json`);
    let newopens = md5(opens + timestamp)

    if (`${config[0]}` != `true`) {
      if (window.location.port === "3007") {
        config.url = `${proxy}${url}`;
        if (config.url.indexOf('?') == -1) {
          config.url = `${config.url}?debug=${debugType}&randomcode=${timestamp}&client_key=${newopens}`;
        } else {
          config.url = `${config.url}&debug=${debugType}&randomcode=${timestamp}&client_key=${newopens}`;
        }
      } else {
        config.url = url;
        if (config.url.indexOf('?') == -1) {
          config.url = `${config.url}?randomcode=${timestamp}&client_key=${newopens}`;
        } else {
          config.url = `${config.url}&randomcode=${timestamp}&client_key=${newopens}`;
        }
      }
    }

    if (config.method === "post") {
      if (requestMap[config.url] === true) { // 避免重复的请求  导致页面f5刷新 也会被阻止  显示这个方法会影响到定制信息
        return false;
      }
    }
    if (config.url.indexOf('update_file') === -1) {
      requestMap[config.url] = true;

      window.setTimeout("setfalseInRequestMap('" + config.url + "')", 900)
    }
    return config;

  }, error => {
    return Promise.reject(error);
  })


  axios.interceptors.response.use(function (response) {
    if (response === undefined) {
      return
    }
    const { data } = response
    const { status, message } = data
    if (status === -1) {
      if (window.location.pathname.startsWith('/tasks/')) {
        Toast.info(message || '服务器异常，请联系管理员。');
      } else {
        Toast.info(message || '服务器异常，请联系管理员。');
      }
      throw new axios.Cancel('Operation canceled by the user.');
    }

    if (status === 403 || status === "403") {
      Toast.info('访问异常，无权限。');
    }

    if (status === 404) {
      Toast.info('访问异常，接口404。');
    }

    if (status === 500) {
      Toast.info('访问异常，接口500。');
    }

    if (status === 501) {
      if (message501 === false) {
        message501 = true
        Toast.info(message || '访问异常，请求不合理');
      }
      window.setTimeout(function () {
        message501 = false
      }, 2000);
    }

    requestMap[response.config.url] = false;
    return response;
  })

}

export function exportMdtoHtml(md) {
  var converter = new showdown.Converter()
  return converter.makeHtml(md);
}


export function debounce(func, wait, immediate) {
  var timeout
  return function () {
    var context = this, args = arguments
    var later = function () {
      timeout = null
      if (!immediate) func.apply(context, args)
    };
    var callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(context, args)
  }
}

