utils

request

import axios from 'axios'
import { ElNotification } from 'element-plus'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'

const pendingMap = new Map();

function apiHandler(domain) {

  let service = axios.create({
    baseURL: domain || location.origin,
    timeout: 5000,
  })

  service.interceptors.request.use(
    config => {
      if (getToken()) config.headers['Authorization'] = getToken();
      removePending(config);
      addPending(config);
      return config
    },
    error => Promise.reject(error)
  )

  service.interceptors.response.use(
    response => {
      removePending(response.config);
      return response.data
    },
    error => {
      // let { response } = error
      httpErrorStatusHandle(error)
      return Promise.reject(error)
    }
  )

  return service
}

/**
 * 处理异常
 * @param {*} error 
 */
function httpErrorStatusHandle(error) {
  // 处理被取消的请求
  if (axios.isCancel(error)) return console.error('请求的重复请求:' + error.message);
  let message = '';
  if (error && error.response) {
    switch (error.response.status) {
      case 302: message = '接口重定向了!'; break;
      case 400: message = '参数不正确!'; break;
      case 401: message = '您未登录,或者登录已经超时,请先登录!'; break;
      case 403: message = '您没有权限操作!'; break;
      case 404: message = `请求地址出错: ${error.response.config.url}`; break; // 在正确域名下
      case 408: message = '请求超时!'; break;
      case 409: message = '系统已存在相同数据!'; break;
      case 500: message = '服务器内部错误!'; break;
      case 501: message = '服务未实现!'; break;
      case 502: message = '网关错误!'; break;
      case 503: message = '服务不可用!'; break;
      case 504: message = '服务暂时无法访问,请稍后再试!'; break;
      case 505: message = 'HTTP版本不受支持!'; break;
      default: message = '异常问题,请联系管理员!'; break
    }
  }
  if (error.message.includes('timeout')) message = '网络请求超时!';
  if (error.message.includes('Network')) message = window.navigator.onLine ? '服务端异常!' : '您断网了!';
  ElNotification({
    position: 'bottom-right',
    title: '提示',
    message: error.response?.data?.message || message,
    type: 'error',
  })
  if ([401, 403].indexOf(error.response?.status) >= 0) {
    removeToken()
    window.sessionStorage.removeItem('userInfo')
    // location.reload()
    router.push({ name: 'login' })
  }
}
/**
 * 生成每个请求唯一的键
 * @param {*} config 
 * @returns string
 */
function getPendingKey(config) {
  let { url, method, params, data } = config;
  if (typeof data === 'string') data = JSON.parse(data); // response里面返回的config.data是个字符串对象
  return [url, method, JSON.stringify(params), JSON.stringify(data)].join('&');
}

/**
 * 储存每个请求唯一值, 也就是cancel()方法, 用于取消请求
 * @param {*} config 
 */
function addPending(config) {
  const pendingKey = getPendingKey(config);
  config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => {
    if (!pendingMap.has(pendingKey)) {
      pendingMap.set(pendingKey, cancel);
    }
  });
}

/**
 * 删除重复的请求
 * @param {*} config 
 */
function removePending(config) {
  const pendingKey = getPendingKey(config);
  if (pendingMap.has(pendingKey)) {
    const cancelToken = pendingMap.get(pendingKey);
    cancelToken(pendingKey);
    pendingMap.delete(pendingKey);
  }
}
export default apiHandler

auth


import { ElNotification } from 'element-plus';
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        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(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}
/**
 * @description: 计算时间差
 * @param  [time] date
 */
