import axios from 'axios'
import FileVerification from "@/utils/FileVerification"
/**
 * deep clone
 * 深度拷贝
 */
export const _deepClone = (data) => {
  return JSON.parse(JSON.stringify(data))
}

/**
 * 新窗口打开url
 */
export const _href = (el, url, params) => {
  const { href } = el.$router.resolve({
    path: url,
    query: params
  });
  window.open(href, '_blank');
}

/**
 * 递归过滤节点，生成新的树结构
 * @param {Node[]} nodes 要过滤的节点
 * @param {node => boolean} predicate 过滤条件，符合条件的节点保留
 * @param {children''} children 子节点名称
 * @return 过滤后的节点
 */
export const _deal = (nodes, predicate,children) => {
  // 如果已经没有节点了，结束递归
  if (!(nodes && nodes.length)) {
      return false;
  }

  const newChildren = [];
  for (const node of nodes) {
      if (predicate(node)) {
          // 如果节点符合条件，直接加入新的节点集
          newChildren.push(node);
          node[children] = _deal(node[children], predicate,children);
      } else {
          // 如果当前节点不符合条件，递归过滤子节点，
          // 把符合条件的子节点提升上来，并入新节点集
          newChildren.push(..._deal(node[children], predicate));

      }
  }

  return newChildren.length !== 0?newChildren:null;
}

/**
 * 两两，三三组合，生成sku的key
 * 接收格式：[[1,2],[3,4]]
 * 输出格式：[1,3],[1,4],[2,3],[2,4]
 */
export const _doExchange = (arr,callback) => {
  let isKey = [];
  let result = [];
  let sku = [];
   doExchange(arr, 0);
  function doExchange(arr, index) {
    for (var i = 0; i < arr[index].length; i++) {
      result[index] = arr[index][i];

      if (index != arr.length - 1) {
        doExchange(arr, index + 1);
      } else {
        result.map(r => {
          // 重新处理数据格式，result已经组合完成
          isKey.push(r);
        });
        // $e.createItemsSku(result, isKey.join(",")); // 生成格式
        // console.dir(JSON.stringify(isKey))
        callback(isKey)
        isKey = []; // 清空临时存放
      }
    }
  }
}

/**
 * 供货商id
 */
export const _supplierId = () => {
  let { supplierId }= localStorage.getItem('info')?JSON.parse(localStorage.getItem('info')):''
  return supplierId
}

export const _uuid = function () {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
}

/**
 * 获取oss token
 */
export const _getOssToken=function() {
	return new Promise((resolve, reject)=> {
		// e.$axios.post("/oss/getOssToken").then((res) => {
      this.$axios.post("/public/ossToken").then((res) => {
      let { code, data} = res.data
			if(code==200){
				// var data=res.data.data;
				// this.uploadHost=data.host;
				let token = {
					'policy': data.policy,
					'OSSAccessKeyId':data.accessKeyId,
					'success_action_status': '200', //让服务端返回200,不然，默认会返回204
					'signature': data.sign,
					'expire_time': data.expireTime,
          "host":data.host
				};
				resolve(token)
			}else{
				reject(res.data)
			}
		}).catch((err)=>{
			reject(err)
		})
	});

}

/**
 * 组装oss 参数
 * file 要上传的文件； label upload框标识（预留）； rules 校验规则； success 获取ossToken成功后的回调；fail 校验失败后的回调；beforeUpload 获取ossToken前的回调
 * rules校验规则请看 FileVerification.js
 */
export const _assembleOss = function(paramsObject) {
  let e = this
  let { file, label, rules, success, fail, beforeUpload } = paramsObject

  // 校验上传文件属性
  return new Promise((resolve, reject) => {
    _beforeUploadCheck(file,label,rules).then(res => {
      let { result, msg } = res

      if(!result){
        e.$notify.error(msg || '请按要求上传文件');
        // e.handleAvatarResult(null, null, label, false)
        fail && fail(result, msg, file)
        // throw new Error('t')
        reject()
      }else{
        beforeUpload && beforeUpload(result)
        _getOssToken
          .call(e, null)
          .then(res => {
            let fileExt = /\.[^\.]+$/.exec(file.name);
            let url = "ROOT/ETao/gl/busiImage/" + _uuid() + fileExt;
            success && success(res,url,file)
            resolve(res);
          }).catch(err => {
            fail && fail()
            reject()
          });
      }
    })

  }).catch(r => {})

}
/**
 * 校验 file
 */
export const _beforeUploadCheck = function(file,label,rules) {
  // let self = this
  // let result = null
  const fv = new FileVerification(file);
  async function getResult(rule){
    let res = { result:true }

    if(!!rule){

      for(let i in rule){
        let val = rule[i]
        if(['vImgPercentage','vImgWH','vImgW','vImgH'].indexOf(i) != -1){
          let r = await fv[i](val[0],val[1])
          res = r
        }else{
          res = fv[i](val)
        }
        if(res && !res.result){
          break
        }

      }

    }
    return res

  }

  return getResult(rules[label])
}

