export function getWeek(week: any) {
  const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return weeks[week]
}

export function deepCopy(obj: any) {
  const a = JSON.stringify(obj)
  const newobj = JSON.parse(a)
  return newobj
}

export function getStockTwoArray(data: any, type: string) {
  const list: any = []
  data[0].forEach((ele: any, index: number) => {
    let res = {
      stockCode1: ele.stockCode,
      stockName1: ele.stockName,
      value1: `${ele[type]}${type === 'companyNum' ? '家' : ''}`,
      stockCode2: '',
      stockName2: '',
      value2: '',
      stockCode3: '',
      stockName3: '',
      value3: '',
      stockCode4: '',
      stockName4: '',
      value4: ''
    }
    res = getStockOneArray(res, data, 1, index, type)
    res = getStockOneArray(res, data, 2, index, type)
    res = getStockOneArray(res, data, 3, index, type)
    list.push(res)
  })
  return list
}

export function getStockOneArray(res: any, data: any, len: number, index: number, type: string) {
  if (data.length > len && data[len].length > index) {
    res[`stockCode${len + 1}`] = data[len][index].stockCode
    res[`stockName${len + 1}`] = data[len][index].stockName
    res[`value${len + 1}`] = `${data[len][index][type]}${type === 'companyNum' ? '家' : ''}`
  }
  return res
}

export function formatMoney(value: any) {
  const arr = (value + '').split('-')
  const negativeFlag = ''
  value = arr.length === 1 ? arr[0] : arr[1]
  if (value > 100000000) {
    return negativeFlag + Math.round(value / 1000000) / 100 + '亿'
  } else if (value > 10000) {
    return negativeFlag + Math.round(value / 100) / 100 + '万'
  } else {
    return negativeFlag + value
  }
}

export function setDecimalPlaces(value: any, fixedNum: number, multiply = 100, divide = 100) {
  if (value) {
    return (Math.round(value * multiply) / divide).toFixed(fixedNum)
  } else {
    return ''
  }
}

import moment from 'moment'
export function getEchartTime(dateValue: any) {
  let time = ''
  switch (dateValue) {
    case '1':
      time = moment().subtract(10, 'years').format('YYYY-MM-DD')
      break
    case '2':
      time = moment().subtract(1, 'years').format('YYYY-MM-DD')
      break
    case '3':
      time = moment().subtract(6, 'months').format('YYYY-MM-DD')
      break
    case '4':
      time = moment().subtract(3, 'months').format('YYYY-MM-DD')
      break
    case '5':
      time = moment().subtract(1, 'months').format('YYYY-MM-DD')
      break
    case '6':
      time = moment().subtract(1, 'weeks').format('YYYY-MM-DD')
      break
  }
  return time
}

export function sortArr(arr: any) {
  return arr.sort((value1: any, value2: any) => {
    return Date.parse(value1) - Date.parse(value2)
  })
}

export function convertToUrl(obj: any) {
  let url = ''
  for (const key in obj) {
    if (typeof obj[key] === 'number' || obj[key]) {
      url += `&${key}=${obj[key]}`
    }
  }
  return url ? url.slice(1) : ''
}

import userInfoStore from '@/stores/userInfo'
const userInfo = userInfoStore()
export function isAuth(key: string) {
  return userInfo.permissions.indexOf(key) !== -1 || false
}

import * as CryptoJS from 'crypto-js'
export function encrypt(word: any) {
  const keyStr = 'firshshanghai!@#' // 判断是否存在ksy，不存在就用定义好的key
  const key = CryptoJS.enc.Utf8.parse(keyStr)
  const srcs = CryptoJS.enc.Utf8.parse(word)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

export function addOrSubtractTime(date: string | Date, value: number, unit: 'year' | 'month') {
  const currentDate = typeof date === 'string' ? new Date(date) : date;
  const newDate = new Date(currentDate.getTime())
  if (unit === 'year') {
    newDate.setFullYear(newDate.getFullYear() + value)
  } else if (unit === 'month') {
    newDate.setMonth(newDate.getMonth() + value)
  }
  const year = newDate.getFullYear();
  const month = String(newDate.getMonth() + 1).padStart(2, '0')
  const day = String(newDate.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`;
}

export function treeDataTranslate(data: any, id = 'id', pid = 'parentId') {
  const res: any = []
  const temp: any = {}
  for (let i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (let k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

export function formatNumberByUnit (value: any) {
  if (value) {
    value = value.toString()
    const negativeFlag = value.indexOf('-') > -1
    if (value.indexOf('-') > -1) {
      value = value.replaceAll('-', '')
    }
    if (Number(value) >= 100000000) {
      return `${negativeFlag ? '-' : ''}${Math.round(Number(value) / 1000000) / 100 + '亿'}`
    } else if (Number(value) >= 10000) {
      return `${negativeFlag ? '-' : ''}${Math.round(Number(value) / 100) / 100 + '万'}`
    } else {
      return `${negativeFlag ? '-' : ''}${value}`
    }
  } else {
    return ''
  }
}

export function formatNumber (n: any) {
  if (n) {
    n = n.toString()
    const negativeFlag = n.indexOf('-') > -1
    if (n.indexOf('-') > -1) {
      n = n.replaceAll('-', '')
    }
    const numArr = n.toString().split('.')
    const decmial = numArr[1] ? '.' + numArr[1] : ''
    const a = numArr[0]
    const b = parseInt(a).toString()
    const len = a.length
    if (len <= 3) {
      return negativeFlag ? `-${b + decmial}` : b + decmial
    }
    const r = len % 3
    const returnNumber = r > 0
      ? b.slice(0, r) + ',' + (b.slice(r, len).match(/\d{3}/g) || []).join(',') + decmial : (b.slice(r, len).match(/\d{3}/g) || []).join(',') + decmial
    return negativeFlag ? `-${returnNumber}` : returnNumber
  } else {
    return '0'
  }
}

export function padZeroAfterDecimal (num: number) {
  let numStr = num.toString()
  if (numStr.includes('.')) {
    const parts = numStr.split('.')
    let decimalPart = parts[1]
    if (decimalPart.length < 2) {
      decimalPart = decimalPart.padEnd(2, '0')
    } else {
      decimalPart = decimalPart.slice(0, 2)
    }
    numStr = parts[0] + '.' + decimalPart
  } else {
    numStr = numStr + '.00'
  }
  return numStr
}

export function getHtmlByValue(
  val: any,
  unit: any,
  nullStr = '',
  compareVal = 0,
  raiseFlag = '+',
  data?: any,
  color?: any
) {
  if (val === null || val === undefined) return nullStr
  if (parseFloat(val) === compareVal) {
    return `<b style="color: ${color || '#1b9c35'}">${data || val}${unit}</b>`
  } else if (parseFloat(val) > compareVal) {
    return `<b style="color: ${color || 'red'}">${raiseFlag}${data || val}${unit}</b>`
  } else {
    return `<b style="color: ${color || '#07c160'}">${data || val}${unit}</b>`
  }
}
