import Vue from "vue";
import axios from "axios";
import vueAxios from "vue-axios";
import store from "../store/store";
// import router from '../router'
// import store from "../store/store";
import { Toast } from "vant";
const variables = [
  "B6dB3QqGZP1lKNICTaiAeNJSHKNepO5GGgtL6FUceqSlpFZCdx2SZ5MPPbzrgy91HeR0dnJazcMrvMgPF7bhFrfsGaApJKk4JohEEhoJ4kKJpAaGsfrFhb7FPgMvrMczaJnd0ReH19ygrzbPPM5ZS2xdCZFplSqecUF6LtgGG5OpeNKHSJNeAiaTCINKl1PZGqQ3Bd6B",
  "EUhzJoyKP7VydtpyBwNUGU2tqzI0QB0LIpQ10Fk3hX2ZcPoGRpACqmzcTQbKd98i3U7raFz2rMl2kys0ODgtAh22E3i57wmh38RbbR83hmw75i3E22hAtgDO0syk2lMr2zFar7U3i89dKbQTczmqCApRGoPcZ2Xh3kF01QpIL0BQ0Izqt2UGUNwByptdyV7PKyoJzhUE",
  "xexcHoyVwOs5TYTQVvU0iXn56ryKVdWedLTpq3KEKmbUHfwzuZjIpZOPVXMEappFhjdqwtp1bBrWaRBCfPFwCq2W8SsyvwqZ6sIGGIs6ZqwvysS8W2qCwFPfCBRaWrBb1ptwqdjhFppaEMXVPOZpIjZuzwfHUbmKEK3qpTLdeWdVKyr65nXi0UvVQTYT5sOwVyoHcxex",
  "2Llnegc5i4flqd4HZPFK210yh61boBxRSdnNVMeudKimx92Qi4aPuHP12HmEImbWrXjLgBGqy1bSnKvLhqMqhknyuse4nFoeLTkJJkTLeoFn4esuynkhqMqhLvKnSb1yqGBgLjXrWbmIEmH21PHuPa4iQ29xmiKdueMVNndSRxBob16hy012KFPZH4dqlf4i5cgenlL2",
  "dZzoMZF6xtt3voTFDbPzEZ7GeM8t7uY05d4K4xfhtdxELh96dDRB4oRYA2smET5dy1dafGkXOz2V7tNOVi0vSqfuhI99IKprVK6QQ6KVrpKI99IhufqSv0iVONt7V2zOXkGfad1yd5TEms2AYRo4BRDd69hLExdthfx4K4d50Yu7t8MeG7ZEzPbDFTov3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ios/this.$http使用axios，一次封装方便协作规范
Vue.use(Toast);
const BASE_URL = process.env.API_HOST //'https://lzdz3-isv.isvjcloud.com/api';
let requestIndex = 0;
function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i].trim();
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";

}
/**
 * Generates a new variable based on the given string.
 * @param {string} str - The input string.
 * @returns {string} - The generated variable.
 */
