import { ScrollView, View, Text } from '@tarojs/components'
import React, { useCallback, useEffect, useState } from 'react'
import indexStore from '@src/store/index'
import './index.less'
/**
 * 热门 tabs
 */

type props = {
    hotValue: {
        name: string,
        id: number,
        color?: string,     // 选中字体颜色
        backColor?: string  // 选中背景颜色
    }[],
    hotTabIndex?: number,  // tab选中第几个  默认1
    onBack?: (value: number) => void,     // 切换回调函数
    scroll?: boolean
}

const BookHotTabs = (props: props) => {
    let { hotValue, hotTabIndex = 1, onBack, scroll = true } = props

    let [stateIndex, setStateIndex] = useState<number>(hotTabIndex)
    let selectHandle = useCallback((value: number, index: number) => {
        setStateIndex(index)
        onBack?.(value)
        indexStore.setData({ indexCategoryId: value })
    }, [stateIndex])
    // 列表数据改变重新设置第一个为选中状态样式
    useEffect(()=>{
        setStateIndex(1)
    },[hotValue])
    return <View className="hotTabs">
        {
            scroll ? <ScrollView scrollX style={{ whiteSpace: 'nowrap' }} className="scroll">
                {
                    hotValue?.map((item, index) => {
                        return <View className={`tab`} style={index === stateIndex - 1 ? item?.backColor ? { backgroundColor: item.backColor } : { backgroundColor: '#E5EBFA' } : {}} onClick={() => { selectHandle(item.id, index + 1) }}>
                            <Text style={index === stateIndex - 1 ? item?.color ? { color: item.color } : { color: '#253C6F' } : {}}>{item.name}</Text>
                        </View>
                    })
                }
            </ScrollView> :
                <View>
                    {
                        hotValue?.map((item, index) => {
                            return <View className="tab scrollTab" onClick={() => { selectHandle(item.id, index + 1) }}>
                                <Text>{item.name}</Text>
                            </View>
                        })
                    }
                </View>
        }

    </View>
}

export default React.memo(BookHotTabs)