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

export default () => {
  const {checkLogin} = useLogin()
  useDidShow(async () => {
    await checkLogin()
  })

  //搜索参数
  const [searchField, setSearchField] = useState({
    status: -1,
    page : 1,
    size : 10,
    Name:''
  })

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

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


  //监听筛选条件变化
  useEffect(() => {
      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 [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  const getRefresherRefresh = async () => {
    pageNum.current.size = 1
    setRefresherTriggeredStatus(true)
    setSearchField((val) => ({...val, size:10}))
  }

  //监听点击的按钮
  const clickOrderBtn = useCallback(({status, orderInfo}) => {
    setCallBackPayOrderInfo(() => orderInfo)
    if(status == 1 || status == 6) {
      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)
    }
  }, [orderData])


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

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

  //添加购物车
  const [showCart, setShowCart] = useState(false)
  const {fetchData:addFetchData} = AddShoppingCartApi()
  const addShopCart =  async (item) => {
      let color_list:{product_color_id: number, roll?: number, length?: number}[] = []
      item?.product_list.map(pitem => {
          pitem?.product_colors.map(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)
  }, [])

  
  return (
    <View className={styles.order_list_main}>
      <View className={styles.title}>
        <Search placeIcon="out" placeholder="搜索商品/名称/颜色/订单号" showBtn={true}  changeOnSearch={getSearchData} debounceTime={300}/>
        <OrderStatusList list={statusList} onSelect={changeStatus} defaultId={1}/>
      </View>
      <View className={styles.order_list}>
          <InfiniteScroll statusMore={statusMore} selfonScrollToLower={getScrolltolower} refresherEnabled={false} 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} orderId={callBackOrderInfo?.id}/>
      <ShopCart show={showCart}  onClose={() => setShowCart(false)}/>
      <Payment onSubmitSuccess={onPaySuccess} show={payMentShow} onClose={closePayShow} orderInfo={callBackOrderInfo}/>
    </View>
  )
}
