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 { AFTER_ORDER_STATUS, ORDER_STATUS, REFUND_STATUS_ORDER, SALE_MODE } from '@/common/enum'
import { alert } from '@/common/common'
import { ReturnApplyOrderCancelApi } from '@/api/salesAfterOrder'
import { throttle } from '@/common/util'

interface Param {
  orderInfo: {
    stage: number // 售后状态
    sale_mode: number // 订单类型
    type: number // 1退货，2退款
    return_apply_order_id: number // 售后申请单
    is_quality_check: true|false // 质检结果
  }
  onClick?: (val: number) => void // 点击后触发的事件，返回订单状态
  fixedBottom?: true|false // 是否固定在底部

}
const AfterOrderBtns = ({ orderInfo, onClick, fixedBottom = true }: Param) => {
  // 售后订单状态
  const {
    ReturnStageApplying,
    ReturnStageWaitCheck,
    ReturnStageReturned,
    ReturnStageQualityCheckPendingRefund,
    ReturnStageServiceOrderPendingRefund,
  } = AFTER_ORDER_STATUS

  const {
    ReturnApplyOrderTypeAdvanceReceiptRefund, // 预收退款
    ReturnApplyOrderTypeReturnForRefund, // 退货退款
    ReturnApplyOrderTypeSalesRefund, // 销售退款
  } = REFUND_STATUS_ORDER

  // 注册按钮
  interface orderBtnsListParams { id: number; label: string; validatarFunc: (val: typeof orderInfo) => any }
  const orderBtnsList = useRef<orderBtnsListParams[]>([
    {
      id: 8,
      label: '申请记录',
      validatarFunc: (orderInfo) => {
        if (orderInfo.sale_mode !== 1) { return [ReturnStageQualityCheckPendingRefund.value, ReturnStageServiceOrderPendingRefund.value, ReturnStageReturned.value].includes(orderInfo.stage) }
        return false
      },
    },
    {
      id: 1,
      label: '取消退货',
      validatarFunc: (orderInfo) => {
        if (orderInfo?.sale_mode != 1 && orderInfo.type == ReturnApplyOrderTypeReturnForRefund.value) { return [ReturnStageApplying.value, ReturnStageWaitCheck.value].includes(orderInfo.stage) }
        return false
      },
    },
    {
      id: 4,
      label: '质检结果',
      validatarFunc: (orderInfo) => {
        return orderInfo?.is_quality_check
      },
    },
    {
      id: 5,
      label: '上传物流',
      validatarFunc: (orderInfo) => {
        return orderInfo?.stage == ReturnStageWaitCheck.value
      },
    },
    {
      id: 6,
      label: '取消退款',
      validatarFunc: (orderInfo) => {
        if (orderInfo?.sale_mode != 1 && orderInfo.type != ReturnApplyOrderTypeReturnForRefund.value) { return [ReturnStageApplying.value, ReturnStageServiceOrderPendingRefund.value]?.includes(orderInfo.stage) }
        if (orderInfo?.sale_mode == 1) { return [ReturnStageApplying.value].includes(orderInfo.stage) }
        return false
      },
    },
  ])

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

  // 取消退货/退款
  const { fetchData: returnApplyOrderCancelFetchData } = ReturnApplyOrderCancelApi()
  const cancelOrder = ({ title = '', val }) => {
    Taro.showModal({
      title,
      async success(res) {
        if (res.confirm) {
          const res = await returnApplyOrderCancelFetchData({ id: orderInfo?.return_apply_order_id })
          if (res.success) {
            alert.success('取消成功')
            onClick?.(val)
          }
          else {
            alert.none(res.msg)
          }
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  // 点击按钮操作
  const submitBtns = throttle((val, index) => {
    if (val == 1) {
      cancelOrder({ title: '要取消退货吗？', val })
    }
    else if (val == 6) {
      cancelOrder({ title: '要取消退款吗？', val })
    }
    else {
      onClick?.(val)
    }
  }, 600)
  // 显示更多按钮
  const [showMore, setShowMore] = useState(false)
  const styleTop = useMemo(() => {
    return { top: `-${(orderBtnsShowList.length - 3) * 70 + 10}rpx`, left: `-${10}rpx` }
  }, [orderBtnsShowList])

  return (
    <>
      {(orderBtnsShowList.length > 0) && <View className={classnames(fixedBottom && styles.submit_order)}>
        <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 >= 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>
      </View>}
    </>
  )
}
export default memo(AfterOrderBtns)
