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 { ClientListApi } from '@/api/order'
import InfiniteScroll from '@/components/infiniteScroll'
import { dataLoadingStatus, getFilterData } from '@/common/util'

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

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

  const [clientObj, setclientObj] = useState({
    clientId: null,
    clientName: '',
  })
  // 上拉加载数据
  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_phone_or_sale_user: 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_phone_or_sale_user: search.name_phone_or_sale_user === null ? '' : search.name_phone_or_sale_user, 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)
  }
  useEffect(() => {
    if (search.name_phone_or_sale_user === '') {
      setSearch(e => ({ ...e, name_phone_or_sale_user: null }))
    }
    if (search.name_phone_or_sale_user !== '') { getCuss() }
  }, [search])
  // 选择客户
  const selectClient = (item) => {
    clentList.list.map((it) => {
      if (item.id === it.id) {
        it.checked = true
      }
      else {
        it.checked = false
      }
      return it
    })
    setclientObj(item)
    const pages = Taro.getCurrentPages() // 获取当前的页面栈
    const prevPage = pages[pages.length - 2]
    prevPage.setData({ // 设置上一个页面的值
      clientId: item.id,
      clientName: item.name,
    })
    setClientlist(e => ({ ...e, list: clentList?.list, total: clentList?.total }))
    Taro.navigateBack({
      delta: 1,
    })
  }
  useEffect(() => {
    if (clientObj?.clientId !== null) {
      setclientObj(clientObj)
    }
    // else {
    //     let pages = Taro.getCurrentPages(); // 获取当前的页面栈
    //     let prevPage = pages[pages.length - 2];
    //     prevPage.setData({ //设置上一个页面的值
    //         clientId: '',
    //         clientName: '',
    //     });
    // }
  }, [clientObj])
  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 CustomerPage
