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";

const SelectDep: FC = () => {
  const {depIds} = Taro.getCurrentInstance()?.router?.params as { depIds: string }
  const [ids, setIds] = useState<number[]>([])
  const [deps, setDeps] = useState<Manage[]>([])

  useEffect(() => {
    curriculum.department().then(res => {
      setDeps(res.data)
    })

    setIds(JSON.parse(depIds))
  }, [])

  const onChange = useCallback((id: number) => {
    setIds([
      ...ids,
      id
    ])
  }, [ids])

  function ok() {
    if (!ids.length) {
      Taro.showToast({title: '请选着部门', icon: "error"})
      return
    }
    Taro.setStorageSync('selectDep', ids)
    Taro.navigateBack({delta: 1})
  }

  return (
    <View className='px-2 bg-white'>
      {deps.map(d => <View className='flex align-center' key={d.id} onClick={()=>onChange(d.id)}>
        <Checkbox value={d.id + ''} checked={ids.includes(d.id)}/>
        <PopPut
          key={d.id}
          title={d.name}
          chevron
          leftImage={folder}
        />
      </View>)}

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

    </View>
  )
}

export default SelectDep
