import React from "react"
import { Button, Spin } from "antd"

import { dispatch } from '../../../../model'
import { showMessage } from "../../../../util"

const FC = ({ id, appType, subType, env }) => {
  const [loading, setLoading] = React.useState(false)
  const [waiting, setWaiting] = React.useState(false)
  const [subsribeData, setSubsribeData] = React.useState()

  React.useEffect(() => {
    if (id && appType && subType && env) {
      getSubsribeData()
    }
  }, [id, appType, env])

  const title = React.useMemo(() => {
    return subsribeData ? '取消收藏' : '收藏'
  }, [subsribeData])

  const getSubsribeData = () => {
    setLoading(true)
    dispatch({
      type: 'assetmanage.subsribeDataList',
      payload: {
        appType,
        subType,
        env,
        resourceIds: id,
      },
      callback: (data) => {
        setLoading(false)
        setSubsribeData(data?.[id])
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  const onSubsribeClick = () => {
    if (waiting || loading) return

    setWaiting(true)
    if (subsribeData?.id) {
      dispatch({
        type: 'assetmanage.deleteSubsribe',
        payload: {
          subscribeIds: subsribeData?.id,
        },
        callback: () => {
          setWaiting(false)
          showMessage("success","操作成功")
          getSubsribeData()
        },
        error: () => {
          setWaiting(false)
        }
      })
    } else {
      dispatch({
        type: 'assetmanage.addSubscribe',
        payload: {
          params: {
            appType,
            subType,
            resourceIds: id,
            env,
          }
        },
        callback: () => {
          setWaiting(false)
          showMessage("success","操作成功")
          getSubsribeData()
        },
        error: () => {
          setWaiting(false)
        }
      })
    }
  }

  return (
    <>
    { env && <Button onClick={onSubsribeClick} loading={loading || waiting}>{title}</Button> }
    </>
  )
}

export default FC