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

type ChangedValue = string | number

interface SelectSaleTypeProps {
  onChange?: (value: ChangedValue) => void
  onCloseOverlay?: () => void
  defaultValue?: ChangedValue
}

interface EnumList {
  id: number
  code: string
  name: string
}
// 销售类型
const SelectSaleType = (props: SelectSaleTypeProps, ref) => {
  const selectName = '销售类型'
  const { onChange, defaultValue = 0, onCloseOverlay } = props
  console.log(props)
  const { fetchData } = EnumSalesTypeApi()
  const [enumList, setEnumList] = useState<EnumList[]>([])

  const getData = async() => {
    const res = await fetchData()
    setEnumList([{ id: -1, code: '', name: '全部' }, ...res.data.list])
  }

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

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

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

  const dropDownRef = useRef<any>(null)

  useImperativeHandle(
    ref,
    () => {
      return {
        show: dropDownRef.current.show,
        showPopup: dropDownRef.current.showPopup,
        closePopup: dropDownRef.current.closePopup,
      }
    },
    [dropDownRef.current],
  )

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

  return (
    <DropDownItem title={displayTitle} value={currentValue} activeColor="#337fff" ref={dropDownRef} onCloseOverlay={onCloseOverlay}>
      <View className={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(forwardRef(SelectSaleType))