export function get_time_diff(time) {
  var diff = '';
  // time = time / 1000
  var time_diff = new Date().getTime() - time; //时间差的毫秒数 

  //计算出相差天数 
  var days = Math.floor(time_diff / (24 * 3600 * 1000));
  if (days > 0) {
    diff += days + '天';
  }
  //计算出小时数 
  var leave1 = time_diff % (24 * 3600 * 1000);
  var hours = Math.floor(leave1 / (3600 * 1000));
  if (hours > 0) {
    diff += hours + '小时';
  } else {
    if (diff !== '') {
      diff += hours + '小时';
    }
  }
  //计算相差分钟数 
  var leave2 = leave1 % (3600 * 1000);
  var minutes = Math.floor(leave2 / (60 * 1000));
  if (minutes > 0) {
    diff += minutes + '分';
  } else {
    if (diff !== '') {
      diff += minutes + '分';
    }
  }
  //计算相差秒数 
  var leave3 = leave2 % (60 * 1000);
  var seconds = Math.round(leave3 / 1000);
  if (seconds > 0) {
    diff += seconds + '秒';
  } else {
    if (diff !== '') {
      diff += seconds + '秒';
    }
  }

  return diff;
}
// 7.是否boolean
export const isBoolean = (o) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean';
};
// 11.是否对象
export const isObj = (o) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Object';
};
// 12.是否数组
export const isArray = (o) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Array';
};
//验证密码
export const isPass = (s) => {
  const PASS_REG = /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$)([^\u4e00-\u9fa5\s]){6,20}$/
  // const PASS_REG =
  //     /((^(?=.*[a-z])(?=.*[A-Z])(?=.*\W)[\da-zA-Z\W]{8,32}$)|(^(?=.*\d)(?=.*[A-Z])(?=.*\W)[\da-zA-Z\W]{8,32}$)|(^(?=.*\d)(?=.*[a-z])(?=.*\W)[\da-zA-Z\W]{8,32}$)|(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z\W]{8,32}$))/;
  return PASS_REG.test(s);
};
/**
 * @description: 封装sessionStorage和localStorage
 * @param {*}
 * @return {*}
 */
export const storage = {
  setLocal: (key, value) => {
    if (isArray(value) || isObj(value) || isBoolean(value)) {
      window.localStorage.setItem(key, JSON.stringify(value));
    } else {
      window.localStorage.setItem(key, value);
    }
  },
  getLocal: (key) => {
    let value = window.localStorage.getItem(key);
    if (value) {
      return JSON.parse(value);
    } else {
      return value;
    }
  },
  clearOneLocal: (key) => {
    window.localStorage.removeItem(key);
  },
  clearAllLocal: () => {
    // indexDBStore 不清除
    const indexDBStore = storage.getLocal('indexDBStore');
    window.localStorage.clear();
    storage.setLocal('indexDBStore', JSON.stringify(indexDBStore));
  },
  setSession: (key, value) => {
    //正常设置,会覆盖原值
    if (isArray(value) || isObj(value) || isBoolean(value)) {
      window.sessionStorage.setItem(key, window.btoa(window.encodeURIComponent(JSON.stringify(value))));
    } else {
      window.sessionStorage.setItem(key, window.btoa(window.encodeURIComponent(value)));
    }
    // window.sessionStorage.setItem(key, JSON.stringify(value))
  },
  appendSession: (key, value) => {
    //追加赋值,不会覆盖原值
    let getValue = window.sessionStorage.getItem(key);
    if (getValue) {
      let oldValue = JSON.parse(getValue);
      let newValue = Object.assign(oldValue, value);
      window.sessionStorage.setItem(key, JSON.stringify(newValue));
    } else {
      window.sessionStorage.setItem(key, JSON.stringify(value));
    }
  },
  getSession: (key) => {
    //需要判断取值格式,如果是string或者undefined,不能JSON.PARSE()
    let value = window.sessionStorage.getItem(key);
    if (!value) {
      return value;
    } else {
      try {
        if (
          isArray(JSON.parse(window.decodeURIComponent(window.atob(value)))) ||
          isObj(JSON.parse(window.decodeURIComponent(window.atob(value))))
        ) {
          return JSON.parse(window.decodeURIComponent(window.atob(value)));
        } else {
          if (window.decodeURIComponent(window.atob(value)) == 'true') {
            return true;
          } else if (window.decodeURIComponent(window.atob(value)) == 'false') {
            return false;
          } else {
            return window.decodeURIComponent(window.atob(value));
          }
        }
      } catch (e) {
        return window.decodeURIComponent(window.atob(value));
      }
    }
  },
  clearOneSession: (key) => {
    window.sessionStorage.removeItem(key);
  },
  clearAllSession: () => {
    window.sessionStorage.clear();
  }
};
/**
 * @description: JSON数组去重
 * @param [array] json Array
 * @param: [string] 唯一的key名,根据此键名进行去重
 */
