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

type Param = {
    orderInfo: {
        status: number, //订单状态
        orderId: number, //订单id
        actual_amount: number, //实付金额
        wait_pay_amount: number, //待付金额
        sale_mode: number, //订单类型
        av_return_roll?: number, //可退数量

    }|null,
    onClick?: (val: number) => void //点击后触发的事件，返回订单状态
}

export default memo(({orderInfo, onClick}:Param) => {
    //订单状态枚举
    const {
        SaleOrderStatusBooking,
        SaleOrderStatusArranging,
        SaleOrderStatusArranged,
        SaleOrderStatusWaitingDelivery,
        SaleOrderStatusComplete,
        SaleOrderStatusRefund,
        SaleOrderStatusWaitingPayment,
        SaleOrderStatusWaitingReceipt,
        SaleOrderStatusAlreadyReceipt,
        SaleorderstatusWaitingPrePayment,
        SaleOrderStatusTaking
    } = 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: 3,
            value: [SaleOrderStatusWaitingDelivery.value, SaleOrderStatusTaking.value], //申请退款按钮对应： 待发货, 提货中
            label: '申请退款'
        },
        // {
        //     id: 4,
        //     value: [SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusComplete.value, SaleOrderStatusRefund.value], //取消订单按钮对应： 待收货, 已收货, 已完成, 已退款
        //     label: '查看物流'
        // },
        {
            id: 5,
            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: '退款'
        },
        {
            id: 2,
            value: [SaleOrderStatusTaking.value, SaleorderstatusWaitingPrePayment.value, SaleOrderStatusWaitingPayment.value, SaleOrderStatusWaitingDelivery.value, SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusComplete.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 if (item.id == 7) {
                return true //再次购买按钮一直存在
            } 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 {ApplyGoods} = SUBSCRIPTION_MESSAGE_SCENE
    const {openSubscriptionMessage} = UseSubscriptionMessage()

    //点击按钮操作
    const submitBtns = throttle(async (val, index) => {
        if (val == 1) {
            cancelOrder()
        } else if (val == 6) {
            receiveOrder()
        } else if(val == 5) {
            if(!orderInfo?.av_return_roll) return alert.none('该订单没有可退条数')
            await openSubscriptionMessage({orderId:  orderInfo?.orderId, scenes: ApplyGoods.value})
            goLink('/pages/applyAfterSales/index',{id:orderInfo?.orderId})
        } else if (val == 3) {
            bigApplyRefurn()
        } else if(val == 8) { 
            applyRefund()
        } else {
            onClick?.(val)
        }
    }, 600)

    //大货申请退款
    const bigApplyRefurn = () => {
        Taro.showModal({
            title: '要申请退款吗？',
            success: async function (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: '要取消该订单吗？',
            success: async function (res) {
              if (res.confirm) {
                let 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: '确定收货？',
            success: async function (res) {
              if (res.confirm) {
                let 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 {fetchData: fetchDataApplyRefund} = ApplyRefundApi()
    const applyRefund = async () => {
        // if(!orderInfo?.av_return_roll) return alert.none('该订单没有可退条数')
        Taro.showModal({
            title: '确定退款？',
            success: async function async (res) {
                if(res.confirm) {
                    await openSubscriptionMessage({orderId:  orderInfo?.orderId, scenes: ApplyGoods.value})
                    let res = await fetchDataApplyRefund({sale_order_id: orderInfo?.orderId})
                    if(res.success) {
                        alert.success('申请成功')
                    } else {
                        alert.error('申请失败')
                    }
                    onClick?.(8)
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
        
    }


    //显示更多按钮
    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={classnames(styles.btns_item)} onClick={() => submitBtns(item.id, index)}>{item.label}</View>
                )}
            </View>
            
        </View>
    )
})