import {View} from "@tarojs/components";
import {FC, useEffect, useState} from "react";
import styles from './userInfo.module.scss'
import Taro from "@tarojs/taro";
import Info from "@/pages/manage/userInfo/components/info";
import MyButton from "@/components/button/MyButton";
import {ManageApi, userApi} from "@/api";
import {Profile} from "@/store";
import LearningRecord from "@/components/learningRecord/learningRecord";


const UserInfo: FC = () => {
  const {userId} = Taro.getCurrentInstance().router?.params as { userId: string }
  const [data, setData] = useState<User | null>(null)
  const router = Taro.useRouter()
  const {user} = Profile.useContainer()

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

  function delUser() {
    Taro.showModal({
      title: '是否确认删除',
      async success({confirm}) {
        if (confirm) {
          try {
            await ManageApi.del(userId)
            Taro.showToast({title: '删除成功'})
            Taro.navigateBack()
          } catch (e) {
          }
        }
      }
    })
  }


  useEffect(() => {

    userApi.info(userId).then(res => {
      setData(res)
    })
  }, [])

  Taro.useDidShow(() => {
    if (data) {
      userApi.info(router.params.userId!).then(res => {
        setData(res)
      })
    }
  })

  return (
    <View className={styles.page}>
      <Info data={data}/>

      <LearningRecord userId={userId}/>


      <View className='mt-5'>
        {
          data?.role_type !== 2
          && <MyButton onClick={setRoleType}>{['设置为管理员', '设置为学员'][data?.role_type || 0]}</MyButton>
        }
        <MyButton
          type='default'
          style={{background: '#fff'}}
          onClick={() => Taro.navigateTo({url: "/pages/manage/addStudent/addStudent?id=" + userId})}
          className={'mt-3'}>
          修改
        </MyButton>
        <MyButton
          type='default'
          style={{background: '#fff', color: 'red'}}
          className={'mt-3'}
          onClick={delUser}>
          删除
        </MyButton>
      </View>
    </View>
  )
}

export default UserInfo