function generateVariable(data) {

  let nowTime = Date.now() + parseInt(getCookie('te'));
  if (typeof data != 'object') {
    data = JSON.parse(data);
  }
  data.nowTime = nowTime;
  let para = getCookie('pToken') + (nowTime);

  const str = para.substring(0, (para.length - 5));
  let key = '';
  for (let i = 0; i < str.length; i++) {
    let index = str.charCodeAt(i);
    let variableIndex = index % 10;
    let ar = variables[variableIndex][i];
    key += ar;
  }

  // 转换为24个字节构成的字符串
  var keyLen = key.length;
  var seg = Math.floor(keyLen / 24);
  var encodeBytes = '';
  for (var i = 0; i < 24; i++) {
    var endIndex = (i + 1) * seg;
    if (i === 23) {
      endIndex = keyLen;
    }
    // 每seg个字符对应的bytes加和求平均值，得到一个平均值字节
    var subStr = key.substring(i * seg, endIndex);
    var bytes = [];
    for (var j = 0; j < subStr.length; j++) {
      bytes.push(subStr.charCodeAt(j));
    }
    var sum = bytes.reduce(function (acc, val) {
      return acc + val;
    }, 0);
    // 求一组子串中的平均值字节
    var b = Math.floor(sum / bytes.length);
    encodeBytes += String.fromCharCode(b);
  }
  key = encodeBytes

  const tokenKey = genTokenKey(key)
  const keyBytes = CryptoJS.enc.Utf8.parse(tokenKey);
  const ivBytes = CryptoJS.enc.Utf8.parse('');
  const encrypted = CryptoJS.AES.encrypt(JSON.stringify(data), keyBytes, {
    iv: ivBytes,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
}
function genTokenKey(specialStr) {
  // 字符串反转
  specialStr = specialStr.split('').reverse().join('');
  // Base64使用12个字节即可生成16个字节
  const encodeBytes = new Uint8Array(12);
  // bytes中包含24个字节，每两个字节处理一次
  const bytes = new TextEncoder().encode(specialStr);
  // 每两个字节做一次处理，尽量保证第二个字节小幅度改动能影响以后的处理
  for (let i = 0; i < bytes.length; i += 2) {
    let val = (bytes[i] << 5) | (bytes[i + 1] & 0xFF);
    val %= 63;
    encodeBytes[i >> 1] = val;
  }
  // 二进制拼串
  let binaryStr = '';
  for (let i = 0; i < encodeBytes.length; i++) {
    binaryStr += (encodeBytes[i] + 0x100).toString(2).slice(1);
  }
  let processedStr = '';
  let prevVal = '';
  // 每6位对应一个Base64编码，根据上一次处理结果循环左移本次结果，尽量保证第一个字节小幅度改动能影响以后的处理
  for (let i = 0; i < 16; i++) {
    if (i !== 0) {
      const index = i * 6;
      const currVal = binaryStr.substring(index, index + 6);
      let curr = parseInt(currVal, 2);
      const chars = prevVal.split('');
      for (let j = 0; j < chars.length; j++) {
        if (chars[j] === '1') {
          curr = ((curr >> (6 - j) | (curr << j)) & 0x3F);
        }
      }
      prevVal = (curr & 0x3F).toString(2).padStart(6, '0');
    } else {
      prevVal = binaryStr.substring(0, 6);
    }
    processedStr += prevVal;
  }
  // 二进制串转回字节数组
  for (let i = 0; i < 12; i++) {
    const index = i * 8;
    encodeBytes[i] = parseInt(processedStr.substring(index, index + 8), 2);
  }
  const key = btoa(String.fromCharCode.apply(null, encodeBytes));
  return key;
}
Toast.allowMultiple();
//防止b端调用加载
// if (sessionStorage.getItem('isC') == 'c') {
  // 添加请求拦截器
  axios.interceptors.request.use(
    function (config) {
      // 在发送请求之前做些什么
      // store.commit("increase", 1);
      if (requestIndex < 0) {
        requestIndex = 0;
      }
      requestIndex++;

      Toast.loading({
        duration: 0, // 持续展示 toast
        message: "加载中...",
        forbidClick: true
      });
      return config;
    },
    function (error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    }
  );

  // 添加响应拦截器
  axios.interceptors.response.use(
    function (response) {
      console.log(response,'response');
      // 对响应数据做点什么
      store.commit("reduce", 1);

      requestIndex--;
      if (requestIndex <= 0) {
        Toast.clear();
      }
      if(response.data.resp_code == 101){
        window.location.replace(process.env.ACTIVITY_HOST + "/errorPage?soHot=1&ajcode=101")
        return 
      }
      return response;
    },
    function (error) {
      console.log(error.response.data,'响应的数据'); // 响应的数据
      console.log(error.response.status,'响应的 HTTP 状态码'); // 响应的 HTTP 状态码
      console.log(error.response.headers,'响应的头信息'); // 响应的头信息
      if(error.response.status === 555 || error.response.status === 500){
        window.location.replace(process.env.ACTIVITY_HOST + "/errorPage?soHot=1&ajcode="+error.response.status)
        return false
      }
      // else if(error.response.status === 493){
      //   window.location.replace(process.env.ACTIVITY_HOST + "/crowded")
      //   return false
      // }
      else {
        // location.href = 'https://3.cn/10-0hi80x?errorAjax=1';
        window.location.replace('https://h5static.m.jd.com/mall/active/2ngyMcc8Ddhv9w9WiJ32wygkteex/index.html?babelChannel=ttt1')
        return false;
      }
      // if (process.env.NODE_ENV != "development") {
      //   location.href = 'https://3.cn/10-0hi80x?errorAjax=1';
      // }
      // 对响应错误做点什么
      // return Promise.reject(error);
    }
  );
// }
let envInfos = '';
let jsVersions = '';
try{
  var env = window.getJdEnvInfo();
  envInfos = env.data;
  jsVersions = env.version
}catch(e){}
export default {
  // post请求
  post(url, params) {
    let isLogin = url.indexOf('/user-info/login') != -1
    let isNoMeet = location.href.indexOf('/noMeet') != -1;
    let interfaceName = url.replace(BASE_URL, '');
    let activityId = store.state.activityId ? store.state.activityId : ''
    let defenseList = store.state.defenseList ? store.state.defenseList : []
    let newDefenseList = []
    if (defenseList.length > 0) {
      defenseList.forEach(ele => {
        if(ele.interfaceName.indexOf('/api') > -1){
          newDefenseList.push(ele.interfaceName.slice(4))
        }else{
          newDefenseList.push(ele.interfaceName)
        }
      })
      if (newDefenseList.includes(interfaceName)) {
        params.actId = activityId;
        params = JSON.stringify({ ecyText: generateVariable(params) });
      }
    }
    let TOKENS = ''
    if(isNoMeet){
      TOKENS = localStorage.getItem('token')
    }
    return new Promise((resolve, reject) => {
      axios({
        method: "post",
        url: url,
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          token:  isLogin ? '' : store.state.token ? store.state.token : TOKENS,//42416b21-3a61-4695-9e40-ffa883996339
          reserveEnvInfo:envInfos?envInfos:'',
          reserveJsVersion:jsVersions?jsVersions:'',
          reserveClientType:'H5',
          // reserveFlowType:'1',
          reserveIsvToken:sessionStorage.getItem("lz_wq_auth_token")
        },
        data: params
      })
        .then(res => {
          if (res.status === 200) {
            // console.log(res, 'asdasd')
            if (res.data.resp_code == 50009) {
              //触发活动已结束，则刷新页面
              // location.reload();
              console.log('活动已结束')
              // Notify('活动已结束33')

            }
            if (res.data.resp_code == 50012) {
              //触发活动已结束，则刷新页面
              // location.reload();
              resolve(res);

            } else {
              resolve(res);
            }
            requestIndex--;
            if (requestIndex <= 0) {
              Toast.clear();
            }
          }
        })
        .catch(error => {
          reject(error);
          Toast.clear();

        });
    });
  },

  get(url, params) {
    let isLogin = url.indexOf('/user-info/login') != -1
    let isNoMeet = location.href.indexOf('/noMeet') != -1;
    let TOKENS = ''
    if(isNoMeet){
      TOKENS = localStorage.getItem('token')
    }
    return new Promise((resolve, reject) => {
      axios(url, {
        params,
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          token: isLogin ? '' : store.state.token ? store.state.token : TOKENS, //42416b21-3a61-4695-9e40-ffa883996339
          reserveEnvInfo:envInfos?envInfos:'',
          reserveJsVersion:jsVersions?jsVersions:'',
          reserveClientType:'H5',
          // reserveFlowType:'1',
          reserveIsvToken:sessionStorage.getItem("lz_wq_auth_token")
        },
      })
        .then(res => {
          requestIndex--;
          if (requestIndex <= 0) {
            Toast.clear();
          }

          if (res.status === 200) {
            resolve(res);
          }
        })
        .catch(error => {
          reject(error);
          Toast.clear();
        });
    });
  }
};
