
import axios from 'axios'
import store from "@/store";

import { downzai } from "@/api/system/config";

const baseURL = '/prod-api' 
    //时间格式转换
    export function dateFormat(date, format) {
        if(!format) {format = 'yyyy-MM-dd hh:mm:ss';}
        if (date !== 'Invalid Date') {
          var o = {
            'M+': date.getMonth() + 1, // month
            'd+': date.getDate(), // day
            'h+': date.getHours(), // hour
            'm+': date.getMinutes(), // minute
            's+': date.getSeconds(), // second
            'q+': Math.floor((date.getMonth() + 3) / 3), // quarter
            'S': date.getMilliseconds() // millisecond
          }
          if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1,
              (date.getFullYear() + '').substr(4 - RegExp.$1.length))
          }
          for (var 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
        }
        return ''
      }

/**
 * 判断是否为空
 */
 export function validatenull(val) {
    if (typeof val === 'boolean') {
      return false
    }
    if (typeof val === 'number') {
      return false
    }
    if (val instanceof Array) {
      if (val.length === 0) return true
    } else if (val instanceof Object) {
      if (JSON.stringify(val) === '{}') return true
    } else {
      if (val === 'null' || val == null || val === 'undefined' || val === undefined || val === '') return true
      return false
    }
    return false
  }
  // 转换字符串，undefined,null等转化为""
  export function praseStrEmpty(str) {
    if (!str || str == "undefined" || str == "null") {
      return "";
    }
    return str;
  }
  /**
 * 根据字典的数值显示对应的汉字
 */
  export const findLabelValueByProp = (dic, value, propl,label) => {
    if (!value) return ""
    const valueArr = (value+'').split(',')
    propl = propl ? propl : 'value';
    label = label ? label : 'label';
    let resultArr = []
    if (validatenull(dic)) return value
    
    valueArr.forEach((it,i) => {
      const index = dic.findIndex(item=>item[propl] == valueArr[i])
      if (index != -1) {
        resultArr.push(dic[index][label])
      }
    })
    return resultArr.join(',')
    // console.log(resultArr.join(','));

    // let idx = dic.findIndex(item=>item[propl] == value);
    // if (idx > -1) { return dic[idx][label] }
    // return  value
  }
/**
 * 根据字典的value显示label
 */
 export const findByvalue = (dic, value) => {
    //  console.log('findByvalue',dic, value)
    let result = ''
    if (validatenull(dic)) return value
    if (typeof (value) === 'string' || typeof (value) === 'number' || typeof (value) === 'boolean') {
      let index = 0
      index = findArray(dic, value)
      if (index !== -1) {
        result = dic[index].label
      } else {
        result = value
      }
    } else if (value instanceof Array) {
      result = []
      let index = 0
      value.forEach(ele => {
        index = findArray(dic, ele)
        if (index !== -1) {
          result.push(dic[index].label)
        } else {
          result.push(value)
        }
      })
      result = result.toString()
    }
    // console.log('result',result)
    return result
  }
/**
 * 根据字典的value查找对应的index
 */
 export const findArray = (dic, value) => {
    for (let i = 0; i < dic.length; i++) {
      if (dic[i].value === value) {
        return i
      }
    }
    return -1
  };

// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = 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]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}
const digitsRE = /(\d{3})(?=\d)/g

export function currency (value, currency, decimals) {
  value = parseFloat(value)
  if (!isFinite(value) || (!value && value !== 0)) return ''
  currency = currency != null ? currency : '$'
  decimals = decimals != null ? decimals : 2
  var stringified = Math.abs(value).toFixed(decimals)
  var _int = decimals
    ? stringified.slice(0, -1 - decimals)
    : stringified
  var i = _int.length % 3
  var head = i > 0
    ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
    : ''
  var _float = decimals
    ? stringified.slice(-1 - decimals)
    : ''
  var sign = value < 0 ? '-' : ''
  return sign + currency + head +
    _int.slice(i).replace(digitsRE, '$1,') +
    _float
}
  // 表单重置   
export function resetForm(refName) {
	if (this.$refs[refName]) {
		this.$refs[refName].resetFields();
	}
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  // console.log(params, dateRange, propName)
	var search = params;
	search.params = {};
	if (null != dateRange && '' != dateRange) {
		if (typeof (propName) === "undefined") {
			search.params["beginTime"] = dateRange[0];
			search.params["endTime"] = dateRange[1];
		} else {
			search.params["begin" + propName] = dateRange[0];
			search.params["end" + propName] = dateRange[1];
		}
	}
	return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
	var actions = [];
	Object.keys(datas).some((key) => {
		if (datas[key].dictValue == ('' + value)) {
			actions.push(datas[key].dictLabel);
			return true;
		}
	})
	return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
	var actions = [];
	var currentSeparator = undefined === separator ? "," : separator;
	var temp = value.split(currentSeparator);
	Object.keys(value.split(currentSeparator)).some((val) => {
		Object.keys(datas).some((key) => {
			if (datas[key].dictValue == ('' + temp[val])) {
				actions.push(datas[key].dictLabel + currentSeparator);
			}
		})
	})
	return actions.join('').substring(0, actions.join('').length - 1);
}

// 都先去掉 baseURL(/prod-api)  打包部署的时候需要加上
// 通用下载方法
export function download(fileName) {
	window.location.href =baseURL + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true;
}
// 通用下载方法
export function downloadHttp(filePath) {
  window.location.href =baseURL + "/common/download/http?filePath=" + encodeURI(filePath) + "&delete=" + false;
}

// 通用下载方法   http://test.console.lovecode.cc/prod-api
export function downloadFast(filePath, loading) {
  //   window.location.href = baseURL + "/common/download/fast?filePath=" + encodeURI(filePath) + "&delete=" + false;
    var url = baseURL + "/common/download/fast?filePath=" + encodeURI(filePath) + "&delete=" + false;
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + store.getters.token }
    }).then(res => {
      try {
      // console.log('res---',res,)
        const aLink = document.createElement('a')
        var blob = new Blob([res.data], {type: 'application/octet-stream'})
        // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
      var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
      // console.log('aLink---',aLink,blob,patt,)
    //   return;
        var contentDisposition = decodeURI(res.headers['content-disposition'])
        var result = patt.exec(contentDisposition)
        var fileName = result[1]
        fileName = fileName.replace(/\"/g, '')
        aLink.href = URL.createObjectURL(blob)
        aLink.setAttribute('download', fileName) // 设置下载文件名称
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink);
        loading.close();
      } catch (e) {
        alert("文件异常，请联系管理员");
        loading.close();
      }
    })
  }
  
/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
	let config = {
		id: id || 'id',
		parentId: parentId || 'parentId',
		childrenList: children || 'children'
	};

	var childrenListMap = {};
	var nodeIds = {};
	var tree = [];

	for (let d of data) {
		let parentId = d[config.parentId];
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = [];
		}
		nodeIds[d[config.id]] = d;
		childrenListMap[parentId].push(d);
	}

	for (let d of data) {
		let parentId = d[config.parentId];
		if (nodeIds[parentId] == null) {
			tree.push(d);
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
}