import { CancelOrderApi, ReceiveOrderApi } from "@/api/order"
import { alert } from "@/common/common"
import { AFTER_ORDER_STATUS, ORDER_STATUS, SALE_MODE } 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 { ReturnApplyOrderCancelApi } from "@/api/salesAfterOrder"

type Param = {
    orderInfo: {
        stage: number, //售后状态
        orderId: number, //订单id
        sale_mode: number //订单类型
        type: number //1退货，2退款
    },
    onClick?: (val: number) => void, //点击后触发的事件，返回订单状态
    onBtnNull?: () => void //所有按钮都为空
}

export default memo(({orderInfo, onClick, onBtnNull}:Param) => {
    //售后订单状态
    const {
        ReturnStageApplying,                  
        ReturnStageWaitCheck,
        ReturnStageReturned,
        ReturnStageQualityCheckPendingRefund,
        ReturnStageServiceOrderPendingRefund,
    } = AFTER_ORDER_STATUS

    //订单类型
    // const {
    //     SaLeModeBulk,
    //     SaleModeLengthCut,
    //     SaLeModeWeightCut,
    // } = SALE_MODE
    
    //售后按钮按售后状态归类, value是该订单状态，可能该按钮会出现
    const orderBtnsList = useRef([
        {
            id: 1,
            value: [ReturnStageApplying.value, ReturnStageWaitCheck.value], 
            label: '取消退货'
        },
        {
            id: 2,
            value: [ReturnStageWaitCheck.value], 
            label: '退货物流'
        },
        // {
        //     id: 3,
        //     value: [ReturnStageChecked.value, ReturnStageQualityCheckPendingRefund.value], 
        //     label: '查看物流'
        // },
        {
            id: 4,
            value: [ReturnStageQualityCheckPendingRefund.value, ReturnStageServiceOrderPendingRefund.value, ReturnStageReturned.value], 
            label: '质检结果'
        },
        {
            id: 5,
            value: [ReturnStageServiceOrderPendingRefund.value, ReturnStageReturned.value], 
            label: '退货码单'
        },
        {
            id: 6,
            value: [ReturnStageApplying.value, ReturnStageServiceOrderPendingRefund.value], 
            label: '取消退款'
        },
        {
            id: 7,
            value: [ReturnStageServiceOrderPendingRefund.value, ReturnStageReturned.value], 
            label: '退款码单'
        },
        {
            id: 8,
            value: [], 
            label: '申请记录'
        },
    ])
    
    
    //判断是否显示该按钮
    const orderBtnsShow = (item) => {
        if(!orderInfo) return false
        if(item.id == 1) {
            //取消退货
            return (orderInfo.type == 1)&&item.value.includes(orderInfo.stage)
        } else if (item.id == 6) {
            //取消退款
            return (orderInfo.type == 2)&&item.value.includes(orderInfo.stage)
        } else {
            if(item.value.includes(orderInfo.stage)) {
                return true
            } else {
                onBtnNull?.()
            }
        }
        
        
    }

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



    //点击按钮操作
    const submitBtns = (val, index) => {
        if (val == 1) {
            cancelOrder()
        } else if (val == 6) {
            receiveOrder()
        } else {
            onClick?.(val)
        }
    }

    //取消退货
    const {fetchData: returnApplyOrderCancelFetchData} = ReturnApplyOrderCancelApi()
    const cancelOrder = () => { 
        Taro.showModal({
            title: '要取消退货吗？',
            success: async function (res) {
              if (res.confirm) {
                let res = await returnApplyOrderCancelFetchData({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 [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>
    )
})