import { Button, Input, View } from '@tarojs/components'
import Taro, { faceVerifyForPay, useDidShow } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import dayjs from 'dayjs'
import styles from './index.module.scss'
import ItemList from './components/itemList'
import Search from '@/components/search'
import { dataLoadingStatus, getFilterData } from '@/common/util'
import Popup from '@/components/popup'
import InfiniteScroll from '@/components/infiniteScroll'
import { formatDateTime, formatHashTag, formatImgUrl, formatPriceDiv, formatWeightDiv } from '@/common/format'
import {
  MpCashManagementOrderList,
} from '@/api/newCollection'
import TimePickerPopup from '@/components/timePickerPopup'
import IconFont from '@/components/iconfont/iconfont'

const NewCollection = () => {
  const myDate = new Date()
  const [searchField, setSearchField] = useState<
  {
    page: number
    size: number
    search_name: string
    start_time: number | string
    end_time: number | string
  }>({
    page: 1,
    size: 10,
    search_name: '',
    start_time: `${dayjs(new Date(`${myDate?.toLocaleDateString()} ` + '00:00:00')).subtract(14, 'day').format('YYYY-MM-DD')} 00:00:00`,
    end_time: `${dayjs(new Date(`${myDate?.toLocaleDateString()} ` + '00:00:00')).add(1, 'day').format('YYYY-MM-DD')} 00:00:00`,
  })
  const pageNum = useRef({ size: searchField.size, page: searchField.page })

  // 获取订单列表
  const { fetchData: listFetchData, state: orderState } = MpCashManagementOrderList()
  const [orderData, setOrderData] = useState<{ list: any[]; total: number; summary?: any }>({ list: [], total: 0, summary: {} })

  // 输入了搜索关键字
  const getSearchData = useCallback((e) => {
    pageNum.current.page = 1
    setOrderData(() => ({ list: [], total: 0 }))
    setSearchField(val => ({ ...val, search_name: e, size: 10 }))
  }, [])
  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  const getOrderList = async() => {
    const res = await listFetchData({
      ...searchField,
    })
    setOrderData(e => ({ ...e, list: res.data?.list, total: res.data?.total, summary: res.data?.summary }))
    // setshowPopup(false)
    setRefresherTriggeredStatus(false)
  }
  const getRefresherRefresh = async() => {
    pageNum.current.page = 1
    // pageNum.current.size = 10
    setRefresherTriggeredStatus(true)
    getOrderList()
    setSearchField(val => ({ ...val, size: 10 }))
  }
  // 数据加载状态
  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: orderData.list, total: orderData.total, status: orderState.loading as any })
  }, [orderData, orderState])

  // 上拉加载数据
  const getScrolltolower = useCallback(() => {
    if (orderData.list.length < orderData.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      console.log(pageNum.current.page, 'pageNum.current.page')
      console.log(size, 123123)
      setSearchField({ ...searchField, size })
    }
  }, [orderData])

  // 是否不允许确认筛选
  const isDisabled = useMemo(() => {
    // if (searchField.stage !== '不限' ||
    //     searchField.sale_mode !== '不限' ||
    //     searchField.return_type !== '不限' ||
    //     searchField.start_time !== '' ||
    //     searchField.end_time !== ''
    // ) {
    //     return false
    // } else {
    //     return true
    // }
    return false
  }, [])

  // 新建收款
  const handAdd = () => {
    Taro.navigateTo({
      url: '/pages/addCollection/index',
    })
  }

  // 筛选弹出

  const [SelectPopup, setSelectPopup] = useState(false)

  // 时间数组
  const [TimeList, setTimeList] = useState<any[]>(
    [
      {
        id: 1,
        name: '默认14天内',
        start_time: `${dayjs(new Date(`${myDate?.toLocaleDateString()} ` + '00:00:00')).subtract(14, 'day').format('YYYY-MM-DD')} 00:00:00`,
        end_time: `${dayjs(new Date(`${myDate?.toLocaleDateString()} ` + '00:00:00')).add(1, 'day').format('YYYY-MM-DD')} 00:00:00`,
        checked: true,
      },
      {
        id: 2,
        name: '展示全部日期',
        start_time: '',
        end_time: '',
        checked: false,
      },
    ],
  )

  // 弹窗确认选择
  const handSureSelect = () => {
    pageNum.current.size = 10
    setSearchField({ ...searchField, size: 10 })
    getOrderList()
    setSelectPopup(false)
  }

  // 展示时间筛选
  const [showTime, setShowTime] = useState(false)
  // 关闭时间筛选
  const handClose = () => {
    setShowTime(false)
  }

  const [start, setStart] = useState<any>(myDate.toLocaleDateString())
  const [end, setEnd] = useState<any>('')
  // 选择时间
  const handTime = (eq) => {
    // 直接进来点确定的时候做处理
    if (Object.keys(eq).length === 0) {
      const obj = {
        start: '',
        end: '',
      }
      obj.start = `${dayjs(new Date(`${myDate?.toLocaleDateString()} ` + '00:00:00')).format('YYYY-MM-DD')} 00:00:00`
      obj.end = `${dayjs(new Date(obj?.start)).add(1, 'day').format('YYYY-MM-DD')} 00:00:00`
      eq.value = obj
    }
    setSearchField(val => ({ ...val, start_time: eq?.value?.start, end_time: eq?.value?.end }))
    setStart(eq?.value?.start)
    setEnd(eq?.value?.end)
    setShowTime(false)
    pageNum.current.size = 10
  }
  useDidShow(() => {
    getOrderList()
  })

  // 监听筛选条件变化
  useEffect(() => {
    getOrderList()
  }, [searchField.size, searchField.search_name])
  const timeArea = useMemo(() => {
    // const res = TimeList.filter(item => {
    //     return item.checked
    // })
    // && res.length > 0
    if (end !== '') {
      return `${start}   ` + '-' + `  ${end}`
    }
    else {
      return '自定义起始时间'
    }
  }, [end])

  useEffect(() => {
    setSearchField(searchField)
  }, [searchField])
  // 选择时间item
  const handSelect = (it) => {
    TimeList.map((item) => {
      if (item.id == it.id) {
        item.checked = true
      }
      else {
        item.checked = false
      }
      return item
    })
    setTimeList([...TimeList])
    pageNum.current.size = 10
    setSearchField({ ...searchField, start_time: it.start_time, end_time: it.end_time, size: 10 })
    setEnd('')
  }

  // 重置
  const handReset = () => {
    TimeList.map((item) => {
      if (item.id == 1) {
        item.checked = true
      }
      else {
        item.checked = false
      }
      return item
    })
    setTimeList([...TimeList])
    pageNum.current.size = 10
    setSearchField({
      ...searchField,
      start_time: `${dayjs(new Date(`${myDate?.toLocaleDateString()} ` + '00:00:00')).subtract(14, 'day').format('YYYY-MM-DD')} 00:00:00`,
      end_time: `${dayjs(new Date(`${myDate?.toLocaleDateString()} ` + '00:00:00')).add(1, 'day').format('YYYY-MM-DD')} 00:00:00`,
      size: 10,
    })
    setStart(myDate.toLocaleDateString())
    setEnd('')
  }
  return (
    <>
      <View style={{ background: '#FFFFFF', paddingLeft: '20rpx', paddingBottom: '20rpx', position: 'sticky', top: '0', zIndex: '99' }}>
        <Search placeholder="请输入客户或客户跟进人" showBtn={false} changeOnSearch={getSearchData} >
          <View className={styles.flexBox} onClick={() => { setSelectPopup(true) }}>
            <IconFont name="icon-shaixuan" size={35} color={!isDisabled ? '#0D7CFF' : ''} customClassName={styles.activeshaixuan} />
            {/* <View className={classnames('iconfont', 'icon-shaixuan', !isDisabled ? styles.icon_shaixuan : styles.activeshaixuan)}></View> */}
            <View className={classnames(isDisabled ? styles.shaixuan : styles.activeshai)}>筛选</View>
          </View>
        </Search>
      </View>
      <View className={styles.pageTop}>
        <View className={styles.pageTopLeft}>时间默认14天内</View>
        <View className={styles.pageTopRight}>金额汇总：{formatPriceDiv(orderData?.summary?.receipt_amount)}</View>
      </View>
      <View className={styles.order_list}>
        <InfiniteScroll
          statusMore={statusMore}
          selfonScrollToLower={getScrolltolower}
          refresherEnabled
          refresherTriggered={refresherTriggeredStatus}
          selfOnRefresherRefresh={getRefresherRefresh}
        >
          {orderData?.list?.map((item, index) => {
            return (
              <View key={item.id} className={styles.order_item_con}>
                <ItemList
                  obj={item}
                  key={index}
                ></ItemList>
              </View>
            )
          })}
        </InfiniteScroll>
        <View className={styles.kongboxTwo}></View>
        <View className={styles.fixedBox}>
          <View className={styles.addBtn} onClick={() => handAdd()}>新建收款</View>
        </View>
      </View>
      <Popup title="选择日期" show={SelectPopup} onClose={() => { setSelectPopup(false) }}>
        <View className={styles.popupBox}>
          <View className={styles.timeFlex}>
            {
              TimeList.map((item, index) => {
                return (
                  <View onClick={() => handSelect(item)} className={classnames((item.checked && timeArea == '自定义起始时间') ? styles.activetimeOne : styles.timeOne)} key={index}>{item.name}</View>
                )
              })
            }
          </View>
          <View className={classnames(timeArea == '自定义起始时间' ? styles.timeBox2 : styles.activetimeBox2)} onClick={() => { setShowTime(true) }}>{timeArea}
            <View className={styles.more}>
              {
                timeArea == '自定义起始时间'
                                && <IconFont name="icon-chakanquanbukehu" color="#000000" size={40} customClassName={styles.more}></IconFont>
              }
            </View>
            {/* {
                            timeArea == '自定义起始时间' && <View className={classnames('iconfont', 'icon-chakanquanbukehu', styles.more)}></View>
                        } */}
          </View>
          <View className={styles.safeBox} ></View>
          <View className={styles.bottomBox}>
            <Button className={styles.resetBox} onClick={() => { handReset() }}> 重置</Button >
            <Button className={classnames(isDisabled ? styles.button : styles.activeButton)} disabled={isDisabled} onClick={() => handSureSelect()}> 确认</Button >
          </View>
        </View>
      </Popup>
      <TimePickerPopup
        start={start}
        end={end}
        showTime={showTime}
        closePopup={handClose}
        onSelectDate={e => handTime(e)}
      ></TimePickerPopup>
    </>
  )
}
export default NewCollection
