import {FC, useEffect, useState} from "react";
import {AddDepProps, ManageApi} from "@/api/manage";
import {Button, View, PageContainer, Input, Form} 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'

interface ChangeDataProps {
  putCompany: Manage | null
  getDeps: () => Promise<void>
}

const ChangeData: FC<ChangeDataProps> = ({putCompany, getDeps}: ChangeDataProps) => {
  const {company} = Profile.useContainer()
  const [name, setName] = useState<string>('')
  const [sort, setSort] = useState<number>(putCompany?.sort || 0)
  const [disable, setDisable] = useState(false)
  const company_id = putCompany?.company_id || company?.id || 0

  useEffect(() => {
    if (putCompany) {
      setName(putCompany.name)
    }
  }, [])

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

  return (
    <View className='p-2'>
      <View className='mt-2 text-center font-weight font-34'>添加部门</View>
      <Form className='form mt-3'>
        <View className='item'>
          <View>名称：</View>
          <Input placeholder='请输入部门名称' value={name} onInput={(event) => setName(event.detail.value)}/>
        </View>
        <View className='item'>
          <View>排序：</View>
          <Input
            type="number"
            placeholder='请输入部门名称'
            value={String(sort)}
            onInput={(event) => setSort(Number(event.detail.value))}/>
        </View>

        <Button className='mt-3' formType='submit' onClick={submit} disabled={disable}>保存</Button>
      </Form>
    </View>
  )
}

const DepAdmin: FC = () => {
  const [manages, setManages] = useState<Manage[]>([])
  const [show, setShow] = useState(false)
  const [putCompany, setPutCompany] = useState<Manage | null>(null)

  async function getData() {
    show && setShow(false)
    const res = await ManageApi.depList()
    if (res) {
      const formatData: Manage[] = []
      Object.values(res)?.forEach(d => {
        formatData.push(...d)
      })
      setManages(formatData)
    }
  }

  function showPop(company: Manage | null) {
    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:
            showPop(item)
            break
          case 2:
            Taro.navigateTo({url: `/pages/manage/depAdmin/depAdmin?id=${item.id}&name=${item.name}`})
            break
          case 3:
            del(item.name, item.id)
            break
        }
      }
    })
  }

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

  Taro.useDidShow(getData)

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

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

      <PageContainer show={show} round onAfterLeave={() => setShow(false)}>
        <View className='h-4'>
          {show && <ChangeData getDeps={getData} putCompany={putCompany}/>}
        </View>
      </PageContainer>
    </Profile.Provider>
  )
}

export default DepAdmin
