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

export default () => {
  const { fetchData, state: cardState } = GetColorCardApi()
  const [colorCardData, setColorCardData] = useState<{ list: ParamType[]; total: number }>({
    list: [],
    total: 0,
  })
  const [searchData, setSearchData] = useState<{ color_card_ids?: number[]; name?: string; page: number; size: number }>({
    page: 1,
    size: 10,
  })

  const shopColorCardData = useRef<ParamType[]>([])

  // 获取已加入购物车的数据id
  const getShopId = () => {
    if (shopColorCardData.current.length <= 0) { return null }
    return shopColorCardData.current?.map((item) => {
      return item.id
    })
  }

  // 获取数据
  const getGetColorCard = async() => {
    console.log('getShopId():::', getShopId())
    const { data } = await fetchData(getFilterData({ ...searchData, color_card_ids: getShopId() }))
    setColorCardData(() => ({ list: data.list, total: data.total }))
    setRefresherTriggeredStatus(() => false)
  }

  useEffect(() => {
    if (Taro.getStorageSync('colorCard') && shopColorCardData.current.length <= 0) {
      shopColorCardData.current = Taro.getStorageSync('colorCard') ? JSON.parse(Taro.getStorageSync('colorCard')) : []
      // Taro.removeStorageSync('colorCard')
    }
    getGetColorCard()
  }, [searchData])

  const getSearch = (con) => {
    setSearchData(e => ({ ...e, name: con }))
  }
  const onReset = () => {
    setSearchData(e => ({ ...e, name: '' }))
  }

  // 选择的数据
  const [selectList, setSelectList] = useState<ParamType[]>([])

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

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

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

  const onSubmit = () => {
    if (selectList.length <= 0) { return alert.none('请选择色卡') }
    selectList?.map((item) => {
      item.count = 1
    })
    Taro.setStorageSync('colorCard', JSON.stringify([...selectList, ...shopColorCardData.current]))
    Taro.redirectTo({
      url: '/pages/colorCardOrder/index',
    })
  }

  const onSelectData = (val, status) => {
    if (status) {
      setSelectList(e => [...e, val])
    }
    else {
      const res = selectList?.filter((item) => {
        return val.id != item.id
      })
      setSelectList(e => res)
    }
  }

  return <View className={styles.main}>
    <View className={styles.search}>
      <Search defaultValue={searchData?.name} placeholder="请输入搜索面料/色卡" changeOnSearch={getSearch} debounceTime={300} />
      <View className={styles.btn_reset} onClick={onReset}>取消</View>
    </View>
    <View className={styles.get_card_con}>
      <InfiniteScroll
        selfonScrollToLower={getScrolltolower}
        refresherTriggered={refresherTriggeredStatus}
        statusMore={statusMore}
        refresherEnabled
        selfOnRefresherRefresh={getRefresherRefresh}
      >
        {colorCardData.list?.map((item) => {
          return (
            <View className={styles.get_card_list} key={item.id}>
              <ProductItem {...item} onSelect={onSelectData} />
            </View>
          )
        })}
      </InfiniteScroll>
    </View>
    <View className={styles.get_card_btn} onClick={onSubmit}>
      <Text>确认</Text>
    </View>
  </View>
}
