import {Button, Form, Input, View} from "@tarojs/components";
import {useCallback, useEffect, useState} from "react";
import {ManageApi, Student} from "@/api/manage";
import Icon from "@/components/icon";
import Taro from "@tarojs/taro";
import {curriculum} from "@/api";
import './addStudent.scss'
import {getCurrentInstance} from "@tarojs/runtime";
import {Profile} from '@/store'
import storageDep from "@/hooks/storageDep";

interface Department {
  id: number
  title: string
}

const AddStudent = () => {
  const [userInfo, setUerInfo] = useState<Student | null>(null)
  const [department, setDepartment] = useState<Department[]>([])
  const [depIds, setDepIds] = useState<number[]>([])
  const params = getCurrentInstance()?.router?.params as { id?: number }
  const {company} = Profile.useContainer()


  async function getDepartment() {
    const res = await curriculum.department()
    if (res) {
      setDepartment(res.data.map(d => ({title: d.name, id: d.id})))
    }
  }

  async function submit(event) {
    const value: Student = event.detail.value
    for (const [_, value1] of Object.entries(value)) {
      if (!value1) {
        Taro.showToast({title: "请填写学员姓名和手机号", icon: 'error'})
        return
      }
    }

    Taro.showLoading()
    try {
      if (params.id) {
        await ManageApi.putUser(params.id, {...value, dep_ids: depIds, company_id: company?.id || 0})
      } else {
        await ManageApi.addUser({...value, dep_ids: depIds, company_id: company?.id || 0})
      }
      Taro.hideLoading()
      Taro.showToast({title: "添加成功", icon: 'success'})
      setTimeout(() => {
        Taro.navigateBack()
      }, 500)
    } catch (e) {
    }
    Taro.hideLoading()
  }


  const formatDep = useCallback(() => {
    const selected = department.filter(d => depIds.includes(d.id)).map(d => d.title)
    const top4 = selected.splice(0, 3).join('、')
    return top4 + (selected.length ? "+" + selected.length : '')
  }, [depIds])

  async function getUserInfo() {
    const res = await ManageApi.userInfo(params.id!)
    setUerInfo(res.user)
    setDepIds(res.dep_ids)
  }

  const jumSetDep = useCallback(() => {
    Taro.navigateTo({url: `/pages/manage/selectDep/selectDep?depIds=${JSON.stringify(depIds)}`})
  }, [depIds])

  useEffect(() => {
    getDepartment()
    if (params.id) {
      getUserInfo()
    }
  }, [])

  Taro.useDidShow(() => {
    const newDepIds = storageDep.get()
    setDepIds(newDepIds)
  })

  return (
    <View className='bg-white px-2 mt-2'>
      <Form className='form' onSubmit={submit}>
        <View className='item'>
          <View>姓名</View>
          <Input placeholder='请输入学员姓名' name='name' value={userInfo?.name}
                 onInput={(event) => setUerInfo({...userInfo, name: event.detail.value} as Student)}/>
        </View>


        <View className='item'>
          <View>手机号</View>
          <Input
            placeholder='请输入手机号'
            name='phone_number'
            value={userInfo?.phone_number}
            onInput={(event) => setUerInfo({...userInfo, phone_number: event.detail.value} as Student)}/>
        </View>


        <View className='item' onClick={jumSetDep}>
          <View>所属部门</View>
          <View className='flex align-center'>
            <View>
              {depIds.length ? formatDep() : '选择部门'}
            </View>
            <Icon name='chevron-right'/>
          </View>
        </View>

        <Button className='add button' formType='submit'>{params.id ? '修改学员' : "添加学员"}</Button>
      </Form>
    </View>
  )
}


export default AddStudent
