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

interface params {
  status?: 'top'|'bottom'|'none'
  onChange?: (val: { status: string; value: string }) => void
  sortValue?: { desc: string; asc: string } // 排序规则，后端制定
}
type sortParam = 'none'|'top'|'bottom'
const SortBtn = ({ status = 'none', onChange, sortValue }: params, ref) => {
  const [sortStatus, setSortStatus] = useState<sortParam>()
  useEffect(() => {
    setSortStatus(() => status)
  }, [status])
  const changeSort = (): { status: sortParam; value: string } => {
    let status: sortParam = 'none'
    let value = ''
    if (sortStatus == 'none') {
      status = 'top'
      value = sortValue?.asc as string
    }
    if (sortStatus == 'top') {
      status = 'bottom'
      value = sortValue?.desc as string
    }
    if (sortStatus == 'bottom') { status = 'none' }
    setSortStatus(() => status)
    onChange?.({ status, value })
    return { status, value }
  }
  useImperativeHandle(ref, () => ({
    changeSort,
  }))

  return (
    <>
      <View className={styles.click} onClick={changeSort}>
        <View className={classnames(styles.top, sortStatus == 'top' && styles.selected)} ></View>
        <View className={classnames(styles.bottom, sortStatus == 'bottom' && styles.selected)}></View>
      </View>
    </>
  )
}
export default forwardRef(SortBtn)
