import { ScrollView, View } from '@tarojs/components'
import { memo, useEffect, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'

interface Param {
  list: { id: number; name: string }[]
  defaultId?: number | null
  onSelect?: (val: number) => void
}
const OrderStatusList = ({ list = [], defaultId = null, onSelect }: Param) => {
  const [selectInfo, setSelectInfo] = useState({
    selected: -1, // 当前选中的id
    tabId: '', // 需要滚动到的id
  })

  const clickEvent = ({ item, index }: { item: any; index: number }) => {
    const num = index > 0 ? index - 1 : 0
    setSelectInfo(e => ({ ...e, tabId: list[num].id.toString(), selected: item.id }))
    onSelect?.(item.id)
  }
  useEffect(() => {
    if (typeof defaultId === 'number' && defaultId >= 0) {
      console.log('defaultId:::', defaultId)
      const index = list?.findIndex((item) => {
        return item.id == defaultId
      })
      if (index !== -1) {
        const num = index > 0 ? index - 1 : 0
        setSelectInfo(e => ({ ...e, tabId: list[num].id.toString() }))
      }
    }
    setSelectInfo(e => ({ ...e, selected: defaultId || -1 }))
  }, [defaultId])
  return (
    <View className={styles.order_status_list}>
      <ScrollView scrollX scrollIntoView={`tabs_${selectInfo.tabId}`} scrollWithAnimation>
        <View className={styles.order_list_scroll}>
          {list.map((item, index) => {
            return (
              <View
                key={item.id}
                id={`tabs_${item.id}`}
                onClick={() => clickEvent({ item, index })}
                className={classnames(styles.order_status_item, selectInfo.selected == item.id && styles.selected)}
              >
                {item.name}
              </View>
            )
          })}
        </View>
      </ScrollView>
    </View>
  )
}
export default memo(OrderStatusList)