/**
 * localStorage的增加，删除，读取
 * 存储字符串，对象均可
 */
export const _saveStorage = (key,value) => {
  let val = typeof(value) == 'string'?value:JSON.stringify(value)
  localStorage.setItem(key, val);
}
export const _getStorage = (key) => {
  let val = localStorage.getItem(key)
  let checkType = (value) => {
    try {
      JSON.parse(value)
      return true
    } catch (err) {
      return false
    }
  }

  if(val != null){
    return checkType(val)?JSON.parse(val):val
  }
}
export const _removeStorage = (key) => {
  localStorage.removeItem(key)
}


/**
 * 获取地区数据并存到strong
 */
// 获取地区数据
export const _getAreaData = () => {
  return new Promise(resolve => {
    if(!!_getStorage('areaData')){
      return resolve(_getStorage('areaData'))
    }else{

      axios.get('/products/areaDetail').then(r => {
        let { code, data } = r.data
        if(code == 200){
          _saveStorage('areaData',data)
          return resolve(data)
        }
      }).catch(r => console.log(r));

    }
  })
}

/**
 * 区域id转成区域字符串
 * areasAll -> 地区数据 Object；areaIdArrys -> 地区id 逗号String（"XXX,XXX"）；
 */
export const _areaId2AreaString = (areaIdArrys) => {
  async function init(value){
    let areasAll = await _getAreaData()

    // 获取地区数据
    let checkArea = (value) => {
      let arr = value.split(',')
      if(arr.length == 1){
        return areasAll.all.name
      }else{
        let { areas } = areasAll
        let newArr = []

        let get = (z,areas,arr) => {
          for(let i in areas){
            let are = areas[i]
            if(are.code == arr[z]){
              newArr.push(are.name)
              z+=1
              if(z == arr.length){
                return newArr
              }else{
                get(z,are.subAreas,arr)
              }
              break
            }
          }
        }

        get(0,areas,arr)
        return newArr.join(' ')

      }
    }
    return checkArea(value)
  }
  return init(areaIdArrys)
}

/**
 * 校验规则
 *
 */

// 订单列表合并
export const  getOrderRowColum =(dataArr)=>{
	let reslen = [];
	let detailsLen = new Array();
	for(let i=0; i<dataArr.length;i++){
		detailsLen[i] = new Array();
		for(let j = 0;j<dataArr[i].details.length;j++){
				// dataArr[i].details[j].rowIndex =j +1;
				detailsLen[i][j] = j;
		}
	}
	for(let i =0;i<detailsLen.length;i++){
		if(detailsLen[i].length>1){
			reslen.push(detailsLen[i]);
		}
	}
	reslen = reslen.sort(function compare(a, b) {
		return b.length - a.length;
	})
	return reslen;

}
/**
 * 倒计时
 * params: curtime 剩余时间（秒） e 当前this； type 倒计时样式； label 具体字段名称(倒计时接收)；tips 倒计时结束后显示内容
 */
export const _countTimer = ({el,label,time,type:type=1,sendState,tips})=> {
  let e = el
  let curtime = time
  let PadZero = (str) => {
      //补零
      return new RegExp(/^\d$/g).test(str) ? `0${str}` : str;
  }
  if(sendState !== undefined){
    curtime>0?e[sendState] = false:e[sendState]=true
  }
	const timer = setInterval(() => {
		curtime--;
		if (curtime > 0) {
      let _seconds = parseInt(curtime);
      let days,hours, mins, seconds;
      let result = '';
      seconds = parseInt(_seconds % 60)
      mins = parseInt(_seconds % 3600 / 60)
      hours = parseInt(_seconds / 3600 % 24)
      days = parseInt(_seconds / 86400);

      if (type == 1){
        result = `${days}天${PadZero(hours)}小时${PadZero(mins)}分钟${PadZero(seconds)}秒`
        e[label] = result
      }else{
        result = `${curtime} s`
        e[label] = result
      }
      // console.log(result)
      // return result;
      // let endTime = oldTime + curtime
			// day = formate(Math.floor(curtime / (60 * 60 * 24)));
			// hour = formate(Math.floor(curtime / (60 * 60)) - day * 24);
			// minute = formate(
			// 	Math.floor(curtime / 60) - day * 24 * 60 - hour * 60
			// );
			// second = formate(
			// 	Math.floor(curtime) -
			// 		day * 24 * 60 * 60 -
			// 		hour * 60 * 60 -
			// 		minute * 60
			// );

			// var dd =
      // 	day + "天" + hour + "时" + minute + "分" + second + "秒";
      // let time = curtime
      // console.dir(moment(endTime).format('YYYY-MM-DD HH:mm:ss'))
      // console.dir(curtime)
      // debugger
			// e.countdownText = dd;
		} else {
      clearInterval(timer);
      if(curtime==0){
        location.reload()
      }
      if(tips){
        e[label] = tips
      }
      if(sendState !== undefined){
        e[sendState] = true;
      }
		}
	}, 1000);
	return (e.timer = timer);
}
// 自增++
export const _addTimer = ({el,label,time,type:type=1,sendState,tips})=> {
  let e = el
  let curtime = time
  let PadZero = (str) => {
      //补零
      return new RegExp(/^\d$/g).test(str) ? `0${str}` : str;
  }
  if(sendState !== undefined){
    curtime>0?e[sendState] = false:e[sendState]=true
  }
	const timer = setInterval(() => {
		curtime++;
		if (curtime > 0) {
      let _seconds = parseInt(curtime);
      let days,hours, mins, seconds;
      let result = '';
      seconds = parseInt(_seconds % 60)
      mins = parseInt(_seconds % 3600 / 60)
      hours = parseInt(_seconds / 3600 % 24)
      days = parseInt(_seconds / 86400);

      if (type == 1){
        result = `${days}天${PadZero(hours)}小时${PadZero(mins)}分钟${PadZero(seconds)}秒`
        e[label] = result
      }else{
        result = `${curtime} s`
        e[label] = result
      }
      
		} else {
      clearInterval(timer);
      if(tips){
        e[label] = tips
      }
      if(sendState !== undefined){
        e[sendState] = true;
      }
		}
	}, 1000);
	return (e.timer = timer);
}

