import { View } from '@tarojs/components'
import classnames from 'classnames'
import React, { FC, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import dayjs from 'dayjs'
import styles from './index.module.scss'
import NormalButton from '@/components/normalButton'
import Search from '@/components/search'
import IconFont from '@/components/iconfont/iconfont'
import { EnumTakeGoodsOrderTypeList } from '@/api/index'
import { getFilterData } from '@/common/util'
import FilterButton from '@/components/filterButton'

interface SearchFilter {
  take_goods_order_type?: number
  timeKey?: string
}

export interface SearchField extends Omit<SearchFilter, 'timeKey'> {
  date_min?: string
  date_max?: string
}

interface DeliveryPropsType {
  onSearchTime?: () => void
  onConfirm?: (searchField: SearchField, timeKey?: Pick<SearchFilter, 'timeKey'>['timeKey']) => void
  onCancal?: () => void
  onReset?: () => void
}

export const filterTimeOptions = {
  0: {
    name: '不限',
    date_min: undefined,
    date_max: undefined,
  },
  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`,
  },
} as const

const DeliveryFilter = (props: DeliveryPropsType) => {
  const { onSearchTime, onConfirm, onCancal, onReset } = props

  const { fetchData, state } = EnumTakeGoodsOrderTypeList()

  const [searchFilter, setSearchFilter] = useState<SearchFilter>({
    take_goods_order_type: undefined,
    timeKey: '0',
  })
  const handleSelectedType = (type: string | number) => {
    console.log('type==>', type)
    if (typeof type === 'string' && type === 'default') {
      setSearchFilter(e => ({ ...e, take_goods_order_type: undefined }))
    }
    else {
      setSearchFilter(e => ({ ...e, take_goods_order_type: type as number }))
    }
  }

  const typeList = useMemo<{ id: number; name: string }[]>(() => {
    return state.data.list
  }, [state])

  const getEnumData = async() => {
    await fetchData()
  }
  useEffect(() => {
    if (!typeList?.length) {
      getEnumData()
      console.log('getEnumData')
    }
  }, [typeList])
  const [customTime, setCustomTime] = useState({
    date_min: undefined,
    date_max: undefined,
  })

  const handleSelectedTime = (timeOptionId) => {
    setSearchFilter(e => ({ ...e, timeKey: timeOptionId }))
    // 不是设置了自定义时间
    if (timeOptionId !== '6') {
      setCustomTime({
        date_min: filterTimeOptions[timeOptionId].date_min,
        date_max: filterTimeOptions[timeOptionId].date_max,
      })
      return
    }
    onSearchTime?.()
  }

  const handleReset = () => {
    setSearchFilter({ take_goods_order_type: undefined, timeKey: '0' })
    onReset?.()
  }
  const handleConfirm = () => {
    const changedField = {
      take_goods_order_type: searchFilter.take_goods_order_type,
      date_min: customTime.date_min,
      date_max: customTime.date_max,
    }
    console.log('changedField==>', changedField)
    onConfirm?.(changedField, searchFilter.timeKey)
  }

  return (
    <>
      <View className={styles.filterItem}>
        <View className={styles['filterItem--title']}>提货类型</View>
        <View className={classnames(styles['filterItem--wrapper'], styles['filter--type'])}>
          <FilterButton isActive={searchFilter.take_goods_order_type == undefined} onClick={() => handleSelectedType('default')}>
            不限
          </FilterButton>
          {!!typeList?.length
            && typeList?.map((item, key) => {
              return (
                <FilterButton key={key} isActive={searchFilter.take_goods_order_type === item?.id} onClick={() => handleSelectedType(item?.id)}>
                  {item.name}
                </FilterButton>
                // <NormalButton type='info' circle onClick={() => handleSelectedType(item?.id)}>
                //   {item.name}
                // </NormalButton>
              )
            })}
        </View>
      </View>

      <View className={styles.filterItem}>
        <View className={styles['filterItem--title']}>查询日期</View>
        <View className={classnames(styles['filterItem--wrapper'], styles['filter--time'])}>
          {Object.entries(filterTimeOptions).map(([key, value], index) => {
            return (
              <FilterButton key={index} isActive={searchFilter.timeKey === key} onClick={() => handleSelectedTime(key)}>
                {value.name}
              </FilterButton>
            )
          })}
          <FilterButton isActive={searchFilter.timeKey === '6'} customClassName={styles.filterTimeButton} onClick={() => handleSelectedTime('6')}>
            自定义时间<IconFont name="icon-chakanquanbukehu" size={40} color={searchFilter.timeKey === '6' ? '#4581ff' : '#909090'}></IconFont>
          </FilterButton>
        </View>
      </View>
      <View className={styles.filterController}>
        <NormalButton type="primary" plain round customClassName={classnames(styles.btn, styles.rest_btn)} onClick={handleReset}>
          重置
        </NormalButton>
        <NormalButton type="primary" round customClassName={classnames(styles.btn, styles.verify_btn)} onClick={handleConfirm}>
          确认
        </NormalButton>
      </View>
    </>
  )
}

export default memo<DeliveryPropsType>(DeliveryFilter)