export function uniqueArray(array, key) {
  var result = [];
  for (var i = 0; i < array.length; i++) {
    var item = array[i];
    var repeat = false;
    for (var j = 0; j < result.length; j++) {
      if (item[key] == result[j][key]) {
        repeat = true;
        break;
      }
    }
    if (!repeat && item[key]) {
      result.push(item);
    }
  }
  return result;
}

/**
 * @description: 复制
 * @param String
 */
// import useClipboard from "vue-clipboard3";
// const { toClipboard } = useClipboard();
export function copyUrl(url, isNotice = true) {
  // var url = JSON.stringify(t)
  // console.log(url)
  if (url) {
    // try {
    //     toClipboard(url)
    // } catch (error) {
    var input = document.createElement('input');
    document.body.appendChild(input);
    input.setAttribute('value', url);
    input.select();
    document.execCommand("copy"); // 执行浏览器复制命令
    if (document.execCommand('copy')) {
      document.execCommand('copy');
    }
    // }
    if (isNotice) {
      ElNotification({
        position: 'bottom-right',
        title: '提示',
        type: 'success',
        message: '复制成功'
      })
    }
    document.body.removeChild(input);
  } else {
    ElNotification({
      position: 'bottom-right',
      title: '提示',
      type: 'warning',
      message: '不能复制空'
    })
  }
}
/**
 * @description: 文件大小转换
 * @param bytes 
 * @param decimalPoint 
 */
export function formatFileSize(bytes, decimalPoint = 2) {
  if (bytes == 0) return "0 Bytes";
  let k = 1000,
    sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
    i = Math.floor(Math.log(bytes) / Math.log(k));
  return (
    parseFloat((bytes / Math.pow(k, i)).toFixed(decimalPoint)) + " " + sizes[i]
  );
}
/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在,重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}
/**
 * @param {Function} fu
 * @param {number} delay
 * @return {*}
 */
export function throttle(fn, delay) {
  var ctx;
  var args;
  // 记录上次触发事件
  var previous = Date.now();

  var later = function () {
    fn.apply(ctx, args);
  };

  return function () {
    ctx = this;
    args = arguments;
    var now = Date.now();
    // 本次事件触发与上一次的时间比较
    var diff = now - previous - delay;

    // 如果隔间时间超过设定时间,即再次设置事件触发的定时器
    if (diff >= 0) {
      // 更新最近事件触发的时间
      previous = now;
      setTimeout(later, delay);
    }
  };
}
/**
 * @description 数据分组
 * @param { array } array 需要进行分组的数据
 * @param { string } key 进行分组时依据的键名
 * @param { string } resKey 分组后数据的键名,默认为 list
 * @returns { array } 一维数组形式
 */
export function GroupingToArray(array, key, resKey = "list") {
  if (!key) return array;
  var aMap = [];
  var aResult = [];
  for (var i = 0; i < array.length; i++) {
    var item = array[i];
    if (aMap.indexOf(item[key]) === -1) {
      var oItem = {};
      oItem[resKey] = [item];
      oItem[key] = item[key];
      aResult.push(oItem);
      aMap.push(item[key]);
    } else {
      var index = aMap.indexOf(item[key]);
      aResult[index][resKey].push(item);
    }
  }
  return aResult;
}
/**
 * @param {Array} 
 * @returns {Number}
 * 获取两个时间相隔多少天
 */
export function datedifference([sDate1, sDate2]) {
  //sDate1和sDate2是2006-12-18格式
  var dateSpan, tempDate, iDays;
  sDate1 = typeof sDate1 == 'number' ? sDate1 : Date.parse(sDate1);
  sDate2 = typeof sDate2 == 'number' ? sDate2 : Date.parse(sDate2);
  dateSpan = sDate2 - sDate1;
  dateSpan = Math.abs(dateSpan);
  iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
  return iDays;
}
/**
 * @param {Number} 
 * @returns {String}
 * 获取当前时间前后某一天
 */
