import { Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { memo, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import { ORDER_STATUS, SALE_MODE, SUBSCRIPTION_MESSAGE_SCENE } from '@/common/enum'
import { alert, goLink } from '@/common/common'
import { CancelOrderApi, ReceiveOrderApi } from '@/api/order'
import { AddShoppingCartApi } from '@/api/shopCart'
import { ApplyRefundApi } from '@/api/salesAfterOrder'
import { UseSubscriptionMessage } from '@/use/useCommon'
import { throttle } from '@/common/util'

interface Param {
  orderInfo: {
    status: number // 订单状态
    orderId: number // 订单id
    actual_amount: number // 实付金额
    wait_pay_amount: number // 待付金额
    sale_mode: number // 订单类型
    av_return_roll?: number // 可退数量
    is_return?: true | false // 是否申请了售后
    is_should_collect_audit?: true | false // 应收单是否审核
  }
  showStatus?: 'detail' | 'list' // 订单详情，订单列表
  onClick?: (val: number) => void // 点击后触发的事件，返回订单状态
}
const OrderBtns = ({ orderInfo, showStatus = 'detail', onClick }: Param) => {
  // 订单状态枚举
  const {
    SaleOrderStatusBooking,
    SaleOrderStatusArranging,
    SaleOrderStatusArranged,
    SaleOrderStatusWaitingDelivery,
    SaleOrderStatusComplete,
    SaleOrderStatusRefund,
    SaleOrderStatusWaitingPayment,
    SaleOrderStatusWaitingReceipt,
    SaleOrderStatusAlreadyReceipt,
    SaleorderstatusWaitingPrePayment,
    SaleOrderStatusTaking,
  } = ORDER_STATUS

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

  // 注册按钮, id:按钮id唯一，label：按钮名称，sort：排序数字越大越靠后，validatarFunc：验证
  interface orderBtnsListParams { id: number; label: string; sort: number; validatarFunc: (val: typeof orderInfo) => any }
  const orderBtnsList = useRef<orderBtnsListParams[]>([
    {
      id: 1,
      label: '取消订单',
      sort: 1,
      validatarFunc: (orderInfo) => {
        // 在待发货之前没有付过款
        const orderStatus = [
          SaleorderstatusWaitingPrePayment.value,
          SaleOrderStatusBooking.value,
          SaleOrderStatusArranging.value,
          SaleOrderStatusArranged.value,
          SaleOrderStatusWaitingPayment.value,
          SaleOrderStatusTaking.value,
          SaleOrderStatusWaitingDelivery.value,
        ]
        return orderInfo.actual_amount == 0 && orderStatus.includes(orderInfo.status)
      },
    },
    {
      id: 2,
      label: '去付款',
      sort: 100,
      validatarFunc: (orderInfo) => {
        // 只要没有付完款就显示
        const orderStatus = [
          SaleOrderStatusTaking.value,
          SaleorderstatusWaitingPrePayment.value,
          SaleOrderStatusWaitingPayment.value,
          SaleOrderStatusWaitingDelivery.value,
          SaleOrderStatusWaitingReceipt.value,
          SaleOrderStatusAlreadyReceipt.value,
          SaleOrderStatusComplete.value,
        ]
        return orderInfo.wait_pay_amount > 0 && orderStatus.includes(orderInfo.status)
      },
    },
    {
      id: 3,
      label: '申请退款',
      sort: 5,
      validatarFunc: (orderInfo) => {
        // 大货在待发货付过款
        const orderStatus = [SaleOrderStatusWaitingDelivery.value, SaleOrderStatusTaking.value]
        return orderInfo.sale_mode == SaLeModeBulk.value && orderInfo.actual_amount > 0 && orderInfo.av_return_roll && orderStatus.includes(orderInfo.status)
      },
    },
    {
      id: 5,
      label: '申请退货',
      sort: 5,
      validatarFunc: (orderInfo) => {
        const orderStatus = [SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusRefund.value]
        return orderInfo.av_return_roll && orderStatus.includes(orderInfo.status)
      },
    },
    {
      id: 6,
      label: '确认收货',
      sort: 10,
      validatarFunc: (orderInfo) => {
        const orderStatus = [SaleOrderStatusWaitingReceipt.value]
        return orderStatus.includes(orderInfo.status)
      },
    },
    {
      id: 7,
      label: '再次购买',
      sort: 6,
      validatarFunc: () => {
        return true
      },
    },
    {
      id: 8,
      label: '退款',
      sort: 5,
      validatarFunc: (orderInfo) => {
        // 散剪和剪板在待接单时付过款
        const orderStatus = [SaleOrderStatusBooking.value]
        return orderInfo.sale_mode != SaLeModeBulk.value && orderInfo.actual_amount > 0 && orderStatus.includes(orderInfo.status)
      },
    },
    {
      id: 9,
      label: '售后记录',
      sort: 6,
      validatarFunc: (orderInfo) => {
        return orderInfo.is_return
      },
    },
    {
      id: 10,
      label: '销售码单',
      sort: 9,
      validatarFunc: (orderInfo) => {
        if (orderInfo.sale_mode === 1 && showStatus == 'detail') { return true }
        if (orderInfo.sale_mode !== 1 && showStatus == 'detail') { return orderInfo.is_should_collect_audit }
      },
    },
  ])

  // 显示的按钮数组
  const orderBtnsShowList: orderBtnsListParams[] = useMemo(() => {
    const list = orderBtnsList.current.filter((item) => {
      return item.validatarFunc(orderInfo)
    })
    return list.sort((a, b) => a.sort - b.sort)
  }, [orderInfo])

  // 小程序订阅
  const { ApplyGoods } = SUBSCRIPTION_MESSAGE_SCENE
  const { openSubscriptionMessage } = UseSubscriptionMessage()

  // 大货申请退款
  const bigApplyRefurn = () => {
    Taro.showModal({
      title: '要申请退款吗？',
      async success(res) {
        if (res.confirm) {
          await openSubscriptionMessage({ orderId: orderInfo?.orderId, scenes: ApplyGoods.value })
          onClick?.(3)
        }
        else {
          console.log('用户点击取消')
        }
      },
    })
  }

  // 取消订单
  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() => {
    Taro.showModal({
      title: '确定收货？',
      async success(res) {
        if (res.confirm) {
          alert.showLoading('收货中', true)
          const res = await receiveOrderFetchData({ sale_order_id: orderInfo?.orderId })
          if (res.success) {
            onClick?.(6)
            alert.success('收货成功')
          }
          else {
            alert.error('收货失败')
          }
          alert.hideLoading()
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }

  // 退款
  const { fetchData: fetchDataApplyRefund } = ApplyRefundApi()
  const applyRefund = async() => {
    Taro.showModal({
      title: '确定退款？',
      success: async function async(res) {
        if (res.confirm) {
          await openSubscriptionMessage({ orderId: orderInfo?.orderId, scenes: ApplyGoods.value })
          alert.showLoading('申请中', true)
          const res = await fetchDataApplyRefund({ sale_order_id: orderInfo?.orderId })
          if (res.success) {
            alert.success('申请成功')
          }
          else {
            alert.error('申请失败')
          }
          alert.hideLoading()
          onClick?.(8)
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }

  // 申请退货
  const applyProduct = async() => {
    if (!orderInfo?.av_return_roll) { return alert.none('该订单没有可退条数') }
    await openSubscriptionMessage({ orderId: orderInfo?.orderId, scenes: ApplyGoods.value })
    goLink('/pages/applyAfterSales/index', { id: orderInfo?.orderId })
  }

  // 显示更多按钮
  const [showMore, setShowMore] = useState(false)
  const styleTop = useMemo(() => {
    return { top: `-${(orderBtnsShowList.length - 3) * 70 + 10}rpx`, left: `-${10}rpx` }
  }, [orderBtnsShowList])

  // 点击按钮操作
  const submitBtns = throttle(async(val, index) => {
    if (val == 1) {
      cancelOrder()
    }
    else if (val == 6) {
      receiveOrder()
    }
    else if (val == 5) {
      applyProduct()
    }
    else if (val == 3) {
      bigApplyRefurn()
    }
    else if (val == 8) {
      applyRefund()
    }
    else {
      onClick?.(val)
    }
  }, 800)

  return (
    <View className={styles.btns_list}>
      {orderBtnsShowList.length > 3 && (
        <View className={styles.more}>
          <Text onClick={() => setShowMore(!showMore)}>{!showMore ? '更多' : '关闭'}</Text>
          {showMore && (
            <View className={styles.more_con}>
              <View className={styles.more_list} style={styleTop}>
                {orderBtnsShowList.map((item, index) => {
                  return (
                    index < orderBtnsShowList.length - 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) =>
            orderBtnsShowList.length - 3 <= index && (
              <View key={item.id} className={classnames(styles.btns_item)} onClick={() => submitBtns(item.id, index)}>
                {item.label}
              </View>
            ),
        )}
      </View>
    </View>
  )
}
export default memo(OrderBtns)
