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

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

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

  const [clientObj, setclientObj] = useState({
    bankId: null,
    bankName: '',
  })

  const router = useRouter()

  // 上拉加载数据
  const pageNum = useRef({ size: search.size, page: search.page })
  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 getSearchData = useCallback((eq) => {
    pageNum.current.page = 1
    setClientlist(() => ({ list: [], total: 0 }))
    setSearch(e => ({ ...e, search_name: eq, size: 10 }))
  }, [])

  // 列表下拉刷新
  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({ search_name: search.search_name === null ? '' : search.search_name, page: search.page, size: search.size })
    if (router?.params.bankId) {
      res.data.list.map((item) => {
        if (item.receiving_account_id == router?.params.bankId) {
          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.search_name === '') {
      setSearch(e => ({ ...e, search_name: null }))
    }
    if (search.search_name !== '') { getCuss() }
  }, [search])
  // 选择业务员
  const selectClient = (item) => {
    clentList.list.map((it) => {
      if (item.receiving_account_id === it.receiving_account_id) {
        it.checked = true
      }
      else {
        it.checked = false
      }
      return it
    })
    const pages = Taro.getCurrentPages() // 获取当前的页面栈
    const prevPage = pages[pages.length - 2]
    prevPage.setData({ // 设置上一个页面的值
      bankId: item.receiving_account_id,
      bankName: item.company_account,
    })
    setClientlist(e => ({ ...e, list: clentList?.list, total: clentList?.total }))
    setclientObj(item)
    Taro.navigateBack({
      delta: 1,
    })
  }
  useEffect(() => {
    if (clientObj?.bankId !== null) {
      setclientObj(clientObj)
    }
    //  else {
    //     let pages = Taro.getCurrentPages(); // 获取当前的页面栈
    //     let prevPage = pages[pages.length - 2];
    //     prevPage.setData({ //设置上一个页面的值
    //         bankId: '',
    //         bankName: '',
    //     });
    // }
  }, [clientObj])
  return (
    <View className={styles.cussBox}>
      {/* <View className={styles.searchBox}>
                <View className={styles.two}>
                    <Search placeholder='请输入收款账户' showBtn={false} changeOnSearch={getSearchData} debounceTime={300} />
                </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.company_account}</View>
                  {/* <View className={styles.phone}>{item.phone}</View>
                                    <View className={styles.woker}>{item.company_account}</View> */}
                </View>
              )
            })
          }
        </InfiniteScroll>
      </View>

    </View>
  )
}

export default AccountPage
