import { View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import React, { ReactNode, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import Tag from './components/Tag'
import Sort from './components/Sort'
import ChoseCity from './components/ChoseCity'
import ItemList from './components/ItemList'
import Popup from '@/components/popup'
import { dataLoadingStatus, debounce, getFilterData } from '@/common/util'
import { alert, goLink } from '@/common/common'
import { formatDateTime, formatPriceDiv, formatWeightDiv } from '@/common/format'
import Search from '@/components/search'
import InfiniteScroll from '@/components/infiniteScroll'
import { ClientListApi } from '@/api/order'
import SelectGroup from '@/components/SelectGroup'

const CustomerManagement = () => {
  const [searchField, setSearchField] = useState<
  {
    page: number
    size: number
    label_ids: string
    purchaser_type: number | string
    name_phone_or_sale_user: string
    province_id: any[] | string
    city_id: any[] | string
    abstract_sort_key: string
  }
  >({
    page: 1,
    size: 10,
    label_ids: '',
    purchaser_type: '',
    name_phone_or_sale_user: '',
    province_id: '',
    city_id: '',
    abstract_sort_key: '',
  })

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

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

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

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

  // 上拉加载数据
  const pageNum = useRef({ size: searchField.size, page: searchField.page })
  // 输入了搜索关键字
  const getSearchData = useCallback((e) => {
    pageNum.current.page = 1
    setOrderData(() => ({ list: [], total: 0 }))
    setSearchField(val => ({ ...val, name_phone_or_sale_user: e, size: 10 }))
  }, [])
  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 getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearchField(val => ({ ...val, size: 10 }))
  }

  // 选择排序
  const sortRefRef = useRef<any>()
  const handSort = useCallback((e: string) => {
    pageNum.current.page = 1
    setSearchField(val => ({ ...val, size: 10, abstract_sort_key: e }))
    sortRefRef.current = e
  }, [])

  const SortRef = useRef<any>()
  const TagRef = useRef<any>()

  // 筛选城市
  const ChoseCityRef = useRef<any>()
  const handCity = useCallback((provinceVal, cityVal) => {
    const provinceArr: number[] = []
    const cityArr: number[] = []
    provinceVal.length && provinceVal.forEach((item) => {
      provinceArr.push(item.id)
    })
    cityVal.length && cityVal.forEach((item) => {
      cityArr.push(item.id)
    })
    pageNum.current.page = 1
    const provinceRes = provinceArr?.toString()
    const cityRes = cityArr?.toString()
    console.log(provinceRes, cityRes)
    setSearchField(val => ({ ...val, province_id: provinceArr.length > 0 ? provinceRes : '', city_id: cityArr.length > 0 ? cityRes : '', size: 10 }))
    // ChoseCityRef.current.close()
  }, [])

  // 选择客户类型
  const handType = useCallback((val) => {
    const arr = val.filter((item) => { return item.checked })
    pageNum.current.page = 1
    setSearchField(val => ({ ...val, size: 10, purchaser_type: arr[0]?.id }))
  }, [])

  // 选择标签
  const handTags = useCallback((val) => {
    const arr: any[] = []
    const arrOne = val.filter((item) => { return item.checked })
    arrOne.forEach((item) => {
      arr.push(item.id)
    })
    pageNum.current.page = 1
    const res = arr.toString()
    setSearchField(val => ({ ...val, size: 10, label_ids: arr.length === 0 ? '' : res }))
  }, [])

  return (
    <View className={styles.mainBox}>
      <View className={styles.topBox}>
        <View className={styles.search_input}>
          <Search placeholder="搜索客户名称、电话、业务员" showBtn={false} changeOnSearch={getSearchData} />
        </View>
        <View className={styles.menuBox} >
          <SelectGroup>
            <Sort ref={SortRef} handSort={handSort} onCloseOverlay={() => true}></Sort>
            <ChoseCity ref={ChoseCityRef} handCity={handCity} onCloseOverlay={() => true}></ChoseCity>
            <Tag ref={TagRef} handTags={handTags} handType={handType} onCloseOverlay={() => true}></Tag>
          </SelectGroup>
        </View>
      </View>
      <View className={styles.totalFont}>共 {orderData?.total || 0} 个客户</View>
      <View className={styles.order_list}>
        <InfiniteScroll
          statusMore={statusMore}
          selfonScrollToLower={getScrollToLower}
          refresherEnabled
          refresherTriggered={refresherTriggeredStatus}
          selfOnRefresherRefresh={getRefresherRefresh}
        >
          {orderData?.list?.map((item, index) => {
            return (
              <ItemList key={index} sortId={sortRefRef.current} obj={item}></ItemList>
            )
          })}
        </InfiniteScroll>
      </View>
      <View className={styles.bottom_box}>
        <View className={styles.bottom_btn} onClick={() => goLink('/pages/customerEditor/index?type=add')}>新增客户</View>
      </View>
    </View >
  )
}

export default CustomerManagement
