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
}
export default memo(({ list = [], defaultId = null, onSelect }: Param) => {
  const [selectInfo, setSelectInfo] = useState({
    selected: -1, // 当前选中的id
    tabId: '', // 需要滚动到的id
  })
  useEffect(() => {
    if (defaultId) {
      const index = list?.findIndex((item) => {
        console.log(item.id, defaultId)
        return item.id == defaultId
      })
      if (index !== -1) {
        const num = index > 0 ? (index - 1) : 0
        setSelectInfo(e => ({ ...e, tabId: list[num].id.toString() }))
      }
    }
  }, [defaultId])
  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)
  }

  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>
  )
})
