import { Image, Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classNames from 'classnames'
import type { ParamItem } from '../productItem'
import ProductItem from '../productItem'
import styles from './index.module.scss'
import InfiniteScroll from '@/components/infiniteScroll'
import { alert, goLink } from '@/common/common'
import { ColorCardOrderCancelApi, GetColorCardOrderApi, GetColorCardOrderStatusApi } from '@/api/colorCard'
import { dataLoadingStatus, getFilterData } from '@/common/util'

export default () => {
  const [searchData, setSearchData] = useState<{ status?: number; page: number; size: number }>({
    status: 0,
    page: 1,
    size: 10,
  })

  const [orderData, setOrderData] = useState<{ list: ParamItem[]; total: number }>({
    list: [],
    total: 0,
  })

  const { fetchData: fetchDataOrder, state: OrderState } = GetColorCardOrderApi()
  const getColorCardOrder = async() => {
    const res = await fetchDataOrder(getFilterData(searchData))
    setRefresherTriggeredStatus(false)
    setOrderData(() => res.data)
  }

  useEffect(() => {
    getColorCardOrder()
  }, [searchData])

  useEffect(() => {
    getColorCardOrderStatus()
  }, [])

  // 获取状态列表
  const [statusList, setStatusList] = useState<{ id: 0|1|2; name: string }[]>([])
  const { fetchData: fetchDataStatus } = GetColorCardOrderStatusApi()
  const getColorCardOrderStatus = async() => {
    const res = await fetchDataStatus()
    setStatusList([{ id: 0, name: '全部记录' }, ...res.data.list])
  }

  // 上拉加载数据
  const pageNum = useRef({ size: searchData.size, page: searchData.page })
  const getScrolltolower = useCallback(() => {
    if (orderData.list.length < orderData.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      setSearchData(e => ({ ...e, size }))
    }
  }, [orderData])

  // 数据加载状态
  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: orderData?.list, total: orderData?.total, status: OrderState.loading })
  }, [orderData, OrderState])

  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  const getRefresherRefresh = async() => {
    pageNum.current.page = 1
    setRefresherTriggeredStatus(true)
    setSearchData(val => ({ ...val, size: 10 }))
  }

  const changeStatus = (index: number) => {
    pageNum.current.page = 1
    setSearchData(e => ({ ...e, status: index, page: 1, size: 10 }))
  }

  // 取消订单
  const { fetchData: fetchDataCancel } = ColorCardOrderCancelApi()
  const onCancel = async(id: number) => {
    Taro.showModal({
      title: '确定取消订单？',
      async success(res) {
        if (res.confirm) {
          const res = await fetchDataCancel({ id })
          if (res.success) {
            alert.success('取消成功')
            getColorCardOrder()
          }
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }

  return <>
    <View className={styles.btn_list}>
      {statusList.map(item => <View key={item.id} onClick={() => changeStatus(item.id)} className={classNames(styles.btn_item, searchData.status === item.id && styles.select_ed)}>{item.name}</View>)}
    </View>
    <View className={styles.con}>
      <View className={styles.con_list}>
        <InfiniteScroll
          statusMore={statusMore}
          refresherEnabled
          selfonScrollToLower={getScrolltolower}
          refresherTriggered={refresherTriggeredStatus}
          selfOnRefresherRefresh={getRefresherRefresh}
          defaultUrl="/color_card/colorCardList_empty.png"
          defaultText="还没领取过色卡"
        >
          {orderData.list?.map((item) => {
            return (
              <View key={item.id} className={styles.order_item_con}>
                <ProductItem value={item} onCancel={onCancel} />
              </View>
            )
          })}
        </InfiniteScroll>
      </View>
    </View>
    <View className={styles.get_card_btn} onClick={() => goLink('/pages/colorCardList/index')}>
      <Text>领取色卡</Text>
    </View>
  </>
}
