import { View } from '@tarojs/components'
import Taro, { useDidHide, useDidShow, useRouter, useUnload } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import Payment from '../components/payment'
import ApplyRefund from '../components/applyRefund'
import ReturnRecord from '../components/returnRecord'
import styles from './index.module.scss'
import Order from './components/order'
import OrderStatusList from './components/orderStatusList'
import Search from '@/components/search'
import useLogin from '@/use/useLogin'
import InfiniteScroll from '@/components/infiniteScroll'
import { GetOrderListApi, OrderStatusListApi } from '@/api/order'
import { dataLoadingStatus, getFilterData } from '@/common/util'
import { AddShoppingCartApi } from '@/api/shopCart'
import ShopCart from '@/components/shopCart'
import { alert } from '@/common/common'

const OrderList = () => {
  const { checkLogin } = useLogin()

  // 传递过来的参数
  const router = useRouter()

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

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

  // 列表下拉刷新
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  // 获取订单列表
  const { fetchData: listFetchData, state: orderState } = GetOrderListApi()
  const [orderData, setOrderData] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })
  const getOrderList = async() => {
    const res = await listFetchData(getFilterData(searchField))
    setOrderData(e => ({ ...e, list: res.data?.list, total: res.data?.total }))
    setRefresherTriggeredStatus(() => false)
  }

  useDidShow(() => {
    checkLogin()
    searchField.status && getOrderList()
  })

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

  // 上拉加载数据
  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({ ...searchField, 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 getRefresherRefresh = async() => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearchField(val => ({ ...val, size: 10 }))
  }

  const [callBackOrderInfo, setCallBackPayOrderInfo] = useState<any>()

  // 去付款
  const [payMentShow, setPayMentShow] = useState(false)
  const toPay = () => {
    setPayMentShow(true)
  }
  // 关闭支付弹窗
  const closePayShow = useCallback(() => {
    setPayMentShow(() => false)
  }, [])
  // 支付成功
  const onPaySuccess = () => {
    getOrderList()
    closePayShow()
  }

  // 添加购物车
  const [showCart, setShowCart] = useState(false)
  const { fetchData: addFetchData } = AddShoppingCartApi()
  const addShopCart = async(item) => {
    const color_list: { product_color_id: number; roll?: number; length?: number }[] = []
    item?.product_list.forEach((pitem) => {
      pitem?.product_colors.forEach((citem) => {
        if (item?.sale_mode == 0) {
          return color_list.push({ product_color_id: citem.id, roll: citem.roll })
        }
        else {
          return color_list.push({ product_color_id: citem.id, length: citem.length })
        }
      })
    })
    const state = await addFetchData({
      sale_mode: item?.sale_mode,
      color_list,
    })
    if (state.success) {
      Taro.showToast({
        title: '已加入购物车',
      })
      setShowCart(true)
    }
    else {
      Taro.showToast({
        icon: 'none',
        title: state.msg,
      })
    }
  }

  // 申请退款
  const [refundShow, setRefundShow] = useState(false)
  const applyRefundClose = useCallback(() => {
    setRefundShow(false)
  }, [])
  const applyRefundSuccess = useCallback(() => {
    getOrderList()
  }, [])

  // 显示售后记录
  const [returnRecordShow, setReturnRecordShow] = useState(false)
  const onReturnRecordShow = useCallback(() => {
    setReturnRecordShow(true)
  }, [])
  const closeReturnRecord = useCallback(() => {
    setReturnRecordShow(false)
  }, [])

  // 显示
  const [showScanPayCheck, setShowScanPayCheck] = useState(false)
  useEffect(() => {
    if (router?.params.status != undefined && router?.params.status !== '') {
      setSearchField(e => ({ ...e, status: router?.params.status as unknown as number }))
    }
    else {
      setSearchField(e => ({ ...e, status: -1 }))
    }
    getOrderStatusList()
  }, [])
  // 监听点击的按钮
  const clickOrderBtn = useCallback(
    ({ status, orderInfo }) => {
      setCallBackPayOrderInfo(() => orderInfo)
      if (status == 1 || status == 6 || status == 8) {
        getOrderList()
      }
      else if (status == 2) {
        // 去支付
        toPay()
      }
      else if (status == 3) {
        // 申请退款
        if (!orderInfo?.av_return_roll) { return alert.none('该订单已申请过退款') }
        setRefundShow(true)
      }
      else if (status == 7) {
        // 购买
        addShopCart(orderInfo)
      }
      else if (status == 9) {
        onReturnRecordShow()
      }
      else if (status == 10) {
        setShowScanPayCheck(true)
      }
    },
    [orderData],
  )
  // useDidHide(() => {
  //   setSearchField(e => ({ ...e, status: -1 }))
  // })
  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={searchField.status as unknown as number} />
      </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>
      <ApplyRefund show={refundShow} onClose={applyRefundClose} onSuccess={applyRefundSuccess} orderId={callBackOrderInfo?.id} />
      <ShopCart intoStatus="again" show={showCart} onClose={() => setShowCart(false)} default_sale_mode={callBackOrderInfo?.sale_mode} />
      <ReturnRecord show={returnRecordShow} onClose={closeReturnRecord} id={callBackOrderInfo?.id} />
      <Payment onSubmitSuccess={onPaySuccess} show={payMentShow} onClose={closePayShow} orderInfo={callBackOrderInfo} />
    </View>
  )
}

export default OrderList
