import { useRouter } from '@tarojs/taro'
import dayjs from 'dayjs'
import type { SetStateAction } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useSelector } from '@/reducers/hooks'

// 倒计时hook
export const useTimeCountDown = () => {
  const [showTime, setShowTime] = useState({
    DD: '',
    HH: '',
    MM: '',
    SS: '',
  })
  const [timeStatus, setTimeStatus] = useState<0 | 1 | 2>(0) // 倒计时状体  0:倒计时未开始 1:倒计时中， 2：倒计时已结束
  const timeObj: any = useRef()
  const endTime = useRef('')
  const count_down = () => {
    const startData = dayjs()
    const endDate = dayjs(endTime.current)
    setTimeStatus(() => 1)
    if (startData >= endDate) {
      clearInterval(timeObj.current)
      setShowTime(e => ({ ...e, DD: '00', HH: '00', MM: '00', SS: '00' }))
      setTimeStatus(() => 2)
      return false
    }
    const _dd = endDate.diff(startData, 'day')
    const _hh = endDate.diff(startData, 'hour')
    const _mm = endDate.diff(startData, 'minute')
    const _ss = endDate.diff(startData, 'second')
    // 转换
    const hh = _hh - _dd * 24
    const mm = _mm - _hh * 60
    const ss = _ss - _mm * 60
    // 格式化
    const DD = (`00${_dd}`).slice(-2)
    const HH = (`00${hh}`).slice(-2)
    const MM = (`00${mm}`).slice(-2)
    const SS = (`00${ss}`).slice(-2)
    // console.log('endTime::', `${DD}-${HH}-${MM}-${SS}`)
    setShowTime(e => ({ ...e, DD, HH, MM, SS }))
  }
  const onStart = (val = '') => {
    // console.log('time:::', val)
    endTime.current = val
    if (endTime.current) {
      clearInterval(timeObj.current)
      timeObj.current = setInterval(() => {
        count_down()
      }, 1000)
    }
  }
  useEffect(() => {
    return () => {
      clearInterval(timeObj.current)
    }
  }, [])

  return {
    showTime,
    onStart,
    timeStatus,
  }
}

// 订阅消息hook
// export const UseSubscriptionMessage = () => {
//   const { fetchData: fetchDataMessage } = SubscriptionMessageApi()
//   const openSubscriptionMessage = ({ orderId = 0, scenes = 0 }: { orderId?: number; scenes: number }) => {
//     return new Promise(async (resolve) => {
//       let params: { sale_order_id?: number; scenes?: number } = {}
//       orderId && (params.sale_order_id = orderId)
//       params.scenes = scenes
//       let res = await fetchDataMessage(params)
//       if (res.success && res.data.TemplateID && res.data.TemplateID.length > 0) {
//         Taro.requestSubscribeMessage({
//           tmplIds: res.data.TemplateID,
//           complete: function (res) {
//             resolve(res)
//           },
//         })
//       } else {
//         resolve(true)
//       }
//     })
//   }

//   return {
//     openSubscriptionMessage,
//   }
// }

type NormalPropsType = Record<string | symbol | number, any>
interface Options {
  deep?: boolean
}

const defaultOptions = {
  deep: false,
}
/**
 * 适用于 memo 第二个入参 手动触发渲染
 * 目前是判断 引用地址 是否相同 TODO： 判断值是否相同
 * @param options 配置
 * @returns {(prevProps: NormalPropsType, nextProps: NormalPropsType) => boolean} 回调函数
 */
export const useNeedMemoCallback = (options: Options = defaultOptions) => {
  return (prevProps: NormalPropsType, nextProps: NormalPropsType) => {
    // console.log(options)
    // console.log('memo==>', prevProps, nextProps)
    let needMemoized = true
    // 引用类型
    // function array object
    // 基本类型
    // number boolean string number symbol null undefined

    // 循环props对象
    const handleDiff = () => {
      for (const [key, value] of Object.entries(prevProps)) {
        if (!Object.is(value, nextProps[key])) {
          // console.log('函数不相等',value === nextProps[key])
          // console.log('asdfasdf',value)
          needMemoized = false
          break
        }
      }
      // Object.entries(prevProps).forEach(([key, value]) => {
      //   if (!nextProps.hasOwnProperty(key)) {
      //     needMemoized = false
      //     // 新增的属性
      //     if (Object.prototype.toString.call(value) === '[object Object]') {
      //       parent[key] = {}
      //     } else if (Object.prototype.toString.call(value) === '[object Array]') {
      //       parent[key] = []
      //     }
      //   }
      //   if (typeof data[key] === 'object') {
      //     o[key] = internalSetData(parent[key], data[key])
      //   } else {
      //     // 核心处理逻辑
      //     // key == data第一层  如果要做到data第二层呢？所以需要递归
      //     if (parent[key] != data[key]) {
      //       o[key] = data[key]
      //       changed = true
      //     }
      //   }
      // })
    }
    handleDiff()
    return needMemoized
  }
}

interface UsePropsValueOptions<T> {
  value?: T
  defaultValue: T
  onChange?: (v: T) => void
}

export function usePropsValue<T>(options: UsePropsValueOptions<T>) {
  const { value, defaultValue, onChange } = options

  const [, setForceUpdate] = useState({})

  const stateRef = useRef<T>(value !== undefined ? value : defaultValue)
  if (value !== undefined) {
    stateRef.current = value
  }

  const setState = useCallback((v: SetStateAction<T>, forceTrigger = false) => {
    // `forceTrigger` 意思是 触发 `onChange` 不管 `v` 是否和 `stateRef.current` 相等
    const nextValue = typeof v === 'function' ? (v as (prevState: T) => T)(stateRef.current) : v
    if (!forceTrigger && nextValue === stateRef.current) { return }
    stateRef.current = nextValue
    setForceUpdate({})
    return onChange?.(nextValue)
  }, [])
  return [stateRef.current, setState] as const
}

// 点击自定义 tab 时触发。
export function useCustomTabItemTap(callback) {
  const { selectedId, tabItem } = useSelector((state) => {
    return state.tabBarData
  })
  const targetPagePayload = tabItem?.find(item => item.id === selectedId)
  callback({
    index: targetPagePayload?.id,
    pagePath: targetPagePayload?.pagePath,
    text: targetPagePayload?.text,
  })
}
