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

type Param = {
    orderInfo: {
        status: number, //订单状态
        orderId: number, //订单id
        actual_amount: number, //实付金额
        wait_pay_amount: number, //待付金额
    }|null,
    onClick?: (val: number) => void //点击后触发的事件，返回订单状态
}

// export const OrderBtnsemus = [{id:1, label:'取消订单'},{id:2, label:'去付款'},{id:3, label:'申请退款'},{id:4, label:'查看物流'}, {id:5, label:'申请退货'}, {id:6, label:'确认收货'}, {id:7, label:'再次购买'}]
export default memo(({orderInfo, onClick}:Param) => {
    const {
            SaleOrderStatusBooking,
            SaleOrderStatusArranging,
            SaleOrderStatusArranged,
            SaleOrderStatusWaitingDelivery,
            SaleOrderStatusComplete,
            SaleOrderStatusRefund,
            SaleOrderStatusWaitingPayment,
            SaleOrderStatusWaitingReceipt,
            SaleOrderStatusAlreadyReceipt
        } = ORDER_STATUS
    //订单按钮按订单状态归类
    const orderBtnsList = useRef([
        {
            id: 1,
            value: [SaleOrderStatusBooking.value, SaleOrderStatusArranging.value, SaleOrderStatusArranged.value, SaleOrderStatusWaitingPayment.value, SaleOrderStatusWaitingDelivery.value], //取消订单按钮对应： 待接单，配布中，已配布, 待付款， 待发货
            label: '取消订单'
        },
        {
            id: 2,
            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: '再次购买'
        }
    ])
    //判断是否显示该按钮
    const orderBtnsShow = useCallback((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.actual_amount != 0 && item.value.includes(orderInfo.status)) //在待发货之前付过款
            } else {
                //其他按钮
                return item.value.includes(orderInfo.status)
            }
        }
    },[orderInfo])

    //点击按钮操作
    const submitBtns = (val, index) => {
        clickEvent(val, index);
        (val == 1)&&cancelOrder(); //取消订单按钮
        (val == 2)&&onClick?.(2); //去付款按钮
        (val == 6)&&receiveOrder(); //确认收货
        
    }

    //取消订单
    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 () => {
        console.log('123456')
        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 [selectInfo, setSelectInfo] = useState({
        selected: -1, //当前选中的id
        tabId: '', //需要滚动到的id
    })
    const clickEvent = (id, index) => {
        console.log(id, index)
        const num = index > 0?( index - 1) : 0
        console.log('num::',orderBtnsList.current[num].id)
        setSelectInfo((e) => ({...e, tabId:orderBtnsList.current[num].id.toString(), selected: id}))
    }

    return (
        <View className={styles.btns_list}>
            <ScrollView scrollX scrollIntoView={`orderBtns_${selectInfo.tabId}`} scrollWithAnimation={true} className={styles.scroll}>
                <View className={styles.list_scroll}>
                    {orderBtnsList.current.map((item, index) => 
                        orderBtnsShow(item)&&<View key={item.id} className={styles.btns_item} onClick={() => submitBtns(item.id, index)}>{item.label}</View>
                        // <View key={item.id}  className={styles.btns_item} onClick={() => submitBtns(item.id, index)}>{item.label}</View>
                    )}
                </View>
            </ScrollView>
            
        </View>
    )
})