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 { ParamItem } from './components/productItem'
import ProductItem from './components/productItem'
import type { ColorItem } from '@/components/popupSelectColor'
import PopupSelectColor from '@/components/popupSelectColor'
import InfiniteScroll from '@/components/infiniteScroll'
import Search from '@/components/search'
import { dataLoadingStatus, getFilterData } from '@/common/util'
import { GetSampleOrderProductApi } from '@/api/cutSample'
import { alert, goLink } from '@/common/common'

export default () => {
  const { fetchData, state: cardState } = GetSampleOrderProductApi()
  const [orderData, setOrderData] = useState<{ list: ParamItem[]; total: number }>({
    list: [],
    total: 0,
  })
  const [searchData, setSearchData] = useState<{ product_ids?: string; product_code_and_name?: string; page: number; size: number }>({
    page: 1,
    size: 10,
  })

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

  // 获取数据
  const getGetColorCard = async() => {
    const { data } = await fetchData(getFilterData({ ...searchData }))
    setOrderData(() => ({ list: data.list, total: data.total }))
    setRefresherTriggeredStatus(() => false)
  }

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

  useEffect(() => {
    if (Taro.getStorageSync('cutSample')) {
      const res = Taro.getStorageSync('cutSample') ? JSON.parse(Taro.getStorageSync('cutSample')) : []
      const selectProsuctIds: number[] = []
      res.map((item) => {
        selectProsuctIds.push(item.id)
      })
      setSelectProsuctIds(selectProsuctIds)
      setSelectProcutColors(res)
      if (selectProsuctIds.length > 0) {
        setSearchData(e => ({ ...e, product_ids: selectProsuctIds.join(',') }))
      }
    }
  }, [])

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

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

  // 上拉加载数据
  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 [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  const getRefresherRefresh = async() => {
    pageNum.current.size = 10
    pageNum.current.page = 1
    setRefresherTriggeredStatus(true)
    setSearchData(val => ({ ...val, size: 10 }))
  }

  const onSubmit = () => {
    if (selectProcutColors.length <= 0) { return alert.none('请选择剪样') }
    Taro.setStorageSync('cutSample', JSON.stringify([...selectProcutColors]))
    const pages = getCurrentPages()
    const current = pages[pages.length - 2]
    if (current?.route === 'pages/cutSampleListOrder/index') {
      Taro.navigateBack()
    }
    else {
      Taro.redirectTo({
        url: '/pages/cutSampleListOrder/index',
      })
    }
  }

  const [showColorList, setShowColorList] = useState(false)
  const [selectItem, setSelectItem] = useState<ParamItem>()
  const onSelectData = (val: ParamItem) => {
    setShowColorList(true)
    setSelectItem(val)

    // 获取该面料下的颜色数据
    const index = selectProsuctIds.indexOf(val.id)
    if (index !== -1) {
      const colorIds: number[] = []
      selectProcutColors[index].colors?.map((citem) => {
        colorIds.push(citem.id)
      })
      setSelectColorIds(colorIds)
    }
  }
  const onClose = () => {
    setShowColorList(false)
  }

  const [selectProcutColors, setSelectProcutColors] = useState < (ParamItem & { colors: ColorItem[] })[] > ([])
  const [selectProsuctIds, setSelectProsuctIds] = useState<number[]>([])
  const [selectColorIds, setSelectColorIds] = useState<number[]>([])
  const onSelected = (val: ColorItem[]) => {
    val.map((item) => {
      if (!item.count) { item.count = 1 }
    })
    const pIndex = selectProcutColors?.findIndex(item => item.id === selectItem?.id)
    if (pIndex === -1) {
      const data: any = { ...selectItem }
      data.colors = val
      selectProcutColors.push(data)
    }
    else {
      selectProcutColors[pIndex].colors = val
    }
    if (selectItem?.id && !selectProsuctIds.includes(selectItem?.id)) {
      selectProsuctIds.push(selectItem?.id)
      setSelectProsuctIds(selectProsuctIds)
    }
    setSelectProcutColors(selectProcutColors)
    setShowColorList(false)
  }

  return <View className={styles.main}>
    <View className={styles.search}>
      <Search defaultValue={searchData?.product_code_and_name} placeholder="请输入搜索面料" changeOnSearch={getSearch} debounceTime={500} />
      <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}

      >
        {orderData.list?.map((item) => {
          return (
            <View className={styles.get_card_list} key={item.id}>
              <ProductItem selected={selectProsuctIds.includes(item.id)} productItem={item} onSelect={onSelectData} />
            </View>
          )
        })}
      </InfiniteScroll>
    </View>
    <View className={styles.get_card_btn} onClick={onSubmit}>
      <Text className={classNames(selectProsuctIds.length > 0 ? styles.selected : '')}>确认</Text>
    </View>
    <PopupSelectColor defaultValueIds={selectColorIds} onSelected={onSelected} show={showColorList} product_id={selectItem?.id || 0} onClose={onClose} />
  </View>
}
