import { View } from '@tarojs/components'
import type { FC } from 'react'
import { memo, useEffect, useMemo, useState } from 'react'
import classnames from 'classnames'
import DropDownItem from '../dropDown-item'
import FilterButton from '../filterButton'
import styles from './index.module.scss'
import { SaleOrderDataFormdataFormStatus } from '@/api/index'

type ChangedValue = string | number

interface SelectSaleTypeProps {
  onChange?: (value: ChangedValue) => void
  dropDownStyle?: React.CSSProperties
  dropDownClassName?: string
  defaultValue?: ChangedValue
}

interface EnumList {
  id: number
  code: string
  name: string
}
// 销售排行指标
const SelectSaleRankingIndicators: FC<SelectSaleTypeProps> = (props) => {
  const selectName = '排行指标'

  const { onChange, dropDownStyle, dropDownClassName, defaultValue = 1 } = props
  console.log(props)
  const { fetchData } = SaleOrderDataFormdataFormStatus()

  const [enumList, setEnumList] = useState<EnumList[]>([])
  const getData = async() => {
    const res = await fetchData()
    setEnumList(res.data.list)
  }

  useEffect(() => {
    getData()
  }, [])

  const [currentValue, setCurrentValue] = useState<ChangedValue>(defaultValue)

  const handleClick = (value: ChangedValue) => {
    setCurrentValue(value)
    onChange?.(value)
  }

  const displayTitle = useMemo(() => {
    if (currentValue === defaultValue) {
      return selectName
    }
    return enumList.length ? enumList.filter(option => option.id === currentValue)?.[0]?.name : selectName
  }, [enumList, currentValue])

  return (
    <DropDownItem title={displayTitle} customClassName={dropDownClassName} customStyle={dropDownStyle} value={currentValue} activeColor="#337fff" showOverlay={false}>
      <View className={classnames(styles.grid)}>
        {!!enumList.length
          && enumList.map((item: EnumList, key) => {
            return (
              <FilterButton key={key} isActive={item.id === currentValue} onClick={() => handleClick(item.id)}>
                {item.name}
              </FilterButton>
            )
          })}
      </View>
    </DropDownItem>
  )
}
export default memo(SelectSaleRankingIndicators)
