import { Button, Image, Input, ScrollView, View } from '@tarojs/components'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import Search from '@/components/search'
import { MpEnumSaleUserList } from '@/api/order'
import InfiniteScroll from '@/components/infiniteScroll'
import { dataLoadingStatus, getFilterData } from '@/common/util'

const SaleUserPage = () => {
  const [search, setSearch] = useState({
    name: null,
    page: 1,
    size: 10,
  })
  const [clentList, setClientlist] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })

  const { fetchData: clitentFetch, state: orderState } = MpEnumSaleUserList()
  // 数据加载状态
  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: clentList.list, total: clentList.total, status: orderState.loading! })
  }, [clentList, orderState])

  const [clientObj, setclientObj] = useState({
    saleuserId: null,
    saleuserName: '',
  })

  const pageNum = useRef({ size: search.size, page: search.page })
  // 输入了搜索关键字
  const getSearchData = useCallback((eq) => {
    pageNum.current.page = 1
    setClientlist(() => ({ list: [], total: 0 }))
    setSearch(e => ({ ...e, name: eq, size: 10 }))
  }, [])

  const router = useRouter()

  // 上拉加载数据
  const getScrolltolower = useCallback(() => {
    if (clentList.list.length < clentList.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      setSearch(e => ({ ...e, size }))
      console.log(search, 11111)
    }
  }, [clentList])

  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  const getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearch(val => ({ ...val, size: 10 }))
  }
  const getCuss = async() => {
    const res = await clitentFetch({ name: search.name === null ? '' : search.name, page: search.page, size: search.size })
    if (router?.params.clientId) {
      res.data.list.map((item) => {
        if (item.id == router?.params.clientId) {
          item.checked = true
        }
        else {
          item.checked = false
        }
        return item
      })
    }
    setClientlist(e => ({ ...e, list: res.data?.list, total: res.data?.total }))
    setRefresherTriggeredStatus(() => false)
  }
  // 选择业务员
  const selectClient = (item) => {
    clentList.list.map((it) => {
      if (item.id === it.id) {
        it.checked = true
      }
      else {
        it.checked = false
      }
      return it
    })
    const pages = Taro.getCurrentPages() // 获取当前的页面栈
    const prevPage = pages[pages.length - 2]
    prevPage.setData({ // 设置上一个页面的值
      saleuserId: item.id,
      saleuserName: item.name,
    })
    setClientlist(e => ({ ...e, list: clentList?.list, total: clentList?.total }))
    setclientObj(item)
    Taro.navigateBack({
      delta: 1,
    })
  }
  useEffect(() => {
    if (clientObj?.saleuserId !== null) {
      setclientObj(clientObj)
    }
    else {
      const pages = Taro.getCurrentPages() // 获取当前的页面栈
      const prevPage = pages[pages.length - 2]
      prevPage.setData({ // 设置上一个页面的值
        saleuserId: '',
        saleuserName: '',
      })
    }
  }, [clientObj])

  useEffect(() => {
    if (search.name === '') {
      setSearch(e => ({ ...e, name: null }))
    }
    if (search.name !== '') { getCuss() }
  }, [search])
  return (
    <View className={styles.cussBox}>
      <View className={styles.searchBox}>
        <View className={styles.two}>
          <Search placeholder="请输入业务员名称" showBtn={false} changeOnSearch={getSearchData} />
        </View>

      </View>
      <View className={styles.listBox}>
        <InfiniteScroll
          statusMore={statusMore}
          selfonScrollToLower={getScrolltolower}
          refresherEnabled
          refresherTriggered={refresherTriggeredStatus}
          selfOnRefresherRefresh={getRefresherRefresh}
        >
          {
            clentList.list.map((item, index) => {
              return (
                <View className={classnames(item.checked ? styles.acticveitemBox : styles.itemBox)} key={index} onClick={() => { selectClient(item) }}>
                  <View className={styles.cussName}>{item.name}</View>
                  <View className={styles.phone}>{item.phone}</View>
                  <View className={styles.woker}>{item.sale_user_name}</View>
                </View>
              )
            })
          }
        </InfiniteScroll>
      </View>

    </View>
  )
}

export default SaleUserPage
