import {getCurrentInstance} from "@tarojs/runtime";
import Taro, {useReachBottom} from "@tarojs/taro";
import {ManageApi} from "@/api/manage";
import React, {FC, useEffect, useState} from "react";
import {Image, View} from "@tarojs/components";
import {curriculum} from "@/api";
import MyButton from "@/components/button/MyButton";
import styles from './depCur.module.scss'
import Empty from "@/components/empty/empty";


let page = 1
const DepCur: FC = () => {
  const {id} = getCurrentInstance()?.router?.params as { id: number }
  const [total, setTotal] = useState<number>(0)
  const [data, setData] = useState<Curriculum[]>([])

  const getData = async (init?: boolean) => {
    try {
      Taro.showLoading({title: "课程查询中"})
      if (init) {
        page += 1
      } else {
        page = 1
      }
      const res = await ManageApi.depCur({id, size: 10, page: page})
      setTotal(res.total)
      const oldData: Curriculum[] = JSON.parse(JSON.stringify(data))
      res.data.forEach(d => {
        const index = oldData.findIndex(c => c.id === d.id)
        if (index === -1) {
          oldData.push(d)
        } else {
          oldData.splice(index, 1, d)
        }
      })
      setData(oldData)
    } catch (e) {
    }
    Taro.hideLoading()
  }


  async function findDel(cur_id: number) {
    try {
      await curriculum.delCur(id, cur_id)
      const index = data.findIndex(d => d.id === cur_id)
      if (index > -1) {
        const oldData: Curriculum[] = JSON.parse(JSON.stringify(data))
        oldData.splice(index, 1)
        setData(oldData)
      }
      Taro.showToast({title: '删除成功'})
    } catch (e) {
    }
  }

  function del(id: number) {
    Taro.showModal({
      title: "是否删除课程",
      success({confirm}) {
        confirm && findDel(id)
      }
    })
  }

  function jumpAddCur() {
    Taro.navigateTo({url: "/pages/manage/addCur/addCur?id=" + id})
  }

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

  useReachBottom(() => {
    if (data.length < total) {
      getData(true)
    }
  })

  return (
    <View className={styles.page}>
      {
        data.length > 0 ?
          data.map(d => <View key={d.id} className={styles.curBox}>
            <View className={styles.imageBox}>
              <Image src={d.thumb} className={styles.image} mode='aspectFill'/>
              <View>{d.title}</View>
              <View className={styles.required}>{d.is_required ? '必修' : '选修'}</View>
            </View>
            <View
              className={styles.del}
              onClick={() => del(d.id)}>
              删除
            </View>
          </View>)
          : <Empty name='部门无课程'/>
      }


      <View className={styles.flexdButton}>
        <MyButton onClick={jumpAddCur}>添加课程</MyButton>
      </View>
    </View>
  )
}
export default DepCur