export function getDay(day) {
  //处理时间函数
  const doHandleMonth = month => {
    var m = month;
    if (month.toString().length == 1) {
      m = "0" + month;
    }
    return m;
  };
  var today = new Date();
  var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
  today.setTime(targetday_milliseconds); //注意,这行是关键代码
  var tYear = today.getFullYear();
  var tMonth = today.getMonth();
  var tDate = today.getDate();
  tMonth = doHandleMonth(tMonth + 1);
  tDate = doHandleMonth(tDate);
  return tYear + "-" + tMonth + "-" + tDate;
}

 //轮询
   let a = 0
    async function getreadMessage() {
      console.log('轮询', ++a);
    }
    const STATUS_INTERVAL = 1.5 * 1000
    const queryOrderStatus = () => {
      setTimeout(async () => {
        await getreadMessage()
        queryOrderStatus();
      }, STATUS_INTERVAL);
    };

index

import { removeRouteList } from '@/router/index'
import { useRouterList } from '@/stores/modules/routerList'
import { useUserInfo } from '@/stores/modules/userInfo'
import { ElMessage, ElMessageBox } from 'element-plus'
import Decimal from 'decimal.js'

import { h } from 'vue'
import { useRouter } from 'vue-router'
export function times(data: number, flag = 0) {
  // let data = "8029775.01";
  const time = Number(data)
  const d = Math.floor(time / 86400)
  let h: number | string = Math.floor((time % 86400) / 3600)
  let m: number | string = Math.floor(((time % 86400) % 3600) / 60)
  const s = ((time % 86400) % 3600) % 60
  if (flag === 1) {
    // 把超过时的转为时
    d > 0 && (h += d * 24)
    return (h ? h + '时' : '') + (m ? m + '分' : '') + (s ? s + '秒' : '')
  } else if (flag === 2) {
    d > 0 && (h += d * 24)
    m = m < 10 ? '0' + m : m
    h = h < 10 ? '0' + h : h
    return (h ? h : '') + (m ? ':' + m : '') + (s ? ':' + s : '')
  }
  return (d > 0 ? d + '天' : '') + (h ? h + '时' : '') + (m ? m + '分' : '') + (s ? s + '秒' : '')
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(
  time: number | Date | string,
  cFormat: string = '{y}-{m}-{d} {h}:{i}:{s}'
) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        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(/{([ymdhisa])+}/g, (result, key: string) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

export const changeByte = (byte: number) => {
  let size = ''
  if (byte < 1 * 1024) {
    // 小于1KB,则转化成B
    size = `${byte.toFixed(2)}B`
  } else if (byte < 1 * 1024 * 1024) {
    // 小于1MB,则转化成KB
    size = `${(byte / 1024).toFixed(2)}KB`
  } else if (byte < 1 * 1024 * 1024 * 1024) {
    // 小于1GB,则转化成MB
    size = `${(byte / (1024 * 1024)).toFixed(2)}MB`
  } else if (byte < 1 * 1024 * 1024 * 1024 * 1024) {
    // 小于1TB,则转化成GB
    size = `${(byte / (1 * 1024 * 1024 * 1024)).toFixed(2)}GB`
  } else {
    // 其他转化成TB
    size = `${(byte / (1024 * 1024 * 1024 * 1024)).toFixed(2)}TB`
  }

  const sizeStr = `${size}` // 转成字符串
  const index = sizeStr.indexOf('.') // 获取小数点处的索引
  const dou = sizeStr.substr(index + 1, 2) // 获取小数点后两位的值
  // eslint-disable-next-line eqeqeq
  if (dou == '00') {
    // 判断后两位是否为00,如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size
}

export const changebyte = (byte: number) => {
  let size = ''
  if (byte < 1 * 1024) {
    // 小于1KB,则转化成B
    size = `${byte.toFixed(2)}b`
  } else if (byte < 1 * 1024 * 1024) {
    // 小于MB,则转化成KB
    size = `${(byte / 1024).toFixed(2)}Kb`
  } else if (byte < 1 * 1024 * 1024 * 1024) {
    // 小于1GB,则转化成MB
    size = `${(byte / (1024 * 1024)).toFixed(2)}Mb`
  } else if (byte < 1 * 1024 * 1024 * 1024 * 1024) {
    // 小于1TB,则转化成GB
    size = `${(byte / (1 * 1024 * 1024 * 1024)).toFixed(2)}G`
  } else {
    // 其他转化成TB
    size = `${(byte / (1024 * 1024 * 1024 * 1024)).toFixed(2)}Tb`
  }

  const sizeStr = `${size}` // 转成字符串
  const index = sizeStr.indexOf('.') // 获取小数点处的索引
  const dou = sizeStr.substr(index + 1, 2) // 获取小数点后两位的值
  // eslint-disable-next-line eqeqeq
  if (dou == '00') {
    // 判断后两位是否为00,如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size
}

/**
 *
 * 获取
 */
export function curTime() {
  //获取当前时间
  // eslint-disable-next-line no-var
  var date: string | any = new Date()
  let month: number | any = date.getMonth() + 1
  let strDate: number | any = date.getDate()
  month = month < 10 ? '0' + month : month
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  let getTimes: string | number =
    date.getFullYear() +
    '-' +
    month +
    '-' +
    strDate +
    ' ' +
    date.getHours() +
    ':' +
    date.getMinutes() +
    ':' +
    date.getSeconds()

  // eslint-disable-next-line no-var
  var date: string | any = new Date(getTimes)
  const time3 = Date.parse(date) //只能精确到秒,毫秒用000替代
  getTimes = Number(time3 / 1000)
  return getTimes
}

export function timePicker(time: number, flag = false, string = false) {
  let timeSu = null
  if (string) {
    timeSu = new Date(time).valueOf()
  } else {
    timeSu = time
  }
  let length = (timeSu + '').length
  const times = new Date(length > 10 ? timeSu : timeSu * 1000)
  let date = !flag
    ? `${times.getFullYear()}-${
        times.getMonth() < 10 ? '0' + (times.getMonth() + 1) : times.getMonth() + 1
      }-${times.getDate() < 10 ? '0' + times.getDate() : times.getDate()}${' '}${
        times.getHours() < 10 ? '0' + times.getHours() : times.getHours()
      }:${times.getMinutes() < 10 ? '0' + times.getMinutes() : times.getMinutes()}:${
        times.getSeconds() < 10 ? '0' + times.getSeconds() : times.getSeconds()
      }`
    : `${times.getFullYear()}-${
        times.getMonth() < 10 ? '0' + (times.getMonth() + 1) : times.getMonth() + 1
      }-${times.getDate() < 10 ? '0' + times.getDate() : times.getDate()}`
  return date
}

/**
 * execCommand 方法复制
 * @param text 复制文本
 */
const fallbackCopyTextToClipboard = (text: string) => {
  // 1.创建一个可选中元素
  let textArea = document.createElement('textarea')
  textArea.value = text
  // 2.使用定位,阻止页面滚动
  textArea.style.top = '0'
  textArea.style.left = '0'
  textArea.style.position = 'fixed'
  document.body.appendChild(textArea)
  textArea.focus()
  textArea.select()
  try {
    var successful = document.execCommand('copy')
    var msg = successful ? 'successful' : 'unsuccessful'
    ElMessage.success('复制成功')
    console.log('Fallback: Copying text command was ' + msg)
  } catch (err) {
    ElMessage.error('复制失败')
    console.error('Fallback: Oops, unable to copy', err)
  }
  // 3.移除元素
  document.body.removeChild(textArea)
}
/**
 * navigator 方法复制 兼任
 * @param text 复制文本
 */
export function copyTextToClipboard(text: string) {
  if (!navigator.clipboard) {
    fallbackCopyTextToClipboard(text)
    return
  }
  navigator.clipboard.writeText(text).then(
    function () {
      ElMessage.success('复制成功')
      console.log('Async: Copying to clipboard was successful!')
    },
    function (err) {
      ElMessage.error('复制失败')
      console.error('Async: Could not copy text: ', err)
    }
  )
}
export const getTimeRangeTimestamp = (range: string) => {
  const now = new Date()
  now.setHours(0, 0, 0, 0) // 设置为当天的 00:00:00
  const startTimestamp = now.getTime()

  switch (range) {
    case 'day':
      const nowTime = new Date()
      return [startTimestamp, Math.floor(nowTime.getTime() / 1000) * 1000 - 1000] // 当天的 00:00:00 到 当时
    case 'dayAll':
      const endTimestamp = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate(),
        23,
        59,
        59
      ).getTime()
      return [startTimestamp, endTimestamp] // 当天的 00:00:00 到 23:59:59
    case 'today':
      const yesterday = new Date(startTimestamp - 24 * 60 * 60 * 1000)
      yesterday.setHours(0, 0, 0, 0) // 设置为昨天的 00:00:00
      return [yesterday.getTime(), startTimestamp - 1000] // 昨天的 00:00:00 到 23:59:59
    case 'toweek':
      return [startTimestamp - 6 * 24 * 60 * 60 * 1000, startTimestamp + 24 * 60 * 60 * 1000 - 1000] // 7天前的 00:00:00 到 当天的 23:59:59
    // 15日
    case 'threemonth':
      return [
        startTimestamp - 14 * 24 * 60 * 60 * 1000,
        startTimestamp + 24 * 60 * 60 * 1000 - 1000
      ] // 15天前的 00:00:00 到 当天的 23:59:59
    case 'tomonth':
      return [
        startTimestamp - 29 * 24 * 60 * 60 * 1000,
        startTimestamp + 24 * 60 * 60 * 1000 - 1000
      ] // 30天前的 00:00:00 到 当天的 23:59:59
    default:
      return null
  }
}
let loginOutTimer: any
function debounce(func: () => void, delay: number) {
  return function () {
    const context = this
    const args = arguments
    clearTimeout(loginOutTimer)
    loginOutTimer = setTimeout(() => {
      func.apply(context, args)
    }, delay)
  }
}
const debounceLoginOut = debounce((): void => {
  useRouterList().removeCacheList()
  useUserInfo().removeUserInfo()
  removeRouteList()
}, 100)
export const loginOut = debounceLoginOut
/**
 * 数字向上保留固定位数方法
 * @param num 数字
 * @param s 保留几位小数
 */
export const decimal_up = (num: number | string, s: number = 2) => {
  return Number(new Decimal(num || 0).toFixed(s, Decimal.ROUND_UP))
}

/**
 * 乘法
 * @param arguments 数字
 *
 */
export const decimal_mul = function (...args: (number | Decimal | string)[]) {
  if (args.length === 0) {
    return 0 // 如果没有传入参数,则返回 0
  }
  const result = args.reduce((accumulator, currentValue) => {
    if (typeof currentValue === 'number' || typeof currentValue === 'string') {
      return new Decimal(accumulator as number).mul(new Decimal(currentValue))
    } else {
      return accumulator
    }
  }, 1)

  return result
}

/**
 * 四舍五入 保留两位小数
 * @param num 数字 字符串
 *
 */
export const decimal_round_half = function (num: number | string | null | undefined) {
  if (!num) {
    return 0 // 如果没有传入参数,则返回 0
  }
  return new Decimal(num).toFixed(2, Decimal.ROUND_HALF_UP).toString()
}

/**
 * 舍 保留sum位小数
 * @param num 数字 字符串
 * @param n 数字 字符串
 * @param sum 数字 字符串
 */
export const decimal_round_Fixed = function (
  num: number | string | null | undefined,
  a: number | string = 1,
  sum: number = 2
) {
  if (!num) {
    return 0 // 如果没有传入参数,则返回 0
  }
  return new Decimal(decimal_mul(num, a)).toFixed(sum, Decimal.ROUND_DOWN).toString()
}

export const defaultTimeSelect: [Date, Date] = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
]
const elementButtonType = {
  danger: {
    confirmButtonClass: 'el-button--danger',
    icon: 'iconfont icon-changguitishi message-icon-danger'
  },
  primary: {
    confirmButtonClass: 'el-button--primary',
    icon: 'iconfont icon-changguitishi message-icon message-icon-primary'
  },
  info: {
    confirmButtonClass: 'el-button--primary',
    icon: 'iconfont icon-toastjinggao message-icon message-icon-info'
  },
  warning: {
    confirmButtonClass: 'el-button--primary',
    icon: 'iconfont icon-toastjinggao  message-icon-warning'
  }
}
export const myMessage = (
  {
    msg,
    title = '删除',
    successText,
    error,
    type = 'danger'
  }: {
    msg: string
    title: string
    successText?: string
    error?: (err: any) => void
    type?: 'primary' | 'danger' | 'warning'
  },
  confirm?: () => Promise<any>
) => {
  ElMessageBox({
    title: title,
    message: h('div', null, [
      h(
        'div',
        {
          class: 'dialog-box',
          style: 'display:flex; justify-content: center;align-items: center;'
        },
        [
          h('span', {
            class: elementButtonType[type].icon,
            'aria-hidden': 'true',
            style: 'margin-right:10px'
          }),
          h('span', null, msg)
        ]
      )
    ]),
    showCancelButton: true,
    confirmButtonText: '确定',

    confirmButtonClass: elementButtonType[type].confirmButtonClass,
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.cancelButtonLoading = true
        confirm &&
          confirm()
            .then((res) => {
              ElMessage.success(successText || '删除成功')
              done()
            })
            .catch((err) => {
              error && error(err)
            })
            .finally(() => {
              instance.confirmButtonLoading = false
              instance.cancelButtonLoading = false
            })
      } else {
        done()
      }
    }
  })
}
export const payType: any = {
  wechat: {
    label: '微信支付',
    icon: '#icon-weixin',
    title: '微信'
  },
  ali_pay: {
    label: '支付宝',
    icon: '#icon-zhifubao',
    title: '支付宝'
  },
  e_bank: {
    label: '网银',
    icon: '#icon-wangyin',
    title: '网银'
  },
  USDT: {
    label: 'USDT',
    icon: '#icon-usdt',
    title: 'USDT'
  },
  dcep: {
    label: '数字人名币',
    icon: '#icon-usdt',
    title: '数字人名币'
  }
}
/**
 * 获取通道类型
 * @param type 类型值
 * @param icon
 */
