/**
 * Created by Anndy Yang on 19/02/28.
 */
let orderVac = [
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S"
];

import { envConfig } from '@/utils/env-config'
const { BUILD_ENV } = process.env;

// 获取SC服务器域名地址
export function getBaseUrl(url) {
  return getConfigByEnvType('baseUrl') + url
}

// 获取API服务器域名地址
export function getApiUrl(url) {
  return getConfigByEnvType('apiUrl') + url
}

// 获取WEB部署服务器域名地址
export function getWebPageUrl(url) {
  return getConfigByEnvType('webPageUrl') + (url || '')
}

// 获取推送域名地址（message_push）
export function getHactiveUrl(url) {
  return getConfigByEnvType('hactiveUrl') + (url || '')
}

// 获取pdf文件地址
export function getPdfFileUrl(path) {
  let base = getConfigByEnvType('webPageUrl');
  return `${base}proxyPdf${path}`;
}

// 获取微信APPID
export function getAPPID() {
  return getConfigByEnvType('appId')
}

// 获取微信APPID对应type
export function getWxType() {
  return getConfigByEnvType('wxType')
}


// 根据不同环境，生成URL
function getConfigByEnvType(urlType) {
  return envConfig[process.env.BUILD_ENV][urlType]
}

// 日期与时间解析函数
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return ''
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 获取APP版本号（数值型）
export function getAppVersion(appVersion) {
  if (!appVersion) return 200;
  return appVersion.split('.').join('')
}

export function setEventByModuleCode(itemData) {
  let modeCode = itemData.appModuleInfo.code || '';
  let paramList = itemData.appModuleInfo.paramList ? itemData.appModuleInfo.paramList : ''
  if (modeCode === 'M001' || modeCode === 'M002' || modeCode === 'M003') {
    paramList = ''
  } else if (modeCode === 'M100' || modeCode === 'M300') {

    let urlPara = getUrlParmByCode(paramList);
    paramList[0] && (paramList[0].value += urlPara);

  } else if (modeCode === 'M400') {

    let path = paramList[0]['key'];
    let v = paramList[0]['value'];
    let query = setRouterParm(paramList);
  }
  if (typeof paramList === 'string' && !paramList) {
    paramList = []
  }

  return paramList;
}

function getUrlParmByCode(paramList) {
  if (paramList.length <= 1) {
    return ''
  }
  let dataStr = ''
  let list = [];
  for (let i = 1; i < paramList.length; i++) {
    list.push(paramList[i].key + '=' + paramList[i].value)
  }
  dataStr = list.join('&')
  if (dataStr !== '') {
    return '?' + dataStr
  }
  return ''
}

export function deepCopy(obj) {
  var result = Array.isArray(obj) ? [] : {};
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (typeof obj[key] === 'object') {
        result[key] = deepCopy(obj[key]);   //递归复制
      } else {
        result[key] = obj[key];
      }
    }
  }
  return result;
}

export function mergeObjs(...ojbs) {

}

// 跳转：在App中使用原生跳转，在浏览器中使用本地路由跳转
export function gotoPage(context, pageUrl) {
  if (__isWeb) {
    context.$router.push(pageUrl)
    // context.$router.push({path: pageUrl, query: query});
  } else {
    let paramList = [
      {
        key: "pageUrl",
        value: getWebPageUrl(pageUrl),
        type: 4,
        seqNo: 1
      }
    ];
    rocNative.dispatchEventByModuleCode({
      modeCode: "M300",
      jsonString: paramList
    });
  }
}

function formatNum(n) {
  return n * 1 < 10 ? `0${n}` : n;
}

// 传入秒，计算出剩余时间的时分秒
export function formatLeftTimeObj(time, hasZero = true) {
  if (typeof time !== 'number') {
    time = parseInt(time)
  }
  // time = parseInt(time / 1000)
  // const d = parseInt(time / 86400)
  // time = time - d * 86400
  const h = parseInt(time / 3600)
  time = time - h * 3600
  const f = parseInt(time / 60)
  const s = parseInt(time - f * 60)
  return {
    // d: hasZero ? formatNum(d) : d,
    h: hasZero ? formatNum(h) : h,
    f: hasZero ? formatNum(f) : f,
    s: hasZero ? formatNum(s) : s,
  }
}

export function preLoadImg(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      resolve(img);
    }
    img.onerror = () => {
      reject();
    }
    img.src = url;
  })
}

// 判断是否是微信浏览器
export function isWeiXin() {
  var ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
}

//弹出微信授权
export const wxOauth = () => {
  let url = location.href, redirectUrl;
  let appId = getAPPID();
  url = url.split('?')[0];
  redirectUrl = encodeURIComponent(url);
  console.log('wxOauth redirectUrl => ', redirectUrl);
  window.location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&#wechat_redirect`);
}

export const setCookie = (name, value, time) => {
  var expires = 30 * 24 * 60 * 60 * 1000; //一天
  var date = new Date(+new Date() + expires);
  if (time) {
    document.cookie =
      name +
      '=' +
      escape(value) +
      '; path=/' +
      ';expires=' +
      date.toUTCString();
  } else {
    document.cookie = name + '=' + escape(value) + '; path=/';
  }
};

export const delCookie = key => {
  var expires = -1 * 24 * 60 * 60 * 1000; //一天
  var date = new Date(+new Date() + expires);
  document.cookie =
    key + '=' + escape('') + '; path=/' + ';expires=' + date.toUTCString(); //这里只需要把Cookie保质期退回一天便可以删除
};

export const getCookie = key => {
  var cookieArr = document.cookie.split('; ');
  for (var i = 0; i < cookieArr.length; i++) {
    var arr = cookieArr[i].split('=');
    if (arr[0] === key) {
      return arr[1];
    }
  }
  return '';
};

export function debounce(fn, wait = 50) {
  let timer;
  return function () {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    }, wait)
  }
}

function decode(input) {
  return decodeURIComponent(input.replace(/\+/g, ' '));
}

export function querystring(query) {
  var parser = /([^=?&]+)=?([^&]*)/g
    , result = {}
    , part;
  for (;
    part = parser.exec(query);
    result[decode(part[1])] = decode(part[2])
  );

  return result;
}

export function getOrderText(index) {
  return orderVac[index];
}

// 从数组中查找某个key对应值所在的位置（序号：0开始的）
export function findQuestionIndexNo(oList, key, keyValue) {
  let index = oList.findIndex(item => {
    return item[key] == keyValue;
  });
  return index;
}

// 对两个数组中的元素进行排序
export function concatArray(firstArr = [], secondArr = [], key) {
  if (firstArr.length == 0) return secondArr;
  if (secondArr.length == 0) return [];
  let all = [], newArr = [], deleteIndex;
  if (firstArr[0][key] == secondArr[0][key]) {
    return firstArr;
  } else if (firstArr[0][key] < secondArr[0][key]) {
    all = firstArr.concat(secondArr);
  } else {
    all = secondArr.concat(firstArr);
  }
  // 从all中去重
  for (let i = 0; i < all.length; i++) {
    deleteIndex = findQuestionIndexNo(all.slice(i + 1), key, all[i][key]);
    if (deleteIndex >= 0) {
      all.splice(deleteIndex, 1);
      i--;
    }
  }
  console.log("in contactArray", all);
  return all;
}

// 将分转换成元
export function convertToYuan(price) {
  return (price / 100).toFixed(0);
}


