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


const DepAdmin: FC = () => {
  const params = getCurrentInstance()?.router?.params as { dep_id: string, name: string, id: string }
  const [manages, setManages] = useState<Manage[]>([])
  const [show, setShow] = useState(false)
  const [users, setUsers] = useState<User[]>([])
  const [putCompany, setPutCompany] = useState<Manage | null>(null)
  const [depName, setDepName] = useState('')
  const {company} = Profile.useContainer()


  async function getData() {
    show && setShow(false)
    const res = await ManageApi.depList(params.dep_id || 0)
    if (res) {
      setManages(res.department)
      setUsers(res.data)
    }
  }

  function showPop(company: Manage | null) {
    if (company) {
      setDepName(company.name)
    } else {
      setDepName('')
    }
    setPutCompany(company)
    setShow(true)
  }

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

  function managesSheet(item: Manage) {
    Taro.showActionSheet({
      itemList: [
        '查看部门课程',
        '查看子部门和学员',
        '修改',
        '删除'
      ],
      success({tapIndex}) {
        switch (tapIndex) {
          case 0:
            Taro.navigateTo({url: `/pages/manage/depCur/depCur?id=${item.id}`})
            break
          case 1:
            Taro.navigateTo({url: `/pages/manage/depAdmin/depAdmin?dep_id=${item.id}&name=${item.name}&id=${item.id}`})
            break
          case 2:
            showPop(item)
            break
          case 3:
            del(item.name, item.id)
            break
        }
      }
    })
  }

  function delUser(id: number) {
    Taro.showModal({
      title: '是否确认删除',
      async success({confirm}) {
        if (confirm) {
          await ManageApi.del(id)
          Taro.showToast({title: '删除成功'})
          await getData()
        }
      }
    })
  }

  function userManagesSheet(user: User) {
    const itemList = [
      '修改',
      '删除',
      "日学习记录",
    ]
    if (user.role_type === 1) {
      itemList.push('取消管理员')
    } else if (user.role_type === 0) {
      itemList.push('设置为管理员')
    }

    Taro.showActionSheet({
      itemList,
      success({tapIndex}) {
        switch (tapIndex) {
          case 0:
            Taro.navigateTo({url: "/pages/manage/addStudent/addStudent" + (user.id ? `?id=${user.id}` : '')})
            break
          case 1:
            delUser(user.id)
            break
          case 2:
            Taro.navigateTo({url: `/pages/manage/college/college?id=${user.id}&name=${user.name}`})
            break
          case 3:
            setRoleType(user)
            break
        }
      }
    })
  }

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

  function setRoleType(user: User) {
    if (user.role_type === 2) {
      Taro.showModal({title: "禁止修改超级管理员"})
      return
    }
    const type = user.role_type === 0 ? 1 : 0
    Taro.showModal({
      title: "设置为" + ['学员', '管理员'][type],
      async success({confirm}) {
        if (confirm) {
          try {
            Taro.showLoading()
            await ManageApi.setRoleType(user.id, {auth_id: user?.id!, role_type: type})
            Taro.hideLoading()
            Taro.showToast({title: "设置成功"})
            await getData()
          } catch (e) {
          }
        }
      }
    })
  }

  async function addDep() {
    if (!depName) {
      Taro.showToast({title: "请认真填写", icon: "error"})
      return
    }
    try {
      const company_id = putCompany?.company_id || company?.id || 0
      const data: AddDepProps = {
        id: putCompany?.id || null,
        name: depName,
        parent_id: putCompany ? putCompany?.parent_id : manages.length,
        company_id: company_id,
        sort: putCompany?.sort || 0
      }
      if (putCompany) {
        await ManageApi.putDep(data)
      } else {
        await ManageApi.addDep(data)
      }
      setTimeout(() => Taro.showToast({title: '操作成功'}))
      await getData()
    } catch (e) {
    }
  }

  Taro.useDidShow(getData)

  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: params.name ?? '部门管理'
    })
  })

  return (
    <>
      <View>
        {manages.map(d => <PopPut
          key={d.id}
          title={d.name}
          onClick={() => managesSheet(d)}
          chevron
          leftImage={folder}
        />)}

        {users.map(d => <PopPut
          key={d.id}
          leftImage={d.avatar}
          title={d.name}
          onClick={() => userManagesSheet(d)}
          content={['学员', '管理员', '超级管理员'][d.role_type]}
        />)}

        <View className='text-center text-muted mt-3'>- 暂无更多 -</View>

        <View className='operation'>
          <View className='safeAreaInsetBottom'>
            <View onClick={jumpAddStudent}>添加学员</View>
            <View onClick={() => showPop(null)}>添加部门</View>
          </View>
        </View>
      </View>

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

const DepAdminIndex: FC = () => {
  return (
    <Profile.Provider>
      <DepAdmin/>
    </Profile.Provider>
  )
}

export default DepAdminIndex
