import React, {FC, useCallback, useEffect, useState} from "react";
import {Checkbox, View} from "@tarojs/components";
import Taro from "@tarojs/taro";
import {curriculum} from "@/api";
import PopPut from "@/components/popPut/popPut";
import folder from "@/static/img/folder.png";
import MyButton from "@/components/button/MyButton";
import storageDep from "@/hooks/storageDep";
import Spin from "@/components/spinner";

/**
 * 选择部门 depIds 是 JSON = number[]
 * required 是 必修选修
 */
const SelectDep: FC = () => {
  const params = Taro.getCurrentInstance()?.router?.params as { depIds: string}
  const [ids, setIds] = useState<number[]>([])
  const [deps, setDeps] = useState<Manage[]>([])
  const [enable, setEnable] = useState(true)

  useEffect(() => {
    curriculum.department().then(res => {
      setDeps(res.data)
    })
    setEnable(false)
    setIds(JSON.parse(params.depIds))
  }, [])

  const onChange = useCallback((id: number) => {
    const index = ids.indexOf(id)
    if (index === -1) {
      setIds([
        ...ids,
        id
      ])
    } else {
      const oldIds: number[] = JSON.parse(JSON.stringify(ids))
      oldIds.splice(index, 1)
      setIds(oldIds)
    }
  }, [ids])

  function ok() {
    storageDep.set(ids)
    Taro.navigateBack({delta: 1})
  }


  return (
    <View className='px-2 bg-white'>
      <Spin overlay enable={enable}/>
      {deps.map((d) => <View className='flex align-center' key={d.id} onClick={() => onChange(d.id)}>
        <Checkbox value={d.id + ''} checked={ids.includes(d.id)} color='#45d4a8'/>
        <View style={{flex: 1}}>
          <PopPut
            key={d.id}
            title={d.name}
            chevron
            leftImage={folder}/>
        </View>
      </View>)}
      <View className='text-center font-24 text-dark mt-3'>暂无更多</View>

      <View className={'my-3'}>
        <MyButton onClick={ok}>确定</MyButton>
      </View>

    </View>
  )
}

export default SelectDep
