import {ScrollView, Swiper, SwiperItem, View} from "@tarojs/components";
import {FC, useEffect, useMemo, useState} from "react";
import {Category, HomeApi} from "@/api";
import Taro from "@tarojs/taro";
import styles from './sort.module.scss'
import Tabs, {TabList} from "@/components/tabs/tabs";
import {illnessApi} from "@/api/illness";
import Empty from "@/components/empty/empty";
import Spin from "@/components/spinner";
import NavigationBar from "@/components/navigationBar/navigationBar";

const prefix = 'SORT'
const Sort: FC = () => {
  const [data, setData] = useState<Category[]>([])
  const [firstId, setFirstId] = useState<number | undefined>(undefined)  // 一级分类
  const [secondId, setSecondId] = useState<number | undefined>(undefined) // 二级分类
  const [list, setList] = useState<any[]>([])
  const [enable, setEnable] = useState(true)
  const [loading, setLoading] = useState(false)
  const globalData = Taro.getApp().globalData

  async function getData() {
    try {
      const res = await HomeApi.category(3)
      setData(res)
      if (res.length) {
        setFirstId(res[0].id)
        setSecondId(res[0]?.resource_category?.[0].id)
      }
    } catch (e) {
      setLoading(false)
    }
    setEnable(false)
  }

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

  const getTabList = useMemo((): TabList[] => {
    return data.map<TabList>(d => ({
      title: d.name,
      value: d.id
    }))
  }, [data])

  function firstIdChange(id: number) {
    setFirstId(id)
    const resource_category = data.find(d => d.id === id)?.resource_category
    setSecondId(resource_category?.[0]?.id)
  }

  Taro.useLoad(getData)

  useEffect(() => {
    if (secondId) {
      setLoading(true)
      illnessApi.list(secondId, 1, 100).then(res => {
        setList(res.list)
      }).catch(() => {
        setList([])
      })
    } else {
      setList([])
    }
    setLoading(false)
  }, [secondId])

  function swiperChange(e) {
    const firstData = data[e.target.current]
    if (!firstData) return;
    setFirstId(firstData.id)
    setSecondId(firstData?.resource_category?.[0]?.id)
  }

  const SecondLevel = (category: Category) => {
    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/>
            {
              list.length ?
                <>
                  {list.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>
      )
    }
  }

  return (
    <View>
      <NavigationBar leftNode={<Tabs
        tabList={getTabList}
        current={firstId}
        style={{paddingBottom: '5px'}}
        onChange={(data) => firstIdChange(data.tab?.value as number)}
      />}/>
      <Spin enable={enable} overlay/>
      {
        data.length > 0 ? <Swiper
            style={{height: `${globalData.pageHeight}px`}}
            onChange={swiperChange}
            current={data.findIndex(d => d.id === firstId)}>
            {
              data.map(d => <SwiperItem key={d.id}>
                {SecondLevel(d)}
              </SwiperItem>)
            }
          </Swiper>
          : <Empty name='暂无疾病分类'/>
      }
    </View>
  )
}

export default Sort