// 订单详情列表合并
export const getOrderDetailRowColum =(dataArr)=>{
	let detailsLen = new Array();
	 for(let i =0;i<dataArr.length;i++){
			detailsLen[i] = new Array();
			for(let j =0;j<dataArr.length;j++){
					detailsLen[i][j] = j;
			}
	}
	return detailsLen;
}

//合并行
export const osmethod =(orderArr,rowIndex)=> {
	var orderArr = orderArr;
	var rowIndex = rowIndex;
	for(let i = 0;i<orderArr.length;i++){
		let element = orderArr[i];
		for(let j = 0;j<element.length;j++){
			let item = element[j];
			if (rowIndex  == item) {
				if(j==0){
					return {
						rowspan: element.length,
						colspan: 1
					};
				}else if(j !=0){
					return {
						rowspan: 0,
						colspan: 0
					};
				}
			}
		}
	}
}

/**
 * html转化为text，并去掉标签
 */
export const _ToText = (HTML) => {
  let input = HTML;
  return input.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'').replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ');
}

/**
 * 时间格式化
 */
export const _formatDate = (date, format) => {
  var value=new Date(Date.parse(date));
  let o = {
    "M+": value.getMonth() + 1,
    "d+": value.getDate(),
    "h+": value.getHours(),
    "m+": value.getMinutes(),
    "s+": value.getSeconds(),
  }
  if(/(y+)/.test(format)){
    format = format.replace(RegExp.$1, (value.getFullYear() + "").substr(4-RegExp.$1.length));
    for(let k in o) {
      if(new RegExp(`(${k})`).test(format)){
        format = format.replace(RegExp.$1, (RegExp.$1.length == 1)?(o[k]):(("00" + o[k]).substr((""+o[k]).length)))
      }
    }
    return format;
  }
}


/**
 * 订单商品交货期转化
 */
export const _delivery = (type) => {
  let text;
  switch (Number(type)) {
    case 0:
      text = '现货';
      break;
    case 1:
      text = '15天';
      break;
    case 2:
      text = '30天';
      break;
    case 3:
      text = '45天';
      break;
    case 4:
      text = '45天以上';
      break;
    default :
      text = '';
  }
  return text
}

/**
 * 订单状态转化
 */
export const _orderStatus = (type) => {
  let text;
  switch (Number(type)) {
    case 0:
      text = '待付款';
      break;
    case 1:
      text = '待确认';
      break;
    case 2:
      text = '待发货';
      break;
    case 3:
      text = '已发货';
      break;
    case 4:
      text = '已成功';
      break;
    case 5:
      text = '已评论';
      break;
    case 6:
      text = '已关闭';
      break;
    default :
      text = '';
  }
  return text
}

/**
 * 订单支付方式转化
 */
export const _paymentType = (type) => {
  let text;
  switch (Number(type)) {
    case 1:
      text = '支付宝';
      break;
    case 2:
      text = '微信';
      break;
    case 3:
      text = '工商银行';
      break;
    case 4:
      text = '钱包';
      break;
    default :
      text = '';
  }
  return text
}

/**
 * 手机号码验证
 */
export const _regMobile = function (mobile) {
	var myreg = /^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$/;
	if (myreg.test(mobile)) {
		return true;
	} else {
		return false;
	}
}

/**
 * 邮箱验证
 */
export const _regEmail= function (email) {
  //验证邮箱正则
  var re = /^(([^()[\]\\.,;:\s@\"]+(\.[^()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}

export const checkPC = function () {
  var device = navigator.userAgent.toLowerCase();
  if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile|mobile/.test(device)) {
    return false;
  } else {
    return true;
  }
};