import { Text, View } from '@tarojs/components'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import type { FC } from 'react'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import ItemList from './components/ItemList'
import DeliveryStatusList from './components/DeliveryStatusList'
import type { SearchField } from './components/Filter'
import DeliveryFilter from './components/Filter'
import Search from '@/components/search'
import { TakeGoodsOrderList } from '@/api/index'
import InfiniteScroll from '@/components/infiniteScroll'
import { dataLoadingStatus, getFilterData } from '@/common/util'
import IconText from '@/components/iconText'
import IconFont from '@/components/iconfont/iconfont'
import Popup from '@/components/popup'
import TimePickerPopup from '@/components/timePickerPopup'
import Empty from '@/components/empty'
import { LIST_EMPTY_IMAGE } from '@/common/constant'

interface SearchData {
  take_goods_order_no?: string // 提货单号
  take_goods_status?: number | string // 提货状态
  date_min?: string // 开始时间
  date_max?: string // 结束时间
  take_goods_order_type?: number // 提货类型
  page: number
  size: number
}

const defaultSearchFields = {
  take_goods_status: 0, // 待提货
  page: 1,
  size: 10,
}

// 提货列表
const Delivery: FC = () => {
  const [search, setSearch] = useState<SearchData>(defaultSearchFields)
  const [takeDeliveryOrderList, setDeliveryOrderList] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })

  const isFirst = useRef(true)

  const { fetchData: FetchDeliveryOrderList, state: orderState } = TakeGoodsOrderList()
  // 数据加载状态
  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: takeDeliveryOrderList.list, total: takeDeliveryOrderList.total, status: orderState.loading! })
  }, [takeDeliveryOrderList, orderState])

  // 输入搜索关键字
  const getSearchData = useCallback((searchValue: string) => {
    setSearch(prevProps => ({ ...prevProps, take_goods_order_no: searchValue }))
    console.log('searchValue==>', searchValue)
  }, [])

  // 上拉加载数据
  const pageNum = useRef({ size: search.size, page: search.page })

  const getScrollToLower = useCallback(() => {
    if (takeDeliveryOrderList.list.length < takeDeliveryOrderList.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      setSearch(e => ({ ...e, size }))
    }
  }, [takeDeliveryOrderList])

  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)

  const getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearch(val => ({ ...val, size: 10 }))
  }
  // 请求数据
  const getData = async() => {
    const res = await FetchDeliveryOrderList(getFilterData(search))

    setDeliveryOrderList(e => ({ ...e, list: res.data?.list, total: res.data?.total }))
    setRefresherTriggeredStatus(() => false)
  }

  const [currentStatus, setCurrentStatus] = useState('提货中')

  const handleChangeStatus = ({ id: statusId, name: statusName }) => {
    setCurrentStatus(statusName)
    setSearch(e => ({ ...e, take_goods_status: statusId }))
  }

  const handleAuditSuccess = () => {
    getData()
  }

  const [showFilter, setShowFilter] = useState(false)
  // 筛选列表
  const onShowFilter = () => {
    setShowFilter(true)
  }
  // 点击关闭筛选列表框
  const handlePopupClose = () => {
    setShowFilter(false)
  }

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

  // 点击关闭时间筛选
  const handClose = () => {
    setShowTime(false)
  }
  const [start, setStart] = useState(new Date().toLocaleDateString())
  const [end, setEnd] = useState('')
  // 选择时间
  const handTime = (event) => {
    console.log(event?.value, 'event?.value?.start')
    setStart(event?.value?.start)
    setEnd(event?.value?.end)
    setShowTime(false)
    console.log(search, 8888)
  }
  // 显示时间选择器
  const handleSearchTime = () => {
    setShowTime(true)
  }
  // 筛选框点击确认
  const handleConfirm = (changedFields: SearchField, timeKey) => {
    console.log('changedFields==>changedFields', changedFields)
    // 自定义时间
    if (timeKey === '6') {
      setSearch(prevProps => ({ ...prevProps, ...changedFields, date_min: start, date_max: end }))
    }
    else {
      setSearch(prevProps => ({ ...prevProps, ...changedFields }))
    }
    handlePopupClose()
  }
  // 筛选框点击重置
  const handleReset = () => {
    setSearch(defaultSearchFields)
    handlePopupClose()
  }

  const scanIcon = () => {
    // 扫描
    const handleScan = () => {
      Taro.scanCode({
        success(res) {
          setSearch(e => ({ ...e, take_goods_order_no: res.result }))
        },
        fail(res) {
          console.log(res)
        },
      })
    }
    return (
      <View onClick={handleScan} className={styles.scanHandler}>
        <IconFont name="icon-saomiao" size={40}></IconFont>
      </View>
    )
  }
  useEffect(() => {
    console.log('useEffect ===> search', search)
    //  已经不是第一次加载该页面了
    if (!isFirst.current) {
      getData()
    }
  }, [search])

  useDidShow(() => {
    getData()
    isFirst.current = false
  })
  return (
    <View className={styles.delivery}>
      <View className={styles.searchBox}>
        <Search placeholder="请输入或扫描条形码" showBtn={false} changeOnSearch={getSearchData} customRightSlot={scanIcon()}>
          <View onClick={onShowFilter} className={styles.icon__filter}>
            <IconText svg iconName="icon-shaixuan" text="筛选" customClass={styles['icon--filter']} />
          </View>
        </Search>
      </View>
      {/* 状态栏 */}
      <DeliveryStatusList onChangeStatus={handleChangeStatus}></DeliveryStatusList>

      <View className={styles.listBox}>
        <InfiniteScroll
          emptySlot={<Empty picUrl={LIST_EMPTY_IMAGE} text="暂无数据" />}
          statusMore={statusMore}
          selfonScrollToLower={getScrollToLower}
          refresherEnabled
          refresherTriggered={refresherTriggeredStatus}
          selfOnRefresherRefresh={getRefresherRefresh}
        >
          <Text className={styles['listBox--total']}>
            {currentStatus}共 {takeDeliveryOrderList.total} 单
          </Text>
          {takeDeliveryOrderList.list.map((item, index) => {
            return <ItemList itemData={item} key={item.id} onSuccess={handleAuditSuccess}></ItemList>
          })}
        </InfiniteScroll>
      </View>
      <Popup show={showFilter} title="筛选列表" onClose={handlePopupClose}>
        <DeliveryFilter onSearchTime={handleSearchTime} onConfirm={handleConfirm} onReset={handleReset} />
      </Popup>
      <TimePickerPopup start={start} end={end} showTime={showTime} closePopup={handClose} onSelectDate={e => handTime(e)}></TimePickerPopup>
    </View>
  )
}

export default Delivery
