import { View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import React, { ReactNode, forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import { alert } from '@/common/common'
import { formatDateTime, formatPriceDiv, formatWeightDiv } from '@/common/format'
import DropDownItem from '@/components/dropDown-item'

interface Props {
  handSort?: (any) => void
  value?: any
  onCloseOverlay?: () => void
}

interface ListType {
  name: string
  id: string
  checked: boolean
}
const Sort = (props: Props, ref) => {
  const DropDownItemRef = useRef<any>()
  useImperativeHandle(
    ref,
    () => {
      return {
        show: DropDownItemRef?.current?.show,
        showPopup: DropDownItemRef?.current.showPopup,
        closePopup: DropDownItemRef?.current?.closePopup,
      }
    },
    [DropDownItemRef?.current],
  )

  const [list, setlist] = useState<ListType[]>([
    {
      name: '下单时间正序',
      id: '1',
      checked: false,
    },
    {
      name: '创建时间正序',
      id: '2',
      checked: false,
    },
    {
      name: '更新时间正序',
      id: '3',
      checked: false,
    },
    {
      name: '下单时间倒序',
      id: '-1',
      checked: false,
    },
    {
      name: '创建时间倒序',
      id: '-2',
      checked: false,
    },
    {
      name: '更新时间倒序',
      id: '-3',
      checked: false,
    },
  ])

  const [currentValue, setCurrentValue] = useState<number>(-1)

  const handItem = (it) => {
    list.map((item) => {
      if (item.id == it.id) {
        item.checked = true
      }
      else {
        item.checked = false
      }
      return item
    })
    setlist([...list])
    props.handSort?.(it.id)
  }

  const title = useMemo(() => {
    const arr = list.filter((item) => { return item.checked })
    if (!arr.length) {
      return '默认排序'
    }
    else {
      return arr[0]?.name
    }
  }, [list])

  return (
    <DropDownItem ref={DropDownItemRef} title={title} value={currentValue} activeColor="#337fff" onCloseOverlay={props?.onCloseOverlay}>
      <View className={styles.mainBox}>
        {
          list.map((item, index) => {
            return (
              <View key={index} className={classnames(styles.itemFlex, item.checked && styles.active)} onClick={() => handItem?.(item)}>{item.name}</View>
            )
          })
        }
      </View>
    </DropDownItem>
  )
}
export default memo(forwardRef(Sort))
