import Taro from '@tarojs/taro'
import type { SelectorQuery } from '@tarojs/taro/types/index'
import { formatImgUrl } from './format'
import { analysisShortCodeApi } from './shortCode'
/**
 * 防抖
 * @param {*} fn
 * @param {*} delay
 * @returns
 */
export const debounce = (fn, delay) => {
  let timer: any = null
  return (...param) => {
    if (timer) { clearTimeout(timer) }
    timer = setTimeout(() => {
      fn(...param)
    }, delay)
  }
}

/**
 * 节流
 * @param {*} fn
 * @param {*} delay
 * @returns
 */
export const throttle = (fn, delay) => {
  let pre = 0
  return (...params) => {
    const now = new Date().getTime()
    if (now - pre > delay) {
      fn(...params)
      pre = now
    }
  }
}

/**
 * 批量过滤对象值为空的属性
 * @param {Object} val 需要过滤的对象
 * @param {Array}  arr 排除过滤的属性
 * @returns
 */
export const getFilterData = (val = {}, arr: string[] = []) => {
  const res = {}
  for (const key in val) {
    // undefined == null  output: true
    if (val[key] != null && val[key] !== '' && !arr.includes(key)) {
      if (typeof val[key] == 'number') {
        if (!Number.isNaN(val[key])) {
          res[key] = val[key]
        }
      }
      else {
        res[key] = val[key]
      }
    }
  }
  return res
}
/**
 * 对象深拷贝
 * @param {*} object
 * @returns
 */
export const copyObject = (object) => {
  if (object.constructor == Object) {
    const keys = Object.keys(object)
    const newObject = {}
    keys.forEach((key) => {
      newObject[key] = copyObject(object[key])
    })
    return newObject
  }
  else if (object.constructor == Array) {
    return object.map((item) => {
      return copyObject(item)
    })
  }
  else {
    return object
  }
}

/**
 *
 * @param {*} suffix
 * !w80
    !w100
    !w160
    !w200
    !w400
    !w800
    !wh400
    !w600
 */
export const screenshot = (url, suffix = '!w200') => {
  return url + suffix
}
interface DataLoadingStatus {
  list: any[]
  total: number
  status: boolean
}
// 获取数据加载状态 //0:数据从无到有加载数据，1，没有任何数据， 2：下拉加载，3：下拉没有数据
export const dataLoadingStatus = ({ list = [], total = 0, status = false }: DataLoadingStatus) => {
  console.log('list & status', list, status)
  // 类型校验
  if (Object.prototype.toString.call(list) !== '[object Array]') {
    list = []
  }
  if (list.length == 0 && status) {
    return 0
  }
  else if (list.length == 0 && !status) {
    return 1
  }
  else if (list.length < total) {
    return 2
  }
  else {
    return 3
  }
}

function delay(delayTime = 25): Promise<null> {
  return new Promise((resolve) => {
    setTimeout(() => {
      // @ts-expect-error no error
      resolve()
    }, delayTime)
  })
}

export function delayQuerySelector(selectorStr: string, delayTime = 500): Promise<any[]> {
  return new Promise((resolve) => {
    const selector: SelectorQuery = Taro.createSelectorQuery()
    delay(delayTime).then(() => {
      selector
        .select(selectorStr)
        .boundingClientRect()
        .exec((res: any[]) => {
          resolve(res)
        })
    })
  })
}

// 全局分享监听
export const shareShop = () => {
  const page = Taro.getCurrentInstance().page
  // 当有分享参数时，绑定上下级
  if (page && page.options?.share) {
    analysisShortCodeApi(page.options.share)
  }
  if (page && page.onShareAppMessage) {
    page.onShareAppMessage = (res) => {
      let path = ''
      let title = ''
      let imageUrl = ''
      const sortCode = Taro.getStorageSync('sort_code') ? JSON.parse(Taro.getStorageSync('sort_code')) : ''
      const pageInfo: any = page
      // 商品详情分享
      if (pageInfo.route === 'pages/details/index') {
        path = `/pages/details/index?share=${sortCode.shareShortDetail.code}`
        title = sortCode.shareShortDetail.title
        imageUrl = sortCode.shareShortDetail.img
      }
      else {
        path
          = pageInfo.route === 'pages/user/index'
            ? `/pages/user/index?share=${sortCode.shareShortPage.code}`
            : `/pages/index/index?share=${sortCode.shareShortPage.code}`
        title = sortCode.shareShortPage.title
        imageUrl = pageInfo.route === 'pages/user/index' ? sortCode.shareShortPage.img : formatImgUrl('/mall/share_img_02.png', '!w400')
      }
      return {
        title,
        path,
        imageUrl,
      }
    }
  }
}