export const getPayType = (type: string, icon: boolean = false) => {
  return payType[type]
}

export const rulesObj = {
  userNameRule: function (rule: any, value: string, callback: (arg0?: Error | undefined) => void) {
    if (/^[A-Za-z0-9-\u4e00-\u9fa5]{4,30}$/.test(value) == false) {
      callback(new Error('不能输入特殊符号和空格'))
    } else {
      //校验通过
      callback()
    }
  },
  // 非汉字验证
  urlRules: function (rule: any, value: string, callback: (arg0?: Error | undefined) => void) {
    if (/[\u4e00-\u9fa5]/.test(value) == true) {
      callback(new Error('请输入合法字符'))
    } else {
      //校验通过
      callback()
    }
  }
}
/**
 * 复合搜索框
 * @param array 选择的数组
 * @param param 需要附加的对象
 */
export const getParamsByAction = (array: Array<any>, param: any) => {
  array.forEach((item: any) => {
    if (item.keys instanceof Array) {
      item.keys.forEach((key: string, index: number) => {
        if (item.type === 'date') param[key] = Number(item.value[index]) || null
        else {
          param[key] = item.value[index]
        }
      })
    } else {
      if (item.type === 'number') param[item.key] = Number(item.value)
      else param[item.key] = item.value
    }
  })
}
export const pathToUrl = (path: string, query?: { [key: string]: string }) => {
  const router = useRouter()
  console.log(router)
  if (path)
    router.push({
      path,
      query
    })
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值