import {FC, useEffect, useState} from "react";
import {Category} from "@/api";
import Taro from "@tarojs/taro";
import Empty from "@/components/empty/empty";
import {ScrollView, View} from "@tarojs/components";
import styles from "../sort.module.scss";
import Spin from "@/components/spinner";


interface Props {
  category: Category
  loading: boolean
  onChange: (id?: number) => void
  illness: Map<number, any[]>
}

const prefix = 'SORT'
const SecondLevel: FC<Props> = ({category, loading, onChange, illness}) => {
  const globalData = Taro.getApp().globalData
  const [secondId, setSecondId] = useState<undefined | number>(undefined)

  useEffect(() => {
    if (!secondId) {
      setSecondId(category.resource_category?.[0]?.id)
    }
    onChange(secondId || category.resource_category?.[0]?.id)
  }, [secondId])

  function jump(id: number) {
    Taro.navigateTo({url: '/pages/preview/illness/list/list?id=' + id})
  }

  if (!category.resource_category?.length) {
    return (<Empty name='暂无二级分类'/>)
  } else {
    return (
      <View className='flex' style={{height: `${globalData.pageHeight}px`}}>
        <ScrollView scrollY className={styles.firstOrder} enhanced showScrollbar={false}>
          {
            category.resource_category?.map(d => <View
              id={`${prefix}-${d.id}`}
              key={d.id}
              onClick={() => setSecondId(d.id)}
              className={secondId === d.id && styles.select}>
              {d.name}
            </View>)
          }
        </ScrollView>
        <ScrollView
          enhanced
          showScrollbar={false}
          scrollY
          className={styles.tree}
          scrollWithAnimation>
          <Spin enable={loading} block/>
          {
            (secondId && illness.get(secondId)?.length) ?
              <>
                {
                  illness.get(secondId)?.map(d => <View
                    className={styles.list}
                    onClick={() => jump(d.id)}>
                    {d.name}
                  </View>)
                }
                <View className='text-center font-24 text-dark mt-3'>暂无更多</View>
              </>
              : <Empty name='暂无数据'/>
          }
        </ScrollView>
      </View>
    )
  }
}

export default SecondLevel
