import {Swiper, SwiperItem, View} from "@tarojs/components";
import {FC, useMemo, useState} from "react";
import {Category, HomeApi} from "@/api";
import Taro from "@tarojs/taro";
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";
import SecondLevel from "./components/secondLevel";


const Sort: FC = () => {
  const [data, setData] = useState<Category[]>([])
  const [firstId, setFirstId] = useState<number | undefined>(undefined)  // 一级选中
  const [illness, setIllness] = useState<Map<number, any[]>>(new Map)
  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)
      }
    } catch (e) {
      setLoading(false)
    }
    setEnable(false)
  }


  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
    changeSecond(resource_category?.[0]?.id)
  }

  Taro.useLoad(getData)

  function changeSecond(secondId?: number) {
    if (secondId) {
      setLoading(true)
      illnessApi.list(secondId, 1, 1000).then(res => {
        const data = new Map(illness)
        if (data.has(secondId)) {
          const newIllness = data.get(secondId)
          data.delete(secondId)
          data.set(secondId, res.list.reduce((pre, cur) => {
            const index = pre.findIndex(d => d.id === cur.id)
            if (index === -1) {
              pre.push(cur)
            } else {
              pre.splice(index, 1, cur)
            }
            return pre
          }, newIllness || []))
        } else {
          data.set(secondId, res.list)
        }
        setIllness(data)
      })
    }
    setLoading(false)
  }

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


  return (
    <View>
      <NavigationBar leftNode={<Tabs
        tabList={getTabList}
        current={firstId}
        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 category={d} illness={illness} loading={loading} onChange={changeSecond}/>
              </SwiperItem>)
            }
          </Swiper>
          : <Empty name='暂无疾病分类'/>
      }
    </View>
  )
}

export default Sort
