import { View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import ApplyRecord from '../components/applyRecord'
import ReturnLogistics from '../components/returnLogistics'
import ReturnPayCheck from '../components/returnPayCheck'
import styles from './index.module.scss'
import Order from './components/order'
import OrderStatusList from './components/orderStatusList'
import InfiniteScroll from '@/components/infiniteScroll'
import { dataLoadingStatus, getFilterData } from '@/common/util'
import { GetSaleOrderListApi, RefundOrderSatausApi } from '@/api/salesAfterOrder'
import useLogin from '@/use/useLogin'
import Search from '@/components/search'

const SalesAfterList = () => {
  useLogin()

  // 搜索参数
  const [searchField, setSearchField] = useState<{ status: number | null; page: number; size: number; name: string }>({
    status: null,
    page: 1,
    size: 10,
    name: '',
  })

  // 获取订单状态
  const [statusList, setStatusList] = useState<any[]>([{ id: -1, name: '全部' }])
  const { fetchData: fetchDataStatus } = RefundOrderSatausApi()
  const getOrderStatusList = async() => {
    const res = await fetchDataStatus()
    setStatusList(e => [...e, ...res.data.list])
  }
  useEffect(() => {
    getOrderStatusList()
    setSearchField(e => ({ ...e, status: -1 }))
  }, [])

  // 获取订单列表
  const { fetchData: listFetchData, state: orderState } = GetSaleOrderListApi()
  const [orderData, setOrderData] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })

  // 上拉加载数据
  const pageNum = useRef({ size: searchField.size, page: searchField.page })
  const getScrolltolower = useCallback(() => {
    if (orderData.list.length < orderData.total) {
      pageNum.current.page++
      const size = pageNum.current.size * pageNum.current.page
      setSearchField(e => ({ ...e, size }))
    }
  }, [orderData])

  // 状态改变
  const changeStatus = useCallback((e) => {
    pageNum.current.page = 1
    setSearchField(value => ({ ...value, status: e, size: 10 }))
    setOrderData(() => ({ list: [], total: 0 }))
  }, [])

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

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

  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  const getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearchField(val => ({ ...val, size: 10 }))
  }
  const getOrderList = async() => {
    const res = await listFetchData(getFilterData(searchField))
    setOrderData({ list: res.data.list, total: res.data.total })
    setRefresherTriggeredStatus(() => false)
  }
  // 监听点击的按钮
  const [callBackOrderInfo, setCallBackPayOrderInfo] = useState<any>()

  // 显示记录
  const [applyRecord, setApplyRecord] = useState(false)

  // 显示码单
  const [returnCodeShow, setReturnCodeShow] = useState(false)
  useDidShow(() => {
    if (searchField.status != null) { getOrderList() }
  })

  // 监听筛选条件变化
  useEffect(() => {
    if (searchField.status != null) { getOrderList() }
  }, [searchField])
  // 物流显示
  const [logisticsShow, setLogisticsShow] = useState(false)
  const onShowLogistics = useCallback((val) => {
    setLogisticsShow(true)
  }, [])
  const onCloseLogistics = useCallback(() => {
    setLogisticsShow(false)
  }, [])
  // 物流成功上传
  const logisticsSuccess = useCallback(() => {
    setLogisticsShow(false)
    getOrderList()
  }, [orderData])
  const clickOrderBtn = useCallback(
    ({ status, orderInfo }) => {
      if (status == 1 || status == 6) {
        getOrderList()
      }
      else if (status == 8) {
        setApplyRecord(true)
      }
      else if (status == 5) {
        onShowLogistics(() => true)
      }
      else if (status == 7) {
        setReturnCodeShow(true)
      }
      console.log('orderInfo::', orderInfo)
      setCallBackPayOrderInfo(orderInfo)
    },
    [orderData],
  )
  return (
    <View className={styles.order_list_main}>
      <View className={styles.title}>
        <Search placeIcon="out" placeholder="搜索商品/名称/颜色/订单号" showBtn changeOnSearch={getSearchData} debounceTime={300} />
        <OrderStatusList list={statusList} onSelect={changeStatus} defaultId={1} />
      </View>
      <View className={styles.order_list}>
        <InfiniteScroll
          statusMore={statusMore}
          selfonScrollToLower={getScrolltolower}
          refresherEnabled
          refresherTriggered={refresherTriggeredStatus}
          selfOnRefresherRefresh={getRefresherRefresh}
        >
          {orderData?.list.map((item) => {
            return (
              <View key={item.id} className={styles.order_item_con}>
                <Order value={item} onClickBtn={clickOrderBtn} />
              </View>
            )
          })}
        </InfiniteScroll>
      </View>
      <ApplyRecord show={applyRecord} id={callBackOrderInfo?.id} onClose={() => setApplyRecord(false)} />
      <ReturnLogistics
        images={callBackOrderInfo?.accessory_url}
        descValue={callBackOrderInfo?.take_goods_remark}
        show={logisticsShow}
        id={callBackOrderInfo?.return_apply_order_id}
        onClose={onCloseLogistics}
        onSubmit={logisticsSuccess}
      />
      <ReturnPayCheck orderInfo={callBackOrderInfo} show={returnCodeShow} onClose={() => setReturnCodeShow(false)}></ReturnPayCheck>
    </View>
  )
}

export default SalesAfterList
