import {CSSProperties, FC, useCallback, useEffect, useState} from "react";
import star from '@/static/img/star.png'
import starLine from '@/static/img/starLine.png'
import {Image, View} from "@tarojs/components";
import styles from './collect.module.scss'
import {Profile} from "@/store"
import Taro from "@tarojs/taro";
import {userApi} from "@/api";

interface Props {
  onClick?: () => void
  select?: boolean
  stylesImage?: CSSProperties
  styles?: CSSProperties
  owner_id: number
  owner_type: CreateOwnerType
  textHidden?: boolean
  onUpdate?: (v: boolean) => void
}

const versions = new Map()

const collect = async (scope: string, params: Create, setSelect: (v: boolean) => void, value: boolean) => {
  const localVersion = (versions.get(scope)  || 0) + 1
  versions.set(scope, localVersion)
  await userApi.create(params)
  if (localVersion === versions.get(scope)) {
    setSelect(value)
  }
}

/** 收藏 */
const Collect: FC<Props> = (props) => {
  const {token} = Profile.useContainer()
  const [loading, setLoading] = useState(false)
  const [select, setSelect] = useState(props.select)

  useEffect(() => {
    setSelect(props.select)
  }, [props])

  const change = useCallback(async () => {
    if (!token) {
      Taro.navigateTo({url: '/pages/login/login'})
      return
    }
    props.onClick?.()
    setSelect(!select)
    setLoading(true)
    collect(`${props.owner_id}#${props.owner_type}`, {
      owner_id: props.owner_id,
      owner_type: props.owner_type,
    }, (v) => {
      setSelect(v)
      props.onUpdate?.(v)
    }, !select)
    setTimeout(() => {
      setLoading(false)
    }, 300)
  }, [loading, token, select])

  return (
    <View className={styles.collect} onClick={change} style={props.styles}>
      <View className={styles.collectImage} style={props.stylesImage}>
        <View className={`${loading && select && styles.zoom}`}/>
        <Image
          src={(select && token) ? star : starLine}
          className={`${loading && styles.pulse}`}/>
      </View>
      {!props.textHidden && (select ? '已收藏' : '收藏')}
    </View>
  )
}

export default Collect
