<template>
  <view class="order-info-container">
    <Header
        system-bar-area-bg="#fff"
        header-area-bg="#fff"
        :scroll-top="scrollTop">
      订单详情
    </Header>
    <image
        :src="orderDetailsBg"
        class="bg-image"
        mode="widthFix"
    />
    <view
        class="main-inner"
        v-if="orderInfoData">
      <!-- 订单状态信息 -->
      <OrderState
          :order-info-data="orderInfoData"
          :remain-time-str="remainTimeStr" />
      <!-- 地址 -->
      <OrderAddress :order-info-data="orderInfoData" />
      <!-- group info 是拼团且已支付 -->
      <OrderGroupInfo
          v-if="orderInfoData.campaignType && orderInfoData.campaignType===1 && orderInfoData._status._type!=='0' && orderInfoData.teamworkId"
          :order-info-data="orderInfoData" />
      <!-- goods list -->
      <OrderGoodsInfo :order-info-data="orderInfoData" />
      <!-- order info -->
      <OrderOrderInfo :order-info-data="orderInfoData" />
      <!-- logistics info -->
      <OrderLogisticsInfo
          v-if="expressData"
          :order-info-data="orderInfoData"
          :express-data="expressData" />
      <view class="bottom-bar-bg"></view>
      <!-- options -->
      <view class="order-actions bottom-bar">
        <OrderOptions
            style="width: 100%"
            :status="orderInfoData._status._type"
            :shop-type="orderInfoData.shippingType"
            @cancel="showModal(MODAL_TYPE.CANCEL)"
            @confirm="showModal(MODAL_TYPE.CONFIRM)"
            @delete="showModal(MODAL_TYPE.DELETE)"
            @pay="handlePay"
            @refund="toSelectRefundGood(orderInfoData.id)"
            @check-off-code="checkOffCode(orderInfoData.writeOffCode)"
            @invite="goGroupByDetail({teamworkId:orderInfoData.teamworkId})"
            @cancel-refund="showModal(MODAL_TYPE.CANCEL_CHECK)"
        />
      </view>

    </view>
  </view>
  <!-- 支付弹窗 -->
  <PayPopup
      ref="payPopupRef"
      @confrim="paySuccess"
  />

  <Modal
      ref="modalRef"
      :content="modalTitle"
      @confirm="confirmModal" />

  <!-- 核销 -->
  <CheckOffCode ref="checkOffCodeRef" />

</template>

<script setup>
import Header from "@/components/Header/index.vue"
import { orderDetailsBg } from "@/utils/images";
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { cancelAfterVerification, orderExpress, orderInfo, orderTake } from '@/api/order'
import { orderReStatus } from '@/config'
import { useRouter } from "@/hooks/useRouter";
import PayPopup from "@/components/PayPopup/index.vue";
import Modal from "@/components/Modal/index.vue";
import { useInterface } from "@/hooks/useInterface";
import { formatRemainTime } from "@/utils/utils";
import { useOrder } from "@/hooks/useOrder";
import { usePay } from "@/hooks/usePay";
import OrderOptions from "@/pages/orderInfo/component/OrderOptions.vue";
import CheckOffCode from "@/components/order/CheckOffCode.vue";
import OrderState from "@/pages/orderInfo/component/OrderState.vue";
import OrderAddress from "@/pages/orderInfo/component/OrderAddress.vue";
import { useScroll } from "@/hooks/useScroll";
import OrderGroupInfo from "@/pages/orderInfo/component/OrderGroupInfo.vue";
import OrderGoodsInfo from "@/pages/orderInfo/component/OrderGoodsInfo.vue";
import OrderOrderInfo from "@/pages/orderInfo/component/OrderOrderInfo.vue";
import OrderLogisticsInfo from "@/pages/orderInfo/component/OrderLogisticsInfo.vue";
import { useJump } from "@/hooks/useJump";

const {goGroupByDetail} = useJump()


const {scrollTop} = useScroll();


const {payPopupRef, openPay, paySuccess} = usePay()

