import { ScrollView, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { ORDER_STATUS, SALE_MODE } from '@/common/enum'
import { alert } from '@/common/common'
import { CancelOrderApi, ReceiveOrderApi } from '@/api/order'

interface Param {
  orderInfo: {
    status: number // 订单状态
    orderId: number // 订单id
    actual_amount: number // 实付金额
    wait_pay_amount: number // 待付金额
    sale_mode: number // 订单类型
  }|null
  onClick?: (val: number) => void // 点击后触发的事件，返回订单状态
}
const OrderBtns = ({ orderInfo, onClick }: Param) => {
  // 订单状态枚举
  const {
    SaleOrderStatusBooking,
    SaleOrderStatusArranging,
    SaleOrderStatusArranged,
    SaleOrderStatusWaitingDelivery,
    SaleOrderStatusComplete,
    SaleOrderStatusRefund,
    SaleOrderStatusWaitingPayment,
    SaleOrderStatusWaitingReceipt,
    SaleOrderStatusAlreadyReceipt,
    SaleorderstatusWaitingPrePayment,
  } = ORDER_STATUS

  // 订单类型
  const {
    SaLeModeBulk,
    SaleModeLengthCut,
    SaLeModeWeightCut,
  } = SALE_MODE

  // 订单按钮按订单状态归类, value是该订单状态，可能该按钮会出现
  const orderBtnsList = useRef([
    {
      id: 1,
      value: [SaleOrderStatusBooking.value,
        SaleOrderStatusArranging.value,
        SaleOrderStatusArranged.value,
        SaleOrderStatusWaitingPayment.value,
        SaleOrderStatusWaitingDelivery.value], // 取消订单按钮对应： 待接单，配布中，已配布, 待付款， 待发货
      label: '取消订单',
    },
    {
      id: 2,
      value: [SaleorderstatusWaitingPrePayment.value, SaleOrderStatusWaitingPayment.value, SaleOrderStatusWaitingDelivery.value, SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusComplete.value], // 去付款按钮对应：待付款， 待发货, 待收货, 已收货, 已完成
      label: '去付款',
    },
    {
      id: 3,
      value: [SaleOrderStatusWaitingDelivery.value], // 申请退款按钮对应： 待发货
      label: '申请退款',
    },
    {
      id: 4,
      value: [SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusComplete.value, SaleOrderStatusRefund.value], // 取消订单按钮对应： 待收货, 已收货, 已完成, 已退款
      label: '查看物流',
    },
    {
      id: 5,
      value: [SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusRefund.value], // 申请退货按钮对应： 待收货, 已收货, 已退款
      label: '申请退货',
    },
    {
      id: 6,
      value: [SaleOrderStatusWaitingReceipt.value], // 确认收货按钮对应： 待收货
      label: '确认收货',
    },
    {
      id: 7,
      value: [SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusComplete.value, SaleOrderStatusRefund.value], // 再次购买按钮对应： 待收货，已收货，已完成, 已退款
      label: '再次购买',
    },
    {
      id: 8,
      value: [SaleOrderStatusBooking.value], // 按钮对应： 待接单
      label: '退款',
    },
  ])

  // 判断是否显示该按钮
  const orderBtnsShow = (item) => {
    if (orderInfo) {
      if (item.id == 1) {
        // 取消订单按钮
        return (orderInfo.actual_amount == 0 && item.value.includes(orderInfo.status)) // 在待发货之前没有付过款
      }
      else if (item.id == 2) {
        // 去付款按钮
        return (orderInfo.wait_pay_amount != 0 && item.value.includes(orderInfo.status)) // 只要没有付完款就显示
      }
      else if (item.id == 3) {
        // 申请退款, 只有大货才有
        return (orderInfo.sale_mode == SaLeModeBulk.value && orderInfo.actual_amount != 0 && item.value.includes(orderInfo.status)) // 大货在待发货付过款
      }
      else if (item.id == 8) {
        // 退款按钮（直接退款不用申请）, 只有散剪和剪板有
        return (orderInfo.sale_mode != SaLeModeBulk.value && orderInfo.actual_amount != 0 && item.value.includes(orderInfo.status)) // 散剪和剪板在待接单时付过款
      }
      else {
        // 其他按钮
        return item.value.includes(orderInfo.status)
      }
    }
  }

  // 显示的按钮数组
  const orderBtnsShowList: { id: number; value: any; label: string }[] = useMemo(() => {
    return orderBtnsList.current.filter((item) => {
      return orderBtnsShow(item)
    })
  }, [orderInfo])

  // 取消订单
  const { fetchData: cancelFetchData } = CancelOrderApi()
  const cancelOrder = () => {
    Taro.showModal({
      title: '要取消该订单吗？',
      async success(res) {
        if (res.confirm) {
          const res = await cancelFetchData({ id: orderInfo?.orderId })
          if (res.success) {
            alert.success('取消成功')
            onClick?.(1)
          }
          else {
            alert.none(res.msg)
          }
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }

  // 确认订单
  const { fetchData: receiveOrderFetchData } = ReceiveOrderApi()
  const receiveOrder = async() => {
    console.log('123456')
    Taro.showModal({
      title: '确定收货？',
      async success(res) {
        if (res.confirm) {
          const res = await receiveOrderFetchData({ sale_order_id: orderInfo?.orderId })
          if (res.success) {
            onClick?.(6)
            alert.success('收货成功')
          }
          else {
            alert.error('收货失败')
          }
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  // 点击按钮操作
  const submitBtns = (val, index) => {
    (val == 1) && cancelOrder(); // 取消订单按钮
    (val == 2) && onClick?.(2); // 去付款按钮
    (val == 6) && receiveOrder() // 确认收货
  }
  // 显示更多按钮
  const [showMore, setShowMore] = useState(false)
  const styleTop = useMemo(() => {
    return { top: `-${(orderBtnsShowList.length - 3) * 70 + 10}rpx`, left: `-${10}rpx` }
  }, [orderBtnsShowList])

  return (
    <View className={styles.btns_list}>
      {(orderBtnsShowList.length > 3) && <View className={styles.more}>
        <Text onClick={() => setShowMore(true)}>更多</Text>
        {showMore && <View className={styles.more_con}>
          <View className={styles.more_list} style={styleTop}>
            {orderBtnsShowList.map((item, index) => {
              return ((index >= 3) && <View className={styles.more_item} key={item.id} onClick={() => submitBtns(item.id, index)}>{item.label}</View>)
            })}
          </View>
          <View className={styles.more_bg} catchMove onClick={() => setShowMore(false)}></View>
        </View>}
      </View>}

      <View className={styles.list_scroll}>
        {orderBtnsShowList.map((item, index) =>
          (index < 3) && <View key={item.id} className={styles.btns_item} onClick={() => submitBtns(item.id, index)}>{item.label}</View>,
        )}
      </View>

    </View>
  )
}
export default memo(OrderBtns)
