import {FC, useCallback, useEffect, useState} from "react";
import {Radio, Text, View} from "@tarojs/components";
import {Search} from "./components/search";
import {CourseAllParam, courseApi, ManageApi} from "@/api";
import styles from './courseAdmin.module.scss'
import Taro, {useReachBottom} from "@tarojs/taro";
import MyButton from "@/components/button/MyButton";
import storageDep from "@/hooks/storageDep";
import Spin from "@/components/spinner";
import Img from "@/components/image/image";

const CourseAdmin: FC = () => {
  const [total, setTotal] = useState(0)
  const [data, setData] = useState<Curriculum[]>([])
  const [batch, setBatch] = useState(false)
  const [curs, setCurs] = useState<number[]>([])
  const [enable, setEnable] = useState(true)
  const [param, setParam] = useState<CourseAllParam>({
    page: 1,
    page_size: 10,
    title: '',
    dep_id: 0
  })

  /**
   *@param replace 替换
   */
  function getData(replace = false) {
    courseApi.getCourseAll({...param, page_size: param.page_size * (replace ? param.page : 1)}).then(res => {
      setTotal(res.total)
      if (param.page === 1 || replace) {
        setData(res.data || [])
      } else {
        setData([
          ...data,
          ...res.data,
        ])
      }
    })
    setEnable(false)
  }

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

  useReachBottom(() => {
    if (data.length < total) {
      setParam({
        ...param,
        page: param.page + 1
      })
    }
  })

  function all() {
    if (curs.length === data.length) {
      setCurs([])
    } else {
      setCurs(data?.map(d => d.id))
    }
  }

  function addCurs(id: number) {
    const index = curs.indexOf(id)
    if (index === -1) {
      setCurs([...curs, id])
    } else {
      const old: number[] = JSON.parse(JSON.stringify(curs))
      old.splice(index, 1)
      setCurs(old)
    }
  }

  function del(id: number, index: number) {
    Taro.showModal({
      title: '删除警告',
      content: "删除后所有部门不可查看",
      confirmText: '删除',
      async success({confirm}) {
        if (confirm) {
          try {
            await courseApi.delCourse(id)
            Taro.showToast({title: '删除成功'})
            const oldData: Curriculum[] = JSON.parse(JSON.stringify(data))
            oldData.splice(index, 1)
            setData(oldData)
          } catch (e) {
          }
        }
      }
    })
  }

  function changeDep(id: number, data: CurDepInfo[]) {
    const depList: Number[] = []
    const required: Number[] = []

    data.forEach(d => {
      depList.push(d.dep_id)
      required.push(d.is_required)
    })

    // @ts-ignore
    batchChangDep([id], depList, required)
  }

  /**
   * 批量添加部门
   * @param ids 课程id
   * @param depList 批量添加为空[]
   * @param required 批量添加为[]
   */
  function batchChangDep(ids: number[], depList = [], required = []) {
    if (!ids?.length) {
      Taro.showToast({title: '请选择课程', icon: 'none'})
      return
    }

    if (ids.length === 1) {
      setCurs(ids)
    }
    Taro.navigateTo({url: `/pages/manage/selectDep/selectDep?depIds=${JSON.stringify(depList)}&required=${JSON.stringify(required)}`})
  }

  Taro.useDidShow(useCallback(async () => {
    const dep_id = storageDep.get()

    if (!dep_id.length || !curs.length) return;


    try {
      await ManageApi.addCur({course_id: curs, dep_id})
      Taro.showToast({title: '修改成功'})
      // deps 中没有 筛选条件中的depid 删除已选的课程
      if (param.dep_id && dep_id.includes(param.dep_id)) {
        const newData = data.reduce((pre, cur) => {
          if (!dep_id.includes(cur.id)) {
            pre.push(cur)
          }
          return pre
        }, [] as Curriculum[])
        setData(newData)
      } else {
        getData()
      }
    } catch (e) {

    }
  }, [curs, data]))


  return (
    <>
      <Search param={param} setParam={setParam}/>
      <Spin enable={enable} overlay/>
      <View className={styles.curList}>
        {
          data?.map((d, index) => <View key={d.id} className={styles.curBox}>
            <View className={styles.curTitle} onClick={() => addCurs(d.id)}>
              {batch && <Radio
                color='#45D4A8'
                checked={curs.includes(d.id)}
                style={{marginTop: '30px'}}
                onClick={() => addCurs(d.id)}/>}
              <Img src={d.thumb} className={styles.curImage}/>
              <View>{d.title}</View>
            </View>
            <View className={styles.Operation}>
              <View onClick={() => del(d.id, index)}>删除</View>
              <View onClick={() => changeDep(d.id, d.data)}>添加部门</View>
            </View>
          </View>)
        }
        <View className='text-center font-24 text-dark mt-3'>暂无更多</View>
      </View>

      <View className={styles.add}>
        {
          !batch
          && data.length > 0
          && <View style={{margin: 'auto', padding: '15px'}} onClick={() => setBatch(true)}>分配部门</View>
        }
        {
          batch && <View className={styles.addBatch}>
            <Radio onClick={all} checked={data.length === curs.length} color='#45D4A8'> 全选</Radio>
            <Text onClick={() => setBatch(false)}>取消</Text>
            <MyButton size='mini' onClick={() => batchChangDep(curs)}>分配部门{curs.length}</MyButton>
          </View>
        }
      </View>
    </>
  )
}

export default CourseAdmin
