import React, {FC, useCallback, useEffect, useState} from "react";
import {Checkbox, Switch, 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, required: string | undefined }
  const [ids, setIds] = useState<number[]>([])
  const [deps, setDeps] = useState<Manage[]>([])
  const [required, setRequired] = useState<number[]>([])
  const [enable, setEnable] = useState(true)

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

  const onChange = useCallback((id: number) => {
    const index = ids.indexOf(id)
    if (index === -1) {
      setIds([
        ...ids,
        id
      ])

      if (params.required) {
        setRequired([...required, 0])
      }
    } else {
      const oldIds: number[] = JSON.parse(JSON.stringify(ids))
      oldIds.splice(index, 1)
      setIds(oldIds)

      if (params.required) {
        const oldRequired: number[] = JSON.parse(JSON.stringify(required))
        oldRequired.splice(index, 1)
        setRequired(oldRequired)
      }
    }
  }, [ids])

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


  function isRequired(dep_id: number): boolean {
    const index = ids.indexOf(dep_id)
    if (index === -1) {
      return false
    } else {
      return !!required?.[index]
    }
  }

  function requiredChange(dep_id: number, value: boolean) {
    const index = ids.indexOf(dep_id)
    if (index === -1) {
      setIds([...ids, dep_id])
      setRequired([...required, value ? 1 : 0])
    } else {
      const oldRequired: number[] = JSON.parse(JSON.stringify(required))
      oldRequired.splice(index, 1, value ? 1 : 0)
      setRequired(oldRequired)
    }
  }

  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}
            content={
              params?.required ?
                <View className='flex align-center'>
                  必修：<Switch
                  color='#45d4a8'
                  onClick={() => event?.stopImmediatePropagation()}
                  checked={isRequired(d.id)}
                  onChange={(e) => requiredChange(d.id, e.detail.value)}/>
                </View>
                : null
            }
          />
        </View>
      </View>)}

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

    </View>
  )
}

export default SelectDep
