import React, {FC, useCallback, useEffect, useState} from "react";
import {ManageApi} from "@/api/manage";
import {View, Input} from "@tarojs/components";
import Taro, {useRouter} from "@tarojs/taro";
import './depAdmin.scss'
import PopPut from "@/components/popPut/popPut";
import folder from '@/static/img/folder.png'
import ShowModel from "@/components/showModel/showModel";
import Empty from "@/components/empty/empty";
import {Profile} from '@/store'
import Spin from "@/components/spinner";

const DepAdmin: FC = () => {
  const router = useRouter()
  const [manages, setManages] = useState<Manage[]>([])
  const [show, setShow] = useState(false)
  const [users, setUsers] = useState<User[]>([])
  const [isPut, setIsPut] = useState(false)
  const [depName, setDepName] = useState('')
  const [reset, setReset] = useState(false)
  const [enable, setEnable] = useState(true)
  const {company} = Profile.useContainer()


  async function getData() {
    show && setShow(false)
    try {
      const res = await ManageApi.depList(router.params.dep_id || 0)
      if (res) {
        setReset(true)
        setManages(res.department)
        setUsers(res.data)
      }
    } catch (e) {
    }
    setEnable(false)
  }

  function showPop(name: string | undefined) {
    if (name) {
      setDepName(name)
      setIsPut(true)
    } else {
      setIsPut(false)
      setDepName('')
    }
    setShow(true)
  }

  function del(name: string, id: string) {
    Taro.showModal({
      title: name + ' 删除后将不可恢复',
      async success({confirm}) {
        if (confirm) {
          try {
            Taro.showLoading()
            await ManageApi.delDep(id)
            Taro.hideLoading()
            Taro.showToast({title: "删除成功"})
            Taro.navigateBack()
            await getData()
          } catch (e) {
          }
        }
      }
    })
  }

  function jumpDepAdmin(item: Manage) {
    Taro.navigateTo({url: `/pages/manage/depAdmin/depAdmin?dep_id=${item.id}&name=${encodeURI(item.name)}&id=${item.id}`})
  }

  function managesSheet() {
    Taro.showActionSheet({
      itemList: [
        '查看部门课程',
        '修改当前部门名称',
        '删除部门'
      ],
      success({tapIndex}) {
        switch (tapIndex) {
          case 0:
            Taro.navigateTo({url: `/pages/manage/depCur/depCur?id=${router.params.id}`})
            break
          case 1:
            showPop(decodeURI(router.params.name!))
            break
          case 2:
            del(decodeURI(router.params.name!), router.params.id!)
            break
        }
      },
      fail() {
      }
    })
  }


  function jumpAddStudent() {
    Taro.navigateTo({url: '/pages/manage/addStudent/addStudent'})
  }

  const addDep = useCallback(async () => {
    if (!depName) {
      Taro.showToast({title: '请填写部门名称！', icon: 'error'})
      return
    }
    try {
      if (isPut) {
        await ManageApi.putDep(router.params.id!, depName)
        router.params.name = depName
        Taro.setNavigationBarTitle({
          title: depName
        })
      } else {
        await ManageApi.addDep({
          name: depName,
          parent_id: Number(router.params.dep_id) || 0,
          company_id: company?.id!,
          sort: manages.length,
        })
      }
      getData()
      setShow(false)
    } catch (e) {
      Taro.showToast({title: '操作失败', icon: 'error'})
    }
  }, [isPut, depName])

  useEffect(() => {
    getData()
    Taro.setNavigationBarTitle({
      title: router.params.name ? decodeURI(router.params.name!) : '部门管理'
    })
  }, [])

  Taro.useDidShow(() => {
    reset && getData()
  })

  return (
    <>
      <Spin overlay enable={enable}/>
      <View className='content'>
        {manages.map(d => <PopPut
          key={d.id}
          title={d.name}
          onClick={() => jumpDepAdmin(d)}
          chevron
          leftImage={folder}
        />)}

        {
          users.map(d => <PopPut
            errorType='avatar'
            key={d.id}
            leftImage={d.avatar}
            title={d.name}
            onClick={() => Taro.navigateTo({url: '/pages/manage/userInfo/userInfo?userId=' + d.id})}
            content={['学员', '管理员', '超级管理员'][d.role_type]}
          />)
        }
        {manages.length > 0 || users.length > 0 && <View className='text-center font-24 text-dark mt-3'>暂无更多</View>}

        {!manages.length && !users.length && <Empty name='暂无数据'/>}

        <View className='operation'>
          <View className='safeAreaInsetBottom'>
            <View onClick={jumpAddStudent}>添加学员</View>
            <View onClick={() => showPop(undefined)}>添加部门</View>
            {
              router.params.id && <View onClick={managesSheet}>更多操作</View>
            }
          </View>
        </View>
      </View>

      <ShowModel
        show={show}
        title={isPut ? `修改${depName}` : '添加部门'}
        onClickOverlay={() => setShow(false)}
        onOk={addDep}
      >
        <Input placeholder='添加部门名称'
               className='depInput'
               value={depName}
               onInput={(e) => setDepName(e.detail.value)}/>
      </ShowModel>
    </>
  )
}


export default DepAdmin
