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 { DeliverNoticeOrderList, EnumSaleorderStatus } 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'

interface SearchData {
  delivery_notice_order_no?: string // 发货单号
  delivery_notice_order_status?: number | string // 发货状态
  date_min?: string // 开始时间
  date_max?: string // 结束时间
  type?: number // 发货类型
  page: number
  size: number
}

const defaultSearchFields = {
  delivery_notice_order_status: 0, // 待发货
  page: 1,
  size: 10,
}

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

  const isFirst = useRef(true)

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

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

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

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

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

  const getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearch(val => ({ ...val, size: 10 }))
  }
  const getData = async() => {
    console.log('search===>', search)
    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 }) => {
    let fuckingBadCodeId: string | number = 0
    if (statusId === 3) {
      fuckingBadCodeId = 0
    }
    else if (statusId === 4) {
      fuckingBadCodeId = '1,2'
    }
    setCurrentStatus(statusName)
    setSearch(e => ({ ...e, delivery_notice_order_status: fuckingBadCodeId }))
  }

  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, delivery_notice_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(() => {
    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
          statusMore={statusMore}
          selfonScrollToLower={getScrollToLower}
          refresherEnabled
          refresherTriggered={refresherTriggeredStatus}
          selfOnRefresherRefresh={getRefresherRefresh}
        >
          <Text className={styles['listBox--total']}>
            {currentStatus}共 {deliveryOrderList.total} 单
          </Text>
          {deliveryOrderList.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
