import { View } from '@tarojs/components'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import Goods from './components/goods'
import ShopCart from './components/shoppingCart'
import Search from '@/components/search'
import Empty from '@/components/empty'
import { MpProductList } from '@/api/search'
import { dataLoadingStatus, debounce, getFilterData } from '@/common/util'
import {
  MpProductColorList,
} from '@/api/order'
import { ProductListApi } from '@/api/index'
import InfiniteScroll from '@/components/infiniteScroll'

const SearchPage = () => {
  const pages = Taro.getCurrentPages() // 获取当前的页面栈
  const prevPage = pages[pages.length - 2]
  const router: any = useRouter()
  const onj = JSON.parse(Taro.getStorageSync('userInfo'))
  const [search, setSearchObj] = useState({
    modeId: router.params.sale_mode,
    goodsId: null,
    code_or_name: '',
    physical_warehouse: onj.physical_warehouse,
    purchaser_id: -1,
  })

  const [paramGoods, setparamGoods] = useState<any[]>([])

  useDidShow(() => {
    prevPage.setData({ // 设置上一个页面的值
      selectGoodsList: [],
      productId: '',
    })
    let arr: any[] = []
    arr = JSON.parse(decodeURIComponent(router.params.goodList))
    setparamGoods(arr)
  })

  const [goodList, setGoodlist] = useState<any[]>([])

  const [showShopCart, setShowShopCart] = useState(false)

  // 获取商品
  const { fetchData: colorlistFetch } = MpProductColorList()
  const getGoodList = async() => {
    const res = await colorlistFetch({ product_id: search.goodsId, code_or_name: search.code_or_name, physical_warehouse: search?.physical_warehouse, purchaser_id: router.params.purchaser_id })
    res.data.list.map((item) => {
      item.showInput = false
      if (search.modeId == 0) {
        item.nums = 1
        item.buyNums = 1
      }
      if (search.modeId == 1) {
        item.nums = 0.3
        item.buyNums = 0.3
      }
      if (search.modeId == 2) {
        item.nums = 3
        item.buyNums = 3
      }
      return item
    })
    paramGoods?.forEach((edg) => {
      if (search.goodsId == edg.id) {
        edg?.product_colors?.forEach((it) => {
          res.data.list?.map((gg) => {
            if (it.id == gg.id) {
              gg.isChecked = true
            }
            return gg
          })
        })
      }
    })
    setGoodlist([...res.data.list])
  }

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

  // 确认添加
  const handSure = () => {
    setShowShopCart(false)
    let arr: any[] = []
    // 洗数据将面料Id底下的数据再装到自己的颜色列表里面
    arr = orderData?.list?.filter((item) => {
      return item.id == search.goodsId
    })
    const filterArr = goodList.filter((item) => {
      return item.showInput
    })
    arr.forEach((item) => {
      filterArr.forEach((it) => {
        // it.sale_price = search.modeId == 0 ? it.bulk_price : search.modeId == 1 ? it.length_cut_price : it.weight_cut_price
        item.product_colors = [...filterArr]
      })
    })
    if (filterArr.length > 0) {
      prevPage.setData({ // 设置上一个页面的值
        selectGoodsList: arr,
        productId: search.goodsId,
      })
    }
    Taro.navigateBack({
      delta: 1,
    })
  }

  // 点击输入框的加
  const handPlus = useCallback((item) => {
    goodList.map((it) => {
      if (item.id === it.id) {
        if (isInteger(item.nums)) {
          item.nums++
        }
        else {
          item.nums++
          item.nums = Math.trunc(item.nums)
        }
      }
      return item
    })
    setGoodlist([...goodList])
  }, [goodList])

  // 输入了搜索关键字
  const getSearchDataInput = useCallback((eq) => {
    setSearchObj(e => ({ ...e, code_or_name: eq }))
  }, [])

  const [goodObj, setGoodsobj] = useState({})
  const ShopCartRef = useRef<any>()
  // 点击对应商品显示购物车
  const showCart = async(item) => {
    setSearchObj(e => ({ ...e, goodsId: item.id, purchaser_id: router.params.purchaser_id }))
    setShowShopCart(true)
    setGoodsobj(item)
    ShopCartRef.current.SearchRef.current.clearInput()
  }

  // 点击加展示输入框
  const handAdd = useCallback((item) => {
    goodList.map((it) => {
      if (item.id === it.id) {
        it.showInput = true
      }
      return item
    })
    setGoodlist([...goodList])
  }, [goodList])

  // 点击减
  const reduceNums = useCallback((item) => {
    goodList.map((it) => {
      if (item.id === it.id) {
        if (isInteger(item.nums)) {
          item.nums--
        }
        else {
          item.nums = Math.trunc(item.nums)
        }

        if (search.modeId == 0) {
          if (item.nums < 1) {
            it.showInput = false
            it.nums = 1
          }
        }
        if (search.modeId == 1) {
          if (item.nums < 0.3) {
            it.showInput = false
            it.nums = 0.3
          }
        }
        if (search.modeId == 2) {
          if (item.nums < 3) {
            it.showInput = false
            it.nums = 3
          }
        }
      }
      return item
    })
    setGoodlist([...goodList])
  }, [goodList])

  // 选择类型
  //   const handCheckMode = (item) => {
  //     typeList.map((it) => {
  //       if (it.id === item.id) {
  //         it.checked = true
  //         setSearchObj(e => ({ ...e, modeId: it.id }))
  //       }
  //       else {
  //         it.checked = false
  //       }
  //       return it
  //     })
  //     setTypeList([...typeList])
  //     setGoodlist([])
  //   }

  // 关闭弹窗
  const closePoup = () => {
    setShowShopCart(false)
  }

  // 搜索商品的数组
  const [searchList, setSearchList] = useState<any[]>([])
  // 是否有值输入框
  const [hasFonts, setHasFonts] = useState(false)
  //   useEffect(() => {
  //     getHistory()
  //   }, [])

  // 搜索获取商品数据
  const { fetchData: productFetch } = MpProductList()
  const getProduct = debounce(async(e) => {
    Taro.showLoading({
      title: '加载中...',
      mask: true,
    })
    // await historyputFetch({ key: e, scene: 0 }).then((res) => {
    //   if (res.data) {
    //     getHistory()
    //   }
    // })
    productFetch({ code_or_name: e }).then((res) => {
      if (res.data) {
        Taro.hideLoading()
        setSearchList([...res?.data?.list])
      }
    })
  }, 300)

  // 输入了搜索关键字
  const getSearchData = useCallback((e) => {
    if (e) {
      setHasFonts(true)
      getProduct(e)
    }
    else {
      setHasFonts(false)
      setSearchList([])
    }
  }, [])

  // 返回
  const back = () => {
    Taro.navigateBack({
      delta: 1,
    })
  }
  // 判断是否整数类型
  function isInteger(obj) {
    return (obj | 0) === obj
  }

  // 输入框失焦
  const onBlur = (e, id) => {
    goodList.map((item) => {
      if (item.id == id) {
        if (search.modeId == 0 && (e.detail.value == '' || Number(e.detail.value) == 0)) {
          item.showInput = false
          item.nums = 1
        }
        else if (search.modeId == 0 && (e.detail.value != '' || Number(e.detail.value) > 0)) {
          item.nums = e.detail.value
        }
        if (search.modeId == 1 && Number(e.detail.value) < 0.3) {
          item.nums = 0.3
          item.showInput = false
        }
        else if (search.modeId == 1 && Number(e.detail.value) >= 0.3) {
          if (isInteger(Number(e.detail.value))) {
            item.nums = Number(e.detail.value)
          }
          else {
            item.nums = Number(e.detail.value).toFixed(2)
          }
        }
        if (search.modeId == 2 && Number(e.detail.value) < 3) {
          item.nums = 3
          item.showInput = false
        }
        else if (search.modeId == 2 && Number(e.detail.value) >= 3) {
          if (isInteger(Number(e.detail.value))) {
            item.nums = Number(e.detail.value)
          }
          else {
            item.nums = Number(e.detail.value).toFixed(2)
          }
        }
      }
      return item
    })
    setGoodlist([...goodList])
  }

  // 选择中后的值到输入框
  const [defaultvalue, setdefaultvalue] = useState('')

  const { fetchData: productFetchData, state: orderState } = ProductListApi()

  // 页码和页数
  const [searchField, setSearchField] = useState<{ page: number; size: number }>({
    page: 1,
    size: 10,
  })

  // 监听筛选条件变化
  useEffect(() => {
    getOrderList()
  }, [searchField])

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

  const pageNum = useRef({ size: searchField.size, page: searchField.page })

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

  const getScrolltolower = useCallback(() => {
    if (orderData.list.length < orderData.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      setSearchField({ ...searchField, size })
    }
  }, [orderData])

  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  const getOrderList = async() => {
    const res = await productFetchData({
      ...getFilterData(searchField),
    })
    setOrderData(e => ({ ...e, list: res.data?.list, total: res.data?.total }))
    setRefresherTriggeredStatus(() => false)
  }

  const getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearchField(val => ({ ...val, size: 10 }))
  }

  return (
    <View className={styles.main}>
      <View className={styles.topBox}>
        <Search placeholder="请输入搜索布料" defaultValue={defaultvalue} showBtn={false} changeOnSearch={getSearchData} >
          <View className={styles.cancelFont} onClick={() => back()}>取消</View>
        </Search>
      </View>
      <View className={styles.line}></View>
      {
        !hasFonts && <>
          <View className={styles.order_list}>
            <InfiniteScroll
              statusMore={statusMore}
              selfonScrollToLower={getScrolltolower}
              refresherEnabled
              refresherTriggered={refresherTriggeredStatus}
              selfOnRefresherRefresh={getRefresherRefresh}
            >
              {orderData?.list?.map((item, index) => {
                return (
                  <View key={item.id} className={styles.order_item_con}>
                    <Goods clickItem={() => showCart(item)} key={index} data={item}></Goods>
                  </View>
                )
              })}
            </InfiniteScroll>
          </View>
        </>
      }
      {
        hasFonts && <>
          <View className={styles.topBox}>
            <View className={styles.histroyLeft}>
              <View className={styles.histroyFonts}>搜索结果</View>
              {/* <View className={styles.back} onClick={() => handBack()}>返回</View> */}
            </View>
          </View>
          {
            !!searchList.length && searchList.map((item, index) => {
              return (
                <Goods clickItem={() => showCart(item)} key={index} data={item}></Goods>
              )
            })
          }
          {
            !searchList.length && <Empty picUrl="https://cdn.zzfzyc.com/empty.png" text="暂无数据"></Empty>
          }
        </>
      }
      <ShopCart
        ref={ShopCartRef}
        sale_mode={router.params.sale_mode}
        handSure={() => handSure()}
        modeFont={router.params.sale_mode}
        handPlus={item => handPlus(item)}
        obj={goodObj}
        getSearchData={(e) => { getSearchDataInput(e) }}
        hasBottom={false}
        reduceNums={(item) => { reduceNums(item) }}
        addNums={(item) => { handAdd(item) }}
        showPopup={showShopCart}
        closePopup={() => closePoup()}
        goodList={goodList}
        onBlur={(e, id) => onBlur(e, id)}
      ></ShopCart>

    </View>

  )
}
export default memo(SearchPage)
// oninputEvent={(e, item) => { onInputEven?.(e, item) }}
