import {CustomWrapper, View} from "@tarojs/components";
import {FC, useEffect, useState} from "react";
import VideoCover from "@/components/videoCover/videoCover";
import styles from './curriculum.module.scss'
import {ManageApi} from "@/api/manage";
import Taro from "@tarojs/taro";
import Empty from "@/components/empty/empty";


const Curriculum = () => {
  const [data, setDta] = useState<Curriculum[]>([])

  async function getData() {
    try {
      const res = await ManageApi.buyAll()
      setDta(res)
    } catch (e) {
    }
  }

  const Add: FC<{ id: number }> = ({id}: { id: number }) => {
    function buy() {
      Taro.showModal({
        title: '是否购买',
        async success({confirm}) {
          if (confirm) {
            try {
              await ManageApi.buy([id])
              Taro.showToast({title: "购买成功"})
              await getData()
            } catch (e) {
            }
          }
        }
      })
    }

    return (
      <View className={styles.curBuy} onClick={buy}>购买</View>
    )
  }

  useEffect(() => {
    getData()
  }, [])

  return (
    <CustomWrapper>
      {data.length ?
        <View className='bg-white flex flex-wrap'>
          {data.map(d => (<VideoCover
              marker='限时免费'
              thumb={d.thumb}
              title={<Add id={d.id}/>}
              id={d.id}
              depId={null}
              content={d.title}/>
          ))}
        </View>
        : <Empty name='无购买课程'/>
      }
    </CustomWrapper>
  )
}

export default Curriculum
