/*
 * @Author: wyd
 * @Date: 2024-02
 * @LastEditors: JiangChunMei
 * @LastEditTime: 2024-06-24 17:27:10
 * @Description: 公共方法
 */
import { round } from 'lodash'
import { useGlobal } from '@/composables'
import { getListByIdsApi } from '@/api/system'
type Icon = 'success' | 'loading' | 'error' | 'none' | 'fail' | 'exception' | undefined

/**
 * @description: 轻提示
 * @param {string} title 提示内容
 * @param {Icon} icon 提示图标
 * @param {number} duration 提示的延迟时间
 * @return {*}
 */
export const message = (title: string, icon: Icon = 'none', duration: number = 1500) => {
  if (!title) {
    return
  }
  return uni.showToast<UniApp.ShowToastOptions>({
    icon,
    title,
    duration,
    mask: true
  })
}

/**
 * @description: 页面跳转
 * @param {string} url 路由
 * @return {*}
 */
export const routeTo = (url: string) => {
  if (!url) return
  // #ifdef H5
  url.indexOf('http') > 0 && (window.location.href = url)
  // #endif
  uni.navigateTo<UniApp.NavigateToOptions>({
    url,
    fail() {
      uni.switchTab({ url })
    }
  })
}

/**
 * 获取页面栈(默认当前页)
 * @param {Number} preIndex
 */
export const getPrePage = (preIndex = 0) => {
  const pages = getCurrentPages()
  const prePage = pages[pages.length - (preIndex + 1)]
  return prePage
}

/**
 * @description: 文件|图片预览
 * @param {string} url 文件地址
 * @return {*}
 */
export const openFile = (url: string, isPrivate: boolean, previewList?: EmptyArrayType) => {
  if (!url) return
  if (isPrivate) {
    getListByIdsApi(url).then((res) => {
      if (res.data && res.data.length) {
        const arr = res.data[0].url.toLowerCase().split('.')
        const imgtype = arr[arr.length - 1]
        showFile([res.data[0].url], imgtype, previewList ? res.data.map((item) => item.url) : previewList)
      }
    })
  } else {
    const arr = url.toLowerCase().split('.')
    const imgtype = arr[arr.length - 1]
    let path = ['']
    if (url.indexOf('http') === -1) {
      url = useGlobal().pathPre + url
    }
    path = [url]
    showFile(path, imgtype, previewList)
  }
}

const showFile = (path: string[], imgtype: string, previewList?: EmptyArrayType) => {
  // 多图预览
  if (previewList && previewList.length) {
    path = previewList.map((item) => {
      if (item.indexOf('http') === -1) {
        item = useGlobal().pathPre + item
      }
      return item
    })
  }
  //#ifndef H5
  uni.downloadFile<UniApp.DownloadFileOption>({
    url: path[0],
    success: function (res) {
      const filePath = res.tempFilePath
      if (imgtype.indexOf('jpg') !== -1 || imgtype.indexOf('jpeg') !== -1 || imgtype.indexOf('png') !== -1 || imgtype.indexOf('gif') !== -1) {
        // 图片
        uni.previewImage<UniApp.PreviewImageOptions>({
          current: 0,
          urls: path,
          fail: (err) => {
            message('图片打开失败')
          }
        })
      } else {
        // 文件
        uni.openDocument<UniApp.OpenDocumentOptions>({
          filePath: filePath,
          success: (res) => {},
          fail: (res) => {
            message('文件打开失败')
          }
        })
      }
    },
    fail: (err) => {
      message('打开失败')
    }
  })
  //#endif
  //#ifdef H5
  //如果是浏览器走这里
  window.open(path[0], '_blank')
  // window.location.assign(url);
  //#endif
}

/**
 * 判断两数组字符串是否相同（用于按钮权限验证），数组字符串中存在相同时会自动去重（按钮权限标识不会重复）
 * @param news 新数据
 * @param old 源数据
 * @returns 两数组相同返回 `true`，反之则反
 */
