import type { ITouchEvent } from '@tarojs/components'
import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import ItemList from './components/itemList'
import Search from '@/components/search'
import NormalButton from '@/components/normalButton'
import InfiniteScroll from '@/components/infiniteScroll'
import { dataLoadingStatus, debounce, getFilterData } from '@/common/util'
import { alert, goLink } from '@/common/common'
import { CancelColorCardOrder, GetColorCardOrderList } from '@/api/colorCard'
import Empty from '@/components/empty'
import { COLOR_CARD_LIST_EMPTY_IMAGE } from '@/common/constant'
import SelectColorCardStatus from '@/components/SelectColorCardStatus'

const GetColorCard = () => {
  const { fetchData, state } = GetColorCardOrderList()
  const getData = async() => {
    const res = await fetchData(getFilterData(searchField))
    if (!res.success) {
      return alert.error(res.msg)
    }
    setColorList({ list: res.data.list, total: res.data.total })
    setRefresherTriggeredStatus(false)
  }

  // status 1 申请中  2 已完成
  // 页码和页数
  const [searchField, setSearchField] = useState<{ name?: string; status?: number; page: number; size: number }>({
    name: '',
    status: 0,
    page: 1,
    size: 10,
  })
  const [colorList, setColorList] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })

  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  // 数据加载状态
  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: colorList.list, total: colorList.total, status: state.loading! })
  }, [colorList, state.loading])
  // 筛选参数
  // 上拉加载数据
  const pageNum = useRef({ size: searchField.size, page: searchField.page })

  const getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearchField(val => ({ ...val, size: 10 }))
  }
  const getScrollToLower = useCallback(() => {
    if (colorList.list.length < colorList.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      setSearchField({ ...searchField, size })
    }
  }, [colorList])

  // 领取色卡
  const getColorCard = () => {
    goLink('/pages/getColorCard/colorCardList/index')
  }

  // 搜索
  const getSearchData = debounce((value: string) => {
    setSearchField(e => ({ ...e, name: value }))
  }, 300)

  const handleClickFilter = (value) => {
    if (searchField.status === value) { return }
    setSearchField(e => ({ ...e, status: value }))
  }

  useEffect(() => {
    getData()
  }, [searchField])

  const { fetchData: cancelOrderApi } = CancelColorCardOrder()

  const cancelOrder = async(id) => {
    const res = await cancelOrderApi({ id })
    if (res.success) {
      getData()
    }
  }

  // 取消订单
  const handleCancel = (e: ITouchEvent, id: number) => {
    e.stopPropagation()
    Taro.showModal({
      content: '确定取消该订单？',
      confirmColor: '#337fff',
      confirmText: '确认',
      success: (res) => {
        if (res.confirm) {
          cancelOrder(id)
          console.log('用户点击确定')
        }
      },
    })
  }

  // 监听选择的类型
  // useEffect(() => {
  //   setSearchObj(search)
  //   if (search.goodsId) { getGoodList() }
  // }, [search])

  return <View className={styles.main}>
    <View className={styles.search}>
      <Search placeholder="请输入客户或业务员" showBtn={false} changeOnSearch={getSearchData} />
    </View>
    <SelectColorCardStatus onChange={handleClickFilter} />
    <View className={styles.color_card_list}>
      <InfiniteScroll
        emptySlot={<Empty picUrl={COLOR_CARD_LIST_EMPTY_IMAGE} text="还没有领取过色卡" />}
        statusMore={statusMore}
        selfonScrollToLower={getScrollToLower}
        refresherEnabled
        refresherTriggered={refresherTriggeredStatus}
        selfOnRefresherRefresh={getRefresherRefresh}
        safeAreaInsetBottom={false}
      >
        {colorList?.list?.map((item, index) => {
          return (
            <View key={item.id} className={styles.order_item}>
              <ItemList data={item} key={index} cancel={e => handleCancel(e, item.order_id)}></ItemList>
            </View>
          )
        })}
      </InfiniteScroll>
    </View>
    <View className={styles.bottomBar}>
      <NormalButton
        customClassName={styles.bottomBar__button}
        type="primary"
        round
        onClick={getColorCard}
      >
          领取色卡
      </NormalButton>
    </View>
  </View>
}

export default GetColorCard
