import { Text, View } from '@tarojs/components'
import dayjs from 'dayjs'
import { FC, forwardRef, memo, useImperativeHandle, useRef, useState } from 'react'
import DropDownItem from '../dropDown-item'
import FilterButton from '../filterButton'
import IconFont from '../iconfont/iconfont'
import TimePickerPopup from '../timePickerPopup'
import styles from './index.module.scss'
import { formatDateTime } from '@/common/format'

export type ChangedValue = string[]

interface SelectSaleTypeProps {
  defaultValue?: Key // 默认值
  timeOptions?: Record<string, Value> // 支持自定义 时间配置
  onChange?: (value: ChangedValue) => void
  onCloseOverlay?: () => void
}

const FilterTimeOptions = {
  0: {
    name: '全部',
    date_min: '',
    date_max: '',
  },
  1: {
    name: '今天',
    date_min: `${dayjs(new Date())
      .add(0, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
    date_max: `${dayjs(new Date())
      .add(1, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
  },
  2: {
    name: '昨日',
    date_min: `${dayjs(new Date())
      .add(-1, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
    date_max: `${dayjs(new Date())
      .add(0, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
  },
  3: {
    name: '近7日',
    date_min: `${dayjs(new Date())
      .add(-7, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
    date_max: `${dayjs(new Date())
      .add(0, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
  },
  4: {
    name: '近30日',
    date_min: `${dayjs(new Date())
      .add(-30, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
    date_max: `${dayjs(new Date())
      .add(0, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
  },
  5: {
    name: '近90日',
    date_min: `${dayjs(new Date())
      .add(-90, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
    date_max: `${dayjs(new Date())
      .add(0, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
  },
  custom: {
    name: '自定义时间',
    date_min: '',
    date_max: '',
  },
}

type Key = keyof typeof FilterTimeOptions
type Value = typeof FilterTimeOptions[Key]

const SelectTimePicker = (props: SelectSaleTypeProps, ref) => {
  const { onChange: change, onCloseOverlay, defaultValue = '0', timeOptions = FilterTimeOptions } = props
  // rerender 的时候需要更新 ref 的值
  const Options = useRef({ ...timeOptions, custom: FilterTimeOptions.custom })
  Options.current = { ...timeOptions, custom: FilterTimeOptions.custom }

  const [currentValue, setCurrentValue] = useState(defaultValue)

  const [currentDate, setCurrentDate] = useState({
    start: new Date().toLocaleDateString(),
    end: '',
  })

  // 展示时间筛选
  const [showTime, setShowTime] = useState(false)

  // 点击关闭时间筛选
  const handClose = () => {
    setShowTime(false)
  }
  const customFilterButtonText = useRef('自定义时间')

  const handleClick = (key: Key) => {
    setCurrentValue(key)
    change?.([Options.current[key].date_min, Options.current[key].date_max])
    customFilterButtonText.current = '自定义时间'
  }

  // 选择自定义时间
  const onSelectDate = (event) => {
    console.log(event?.value, 'event?.value?.start')
    setCurrentDate({
      start: event?.value?.start,
      end: event?.value?.end,
    })
    setShowTime(false)
    customFilterButtonText.current = `${dayjs(event?.value?.start).format('YYYY年MM月DD日')} 至 ${dayjs(event?.value?.end).format('YYYY年MM月DD日')}`
    change?.([event?.value?.start, event?.value?.end])
  }

  // const [customFilterButtonText, setCustomFilterButtonText] = useState('自定义时间')

  // 点击自定义时间
  const handleCustomTime = () => {
    setCurrentValue('custom')
    setShowTime(true)
  }
  const dropDownRef = useRef<any>(null)

  useImperativeHandle(
    ref,
    () => {
      return {
        show: dropDownRef.current.show,
        showPopup: dropDownRef.current.showPopup,
        closePopup: dropDownRef.current.closePopup,
      }
    },
    [dropDownRef.current],
  )
  return (
    <>
      <DropDownItem
        title={currentValue === '0' ? '查询日期' : Options.current[currentValue].name}
        direction="down"
        value={currentValue}
        activeColor="#337fff"
        ref={dropDownRef}
        onCloseOverlay={onCloseOverlay}
      >
        <View className={styles.grid} style={{ paddingBottom: '24rpx' }}>
          {Object.entries(Options.current)
            .slice(0, -1)
            .map(([key, value], index) => {
              return (
                <FilterButton key={index} isActive={key === currentValue} onClick={() => handleClick(key as Key)}>
                  {value.name}
                </FilterButton>
              )
            })}
          <FilterButton customClassName={styles.customFilterTime} isActive={currentValue === 'custom'} onClick={handleCustomTime}>
            <Text>{customFilterButtonText.current}</Text>
            <IconFont name="icon-chakanquanbukehu" color={currentValue === 'custom' ? '#3983ff' : '#7f7f7f'}></IconFont>
          </FilterButton>
        </View>
      </DropDownItem>
      <TimePickerPopup start={currentDate.start} end={currentDate.end} showTime={showTime} closePopup={handClose} onSelectDate={onSelectDate}></TimePickerPopup>
    </>
  )
}
export default memo(forwardRef(SelectTimePicker))