export function judementSameArr(newArr: unknown[] | string[], oldArr: string[]): boolean {
  const news = removeDuplicate(newArr)
  const olds = removeDuplicate(oldArr)
  let count = 0
  const leng = news.length
  for (const i in olds) {
    for (const j in news) {
      if (olds[i] === news[j]) count++
    }
  }
  return count === leng ? true : false
}

/**
 * 数组、数组对象去重
 * @param arr 数组内容
 * @param attr 需要去重的键值（数组对象）
 * @returns
 */
export function removeDuplicate(arr: EmptyArrayType, attr?: string) {
  if (!Object.keys(arr).length) {
    return arr
  } else {
    if (attr) {
      const obj: EmptyObjectType = {}
      return arr.reduce((cur: EmptyArrayType[], item: EmptyArrayType) => {
        obj[item[attr]] ? '' : (obj[item[attr]] = true && item[attr] && cur.push(item))
        return cur
      }, [])
    } else {
      return [...new Set(arr)]
    }
  }
}

/**
 * @description: 格式化数组
 * @return {*}
 */
export const formatArray = (data: EmptyArrayType, id = 'id', name = 'name', children = 'children') => {
  data.map((item) => {
    item.value = (id && item[id]) || ''
    item.text = (name && item[name]) || ''
    if (children && item[children]) {
      item.children = item[children]
      formatArray(item.children, id, name, children)
    }
  })
  return data
}

/**
 * @description: 过滤对象中为空的属性
 * @return {*}
 */
export const filterObject = (data: EmptyObjectType) => {
  for (const key in data) {
    if (!data[key]) {
      delete data[key]
    }
  }
  return data
}

/**
 * @description: 格式化富文本图片
 * @return {*}
 */
export const formatRichTextImg = (html: string) => {
  // let newContent = html.replace(/<text[^>]*>/gi, function (match, capture) {
  //   match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')
  //   return match
  // })
  let newContent = html
  // newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
  //   match = match
  //     .replace(/width:[^;]+;/gi, 'max-width:100%;')
  //     .replace(/width:[^;]+;/gi, 'max-width:100%;')
  //   match = match
  //     .replace(/line-height:[^;]+;/gi, 'line-height:24px;')
  //     .replace(/line-height:[^;]+;/gi, 'line-height:24px;')
  //   match = match
  //     .replace(/font-size:[^;]+;/gi, 'font-size:12px !important;')
  //     .replace(/font-size:[^;]+;/gi, 'font-size:12px !important;')
  //   match = match
  //     .replace(/color:[^;]+;/gi, 'color:#545869;')
  //     .replace(/color:[^;]+;/gi, 'color:#545869;')
  //   match = match
  //     .replace(/background-color:[^;]+;/gi, 'background-color:#fff;')
  //     .replace(/background-color:[^;]+;/gi, 'background-color:#fff;')
  //   match = match
  //     .replace(/font-family:[^;]+;/gi, 'font-family:Microsoft YaHei;')
  //     .replace(/font-family:[^;]+;/gi, 'font-family:Microsoft YaHei;')
  //   return match
  // })
  // newContent = newContent
  //   .replace(/width="[^"]+"/gi, 'max-width:100%;')
  //   .replace(/width='[^']+'/gi, 'max-width:100%;')
  // 给没有style的标签添加style
  const regex1 = new RegExp('(i?)(<p)(?!(.*?style=[\'"](.*)[\'"])[^>]+>)', 'gmi')
  newContent = String(newContent).replace(regex1, '$2 style=""$3')
  // const regex2 = new RegExp('(i?)(<p.*?style=[\'"])([^>]+>)', 'gmi')
  // newContent = newContent.replace(
  //   regex2,
  //   '$2font-size:12px !important;line-height:24px !important;color:#545869;font-family:Microsoft YaHei;$3'
  // )
  // const regex3 = new RegExp('(i?)(<a)(?!(.*?style=[\'"](.*)[\'"])[^>]+>)', 'gmi')
  // newContent = newContent.replace(regex3, '$2 style=""$3')
  // const regex4 = new RegExp('(i?)(<a.*?style=[\'"])([^>]+>)', 'gmi')
  // newContent = newContent.replace(
  //   regex4,
  //   '$2font-size:12px;line-height:24px;color:#545869;font-family:Microsoft YaHei;$3'
  // )
  // newContent =
  //   '<p style="font-size:12px !important;line-height:24px;color:#545869 !important;font-family:Microsoft YaHei !important; background: #fff !important; word-break: break-all !important;">' +
  //   newContent +
  //   '</p>'

  // 去掉img中的style重新赋值

  newContent = newContent.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')
    return match
  })

  newContent = newContent.replace(/\<img/gi, '<img style="width:100% !important;height:auto;display:block;margin-top:0;margin-bottom:0;"')
  return newContent
}