const {getParams, getUrlParams, push, goBack} = useRouter()
const {toast} = useInterface();

const orderInfoData = ref(null)
const orderInfoStatusMsg = ref('')
const expressData = ref(null)
const remainTimeStr = ref('')


const handleOrderInfo = async (option) => {
  const res = await orderInfo(option)
  orderInfoData.value = res
  res.status = res.paid === 1 && res.status === 0 ? 99 : res.status
  handleMsg(res.status)
  if (parseInt(res._status._type) > 1) {
    if (parseInt(res._status._type) === 2) {
      remainTimeStr.value = formatRemainTime(res._status._payRemainTime)
    }
    // _type: 2待收货 3已收货 4已完成 8代发货 6待成团 7已成团
    if ([2, 3, 4].includes(parseInt(res._status._type))) {
      if (res.shippingType === 2) return // 核销订单不需要物流
      await orderExpress({
        orderCode: orderInfoData.value.orderId,
        shipperCode: orderInfoData.value.deliverySn,
        logisticCode: orderInfoData.value.deliveryId,
      }).then(res => {
        expressData.value = res.traces.reverse()
      }).catch(err => {
        console.log(err, 'err')
      })
    }
  }
}

const {
  MODAL_TYPE,
  modalRef,
  checkOffCodeRef,
  modalType,
  modalTitle,
  showModal,
  cancelOrder,
  deleteOrder,
  toEvaluate,
  toSelectRefundGood,
  showWsReceipt,
  checkOffCode,
} = useOrder(handleOrderInfo)


const handlePay = () => {
  openPay(orderInfoData.value.orderId)
}

// 返回列表
const goList = () => {
  let status = 0
  switch (orderInfoData.value.status) {
    case -1:
      status = -1
      break
    case 0:
      status = 0
      break
    case 4:
      status = -1
      break
    case 99:
      status = 1
      break
    default:
      status = orderInfoData.value.status + 1
  }
  push({url: '/pages/orderList/orderList'}, {
    data: {
      type: status
    }
  })
}

/**
 * 确认弹窗
 */
function confirmModal() {
  const funcArr = [doDeleteOrder, doCancelOrder, doTakeGoods, doCancelAnOrder]
  funcArr[modalType.value]()
}

const handleMsg = (status) => {
  orderInfoStatusMsg.value = orderReStatus[status]
}

async function doDeleteOrder() {
  deleteOrder(orderInfoData.value).then(() => {
    setTimeout(() => {
      goList()
    }, 2000)
  })
}

async function doCancelOrder() {
  cancelOrder(orderInfoData.value).then(() => {
    setTimeout(() => {
      goList()
    }, 2000)
  })
}

async function doTakeGoods() {
  let option = {
    uni: orderInfoData.value.orderId,
  }
  let payInfo = JSON.parse(orderInfoData.value.payInfo)
  showWsReceipt(payInfo.transaction_id).then(async (res) => {
    if (res === 'success') {
      await orderTake(option)
      toast({title: '收货成功'});
      await handleOrderInfo({
        key: option.uni
      })
    }
  })
}


const doCancelAnOrder = async () => {
  await cancelAfterVerification({id: orderInfoData.value.orderId})
  toast({title: '取消成功'})
  goBack()
}

onShow(() => {
  const params = getUrlParams()
  handleOrderInfo({
    key: params.orderId
  })
})

</script>

<style lang="scss">
@import "../../style/images";

.order-info-container {
  width: 100%;
  position: relative;

  .bg-image {
    position: absolute;
    left: 0;
    width: 100%;
    height: 300rpx;
    z-index: 0;
  }

  .main-inner {
    position: relative;
    z-index: 1;
    @include usePadding(30, 30);
  }
}

.orderList {
  padding: 20rpx 0;
}


.order-infos {
  margin: 0 40rpx;
  padding: 40rpx 0 20rpx;

  &:after {
    content: '';
  }
}

.no-express {
  font-size: 26rpx;
  padding: 20rpx 14rpx 30rpx;
}
.order-actions{
  bottom: env(safe-area-inset-bottom);
}

</style>
