import { ScrollView, View } from '@tarojs/components'
import Taro, { useReady } from '@tarojs/taro'
import type { ReactNode } from 'react'
import React, { memo, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import type { StatusParam } from '../infiniteScroll'
import InfiniteScroll from '../infiniteScroll'
import LoadingCard from '../loadingCard'
import styles from './index.module.scss'
import ProductClass from '@/pages/index/components/productClass'
import { GetClassList } from '@/api/index'

interface Params {
  list?: any[]
  defaultValue?: number | string
  children?: ReactNode
  height?: string
  heightItem?: number
  sideBarOnClick?: (val: any) => void
  refresherTriggered?: true | false
  selfOnRefresherRefresh?: () => void
  selfOnScrolltolower?: () => void
  hasMore?: true | false
  statusMore?: StatusParam
  selectClass?: (val: number) => void
}
const SideBar = ({
  list = [],
  defaultValue = 0,
  height = '100vh',
  sideBarOnClick,
  children,
  heightItem = 100,
  refresherTriggered = false,
  selfOnRefresherRefresh,
  selfOnScrolltolower,
  hasMore = true,
  statusMore = 0,
  selectClass,
}: Params) => {
  const num_half = useRef(0)

  const [selected, setSelected] = useState(defaultValue)
  const [tabId, setTabId] = useState('')

  useEffect(() => {
    setSelected(defaultValue)
  }, [defaultValue])

  const computeSelectTab = (index) => {
    if ((index + 1) > num_half.current) {
      const num = index + 1 - num_half.current
      setTabId(list[num].id.toString())
    }
    else {
      setTabId(list[0].id.toString())
    }
  }
  const init = () => {
    const index = list?.findIndex((item) => {
      return item.id == defaultValue
    })
    if (index !== -1) {
      computeSelectTab(index)
    }
  }

  useEffect(() => {
    Taro.nextTick(() => {
      const query = Taro.createSelectorQuery()
      query.select('.side_bar_select').boundingClientRect((rect) => {
        console.log('rect::', rect)
        const clientHeight = rect.height
        const clientWidth = rect.width
        const ratio = 750 / clientWidth
        const height = clientHeight * ratio
        num_half.current = Math.ceil(height / 2 / heightItem)
        init()
      }).exec()
    })
  }, [])

  // 二级面料系列分类
  const [openClass, setOpenClass] = useState(false)
  const [classList, setClassList] = useState([])
  const [classId, setClassId] = useState(-1)
  const { fetchData } = GetClassList()
  const getClassData = async(id) => {
    const res = await fetchData({ id })
    if (res.success) {
      if (res.data?.list.length > 0) {
        res.data.list = [{ id: -1, name: '全部' }, ...res.data.list]
      }
      setClassList(() => res.data?.list)
      console.log('res.data?.list=>', res.data?.list)
    }
  }
  useEffect(() => {
    if (selected) { getClassData(selected) }
  }, [selected])

  const getSelectClass = (id) => {
    selectClass?.(id)
    setClassId(() => id)
  }

  const clickEvent = ({ item, index }: { item; index: number }) => {
    setSelected(item.id)
    sideBarOnClick?.(item)
    computeSelectTab(index)
    setClassId(-1)
    selectClass?.(-1)
  }
  return (
    <>
      <View className={classnames(styles.sideBar_main, 'side_bar_select')}>
        <ScrollView scrollWithAnimation style={{ height }} className={styles.sideBar_select} scrollY scrollIntoView={`tab_${tabId}`}>
          {
            list?.map((item, index) => {
              return (
                <View
                  className={classnames(styles.sideBar_select_title, { [styles.sideBar_select_title_select]: (selected == item.id) })}
                  onClick={() => clickEvent({ item, index })}
                  id={`tab_${item.id}`}
                  key={item.id}
                  style={{ height: `${heightItem}rpx` }}
                >
                  {
                    selected == item.id && <View className={styles.shu}></View>
                  }
                  <View className={styles.title_con}>
                    {item.name}
                  </View>
                </View>
              )
            })
          }
        </ScrollView>
        <View className={classnames(classList.length > 0 ? styles.sideBar_con : styles.nosideBar_con)}>
          {classList.length > 0 && (
            <View className={styles.product_class} style={{ height: openClass ? '100%' : '' }}>
              <ProductClass list={classList} open={openClass} onOpenClick={val => setOpenClass(val)} onSelect={getSelectClass} defaultSelectId={classId} />
            </View>
          )}
          <InfiniteScroll statusMore={statusMore} selfonScrollToLower={() => selfOnScrolltolower?.()} refresherTriggered={refresherTriggered} refresherEnabled selfOnRefresherRefresh={() => selfOnRefresherRefresh?.()}>
            {children}
          </InfiniteScroll>
        </View>
      </View>

    </>
  )
}
export default memo(SideBar)
