import { View } from '@tarojs/components'
import Taro, { useDidShow, useRouter, useUnload } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import Search from '@/components/search'
import NormalButton from '@/components/normalButton'
import LabAndImg from '@/components/LabAndImg'
import Tag from '@/components/tag'
import MCheckbox from '@/components/checkbox'
import InfiniteScroll from '@/components/infiniteScroll'
import { dataLoadingStatus, debounce, getFilterData } from '@/common/util'
import { alert, goLink } from '@/common/common'
import { GetCanAddCardList } from '@/api/colorCard'
import { formatRemoveHashTag } from '@/common/format'

const ColorCardList = () => {
  const { fetchData, state } = GetCanAddCardList()

  const [orderList, setOrderList] = useState<{ list: any[]; total: number }>({
    list: [],
    total: 0,
  })
  const multipleSelection = useRef<typeof orderList['list']>([])
  // 搜索
  const getSearchData = debounce((value: string) => {
    console.log('search', value)
  }, 300)
  // 取消
  const handleCancel = () => {
    Taro.navigateBack()
  }

  const router = useRouter()

  // redirectTo 会触发 onLoad 事件
  let isRedirect = false
  // 确认
  const handleSubmit = () => {
    const cache = Taro.getStorageSync('colorCardCache')
    let cacheArr: any[] = multipleSelection.current
    if (cache) {
      cacheArr = [...cacheArr, ...JSON.parse(cache)]
    }
    Taro.setStorageSync('colorCardCache', JSON.stringify(cacheArr))
    if (router?.params.isGoBack) {
      isRedirect = true
      Taro.navigateBack({
        delta: 1,
      })
    }
    else {
      isRedirect = true
      // 携带id跳转
      goLink('/pages/getColorCard/addColorCard/index', null, 'redirectTo')
    }
  }

  const labAndImgObj = useCallback((item) => {
    return { lab: item?.lab, rgb: item?.rgb, texture_url: item?.texture_url }
  }, [])
  // 页码和页数
  const [searchField, setSearchField] = useState<{ name?: string; color_card_ids?: number[]; page: number; size: number }>({
    name: '',
    color_card_ids: [],
    page: 1,
    size: 10,
  })

  const getData = async() => {
    const res = await fetchData(getFilterData(searchField))
    if (!res.success) {
      return alert.error(res.msg)
    }
    setOrderList({ list: res.data.list, total: res.data.total })
  }

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

  useDidShow(() => {
    const cache = Taro.getStorageSync('colorCardCache')
    if (cache) {
      setSearchField(val => ({ ...val, color_card_ids: JSON.parse(cache).map(item => item.id) }))
    }
  })

  useDidShow(() => {

  })

  // 上拉加载数据
  const pageNum = useRef({ size: searchField.size, page: searchField.page })
  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  // 下拉刷新
  const getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearchField(val => ({ ...val, size: 10 }))
  }
  // 数据加载状态
  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: orderList.list, total: orderList.total, status: state.loading! })
  }, [orderList, state.loading])

  const getScrollToLower = useCallback(() => {
    if (orderList.list.length < orderList.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      setSearchField({ ...searchField, size })
    }
  }, [orderList])
  // 选择
  const onSelect = (item: any) => {
    console.log('item==>', item)
    setOrderList((prev: any) => {
      prev.list?.forEach((val) => {
        if (val.id === item.id) {
          val.status = true
          multipleSelection.current = [...multipleSelection.current, val]
        }
      })
      return { list: prev.list, total: prev.total }
    })
  }
  // 未选择
  const onUnSelect = (item: any) => {
    setOrderList((prev: any) => {
      prev.list?.forEach((val) => {
        if (val.id === item.id) {
          val.status = false
          multipleSelection.current = multipleSelection.current.filter(mul => mul.id !== val.id)
        }
      })
      return { list: prev.list, total: prev.total }
    })
    console.log('multipleSelection', multipleSelection.current)
  }

  const handleClickCheckBox = (item: any) => {
    console.log('item', item)
    if (!item.is_add) {
      if (item.status) {
        onUnSelect(item)
      }
      else {
        onSelect(item)
      }
    }
  }
  const noop = (e) => {
    e.stopPropagation()
  }

  useUnload(() => {
    console.log('onUnload', isRedirect)
    if (!isRedirect) {
      Taro.removeStorageSync('colorCardCache')
    }
  })

  return <View className={styles.main}>
    <View className={styles.search}>
      <Search placeholder="请输入搜索面料/色卡" showBtn={false} changeOnSearch={getSearchData} >
        <View className={styles.search__cancel} onClick={handleCancel}>取消</View>
      </Search>
    </View>
    <View className={styles.context}>
      <InfiniteScroll
        statusMore={statusMore}
        selfonScrollToLower={getScrollToLower}
        refresherEnabled
        refresherTriggered={refresherTriggeredStatus}
        selfOnRefresherRefresh={getRefresherRefresh}
        safeAreaInsetBottom={false}
      >
        {
          orderList.list.map((item) => {
            return <View key={item.id} style={{ padding: '0 16px', backgroundColor: 'white' }} onClick={() => handleClickCheckBox(item)}>
              <View className={styles.colorCard}>
                <View style={{ minWidth: '24%' }}>
                  <View className={styles.colorCard__image}>
                    <LabAndImg value={labAndImgObj(item)} />
                    {
                      item.is_multiple_product ? <View className={styles.imageTag}>多面料共用</View> : null
                    }
                  </View>
                </View>
                <View className={styles.colorCard__content}>
                  <View className={styles.colorCard__title}>{item.color_card_name}</View>
                  <View className={styles.colorCard__code}>
                    {
                      item.affiliation_product?.map((colorCode, index) => {
                        return <Tag customStyle={{ marginRight: '5px', marginBottom: '2px', padding: '5px', background: '#e3ecff', color: '#558cff', borderColor: '#e3ecff' }} key={index} size="small" circle>{formatRemoveHashTag(colorCode.code)}</Tag>
                      })
                    }
                  </View>
                </View>
                <View className={styles.addButton} onClick={noop}>
                  <MCheckbox
                    disabled={item.is_add}
                    status={item.is_add || item.status}
                    onSelect={() => onSelect(item)}
                    onClose={() => onUnSelect(item)}
                  />
                </View>
              </View>
            </View>
          })
        }
      </InfiniteScroll>

    </View>
    <View className={styles.bottomBar}>
      <NormalButton
        customClassName={styles.bottomBar__button}
        type="primary"
        round
        disabled={multipleSelection.current.length === 0}
        onClick={handleSubmit}
      >
        {
          multipleSelection.current.length ? `确认（已选 ${multipleSelection.current.length} 个）` : '确认'
        }
      </NormalButton>

    </View>
  </View>
}
export default ColorCardList
