import Taro from '@tarojs/taro'
import dayjs from 'dayjs'
import { useCallback, useEffect, useRef, useState } from 'react'
import type { SetStateAction } from 'react'
import { SubscriptionMessageApi } from '@/api/user'

// 倒计时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('')

  useEffect(() => {
    return () => {
      clearInterval(timeObj.current)
    }
  }, [])
  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)
    }
  }
  return {
    showTime,
    onStart,
    timeStatus,
  }
}

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

  return {
    openSubscriptionMessage,
  }
}

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
}