/**
 * @description: 获取当前日期
 * @return {*}
 */
export const getCurDate = () => {
  const dates = new Date()
  const year = dates.getFullYear()
  const month = dates.getMonth() + 1
  const date = dates.getDate()
  const day = dates.getDay()
  const hour = dates.getHours()
  const min = dates.getMinutes()
  const days = ['日', '一', '二', '三', '四', '五', '六']
  return {
    allDate: `${year}-${strFormat(month)}-${strFormat(date)}`,
    date: `${strFormat(month)}-${strFormat(date)}`, // 返回的日期 07-01
    day: `星期${days[day]}`, // 返回的礼拜天数  星期一
    hour: strFormat(hour) + ':' + strFormat(min) // 返回的时钟 08:00
  }
}

// 字符串拼接
const strFormat = (str: number) => {
  return str < 10 ? `0${str}` : str
}

/**
 * @description: 排序
 * @param {*} property
 * @param {*} order des降序 asc升序
 * @return {*}
 */
export const compare = (property: string, order = 'des') => {
  return (a: { [x: string]: string | number }, b: { [x: string]: string | number }) => {
    const value1 = +a[property]
    const value2 = +b[property]
    if (order === 'des') {
      return value1 - value2
    }
    return value2 - value1
  }
}

/**
 *
 * @param arr 树数据
 * @param id 要查找的id值
 * @param findProps 查找的属性id名字
 * @param findNameProps 查找的属性name名字
 * @param childProps  查找的子数据名字
 * @returns  返回所有父节点ID的数组，包含本节点id
 */
export const findParents = (arr: EmptyArrayType, id: string | number, findProps = 'id', findNameProps = 'label', childProps = 'children') => {
  const ids: any[] = []
  const name: any[] = []
  const options: any[] = []
  let going = true
  function recursion(arr: EmptyArrayType, id: string | number, findProps: string, findNameProps: string, childProps: string) {
    arr.forEach((item) => {
      if (!going) return
      ids.push(item[findProps])
      name.push(item[findNameProps])
      options.push(item)
      if (item[findProps] === id) {
        going = false
      } else if (item[childProps]) {
        recursion(item[childProps], id, findProps, findNameProps, childProps)
      } else {
        ids.pop()
        name.pop()
        options.pop()
      }
    })
    if (going) {
      ids.pop()
      name.pop()
      options.pop()
    }
  }
  recursion(arr, id, findProps, findNameProps, childProps)
  return { ids, name, options }
}

/**
 * @description: 复制文本内容
 * @return {*}
 */
export const copyText = (content: string) => {
  if (!content) return
  uni.setClipboardData({
    data: content,
    success: function () {
      console.log('success')
    }
  })
}

/**
 * @description: 获取时间戳
 * @return {*}
 */
export const getTheTime = (time: string) => {
  if (!time) return
  time = time.replace('-', '/')
  const date = new Date(time)
  return date.getTime()
}

/**
 * @description: 图表-计算比例
 * @return {*}
 */
export const getChartsRate = (val: number, arr: EmptyObjectType[], valueKey = 'value') => {
  if (!+val || !arr || !arr.length) return 0
  let sum = 0
  arr.map((item) => {
    sum += item[valueKey]
  })
  return round((val / sum) * 100, 2)
}
