<template>
  <layout class="orderInfo">
    <uv-navbar
        :fixed="false"
        title="订单详情"
        left-arrow
        @leftClick="goList"
    />
    <view v-if="orderInfoData">
      <view class="orderInfo-header background-warp">
        <view class="background">
          <image
              class="image"
              :src="orderDetailsBg"
              mode="widthFix"
          />
        </view>
        <view class="background-content page-space">
          <view class="order-status-info">
            <view
                class="order-status"
                :class="'order-status-'+ orderInfoData.status"
            >
              <view>{{ orderInfoData._status._title }}</view>
            </view>
            <view class="order-date">
              {{orderInfoData._status._type === "2"?`${remainTimeStr}`:orderInfoData._status._msg }}
            </view>
          </view>
          <view class="address noBorder">
            <view class="address-icon">

              <image
                  class="image"
                  :src="orderAddressIcon"
              />
            </view>
            <view class="address-main">
              <view class="address-header">
                <view class="address-name">{{ orderInfoData.realName }}</view>
                <view class="address-phone">{{ orderInfoData.userPhone }}</view>
              </view>
              <view class="address-content">
                <view class="address-desc">{{ orderInfoData.userAddress }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="page-space">

        <view class="order-goods  page-card mb-20">
          <!-- <view class="order-header">
            <view class="order-logo">
              <image
                class="image"
                src="https://b2c-pro-static-dev.zkthink.com/static/images/flashKilling.png"
                alt=""
              />
            </view>
          </view> -->
          <view
              v-for="(item, index) in orderInfoData.cartInfo"
              class="order-evaluate"
              :class="{evaluateBtn: orderInfoData._status._type == 3}"
          >
            <goods
                list
                link
                interval
                desc="3"
                showAction
                model
                :purchase="item.cartNum"
                :data="item.productInfo"
            >
              <template #price>
                ￥{{ item.truePrice }}
              </template>
            </goods>
            <view
                v-if="orderInfoData.status == 2 && item.isReply === 0"
                @tap.stop="toEvaluate(item)"
                class="order-actions-primary order-evaluate-btn"
            >去评价
            </view>
          </view>
          <view class="order-infos infos mb-20 infos-right border-top">
            <view class="info-cell">
              <view class="info-cell-label">商品总价：</view>
              <view class="info-cell-value">¥{{ orderInfoData.cost }}</view>
            </view>
            <view class="info-cell ">
              <view class="info-cell-label">优惠：</view>
              <view class="info-cell-value">¥{{ orderInfoData.couponPrice }}</view>
            </view>
            <view class="info-cell ">
              <view class="info-cell-label">运费：</view>
              <view class="info-cell-value">¥{{ orderInfoData.totalPostage }}</view>
            </view>
            <view class="info-cell ">
              <view class="info-cell-label">总计：</view>
              <view class="info-cell-value">¥{{ orderInfoData.payPrice }}</view>
            </view>
          </view>
        </view>

        <view class="mb-20 card">
          <view class="card-head">
            <view class="card-title">
              订单信息
            </view>
          </view>
          <view class="card-content">
            <view class="infos">
              <view class="info-cell">
                <view class="info-cell-label">
                  订单编号
                </view>
                <view class="info-cell-value">
                  {{ orderInfoData.orderId }}
                </view>
                <view
                    class="info-cell-operation"
                    @click="setData(orderInfoData.orderId,'复制成功')"
                >
                  复制
                </view>

              </view>
              <view class="info-cell">
                <view class="info-cell-label">
                  创建时间
                </view>
                <view class="info-cell-value">
                  {{ $timeFormat(orderInfoData.createTime, 'yyyy-mm-dd hh:MM:ss') }}
                </view>
              </view>
              <view
                  class="info-cell"
                  v-if="orderInfoData.status > 0 && orderInfoData.payTime"
              >
                <view class="info-cell-label">
                  付款时间
                </view>
                <view class="info-cell-value">
                  {{ $timeFormat(orderInfoData.payTime, 'yyyy-mm-dd hh:MM:ss') }}
                </view>
              </view>
              <view
                  class="info-cell"
                  v-if="orderInfoData.deliveryTime"
              >
                <view class="info-cell-label">
                  发货时间
                </view>
                <view class="info-cell-value">
                  {{ $timeFormat(orderInfoData.deliveryTime, 'yyyy-mm-dd hh:MM:ss') }}
                </view>
              </view>
            </view>
          </view>
        </view>
        <view
            class="mb-20 card"
            v-if="orderInfoData.status >= 1"
        >
          <view class="card-head">
            <view class="card-title">
              物流信息
            </view>
          </view>
          <view
              class="card-content "
              v-if="expressData"
          >
            <view class="paddingH-10">
              <view class="no-express" v-if="expressData.length === 0">暂无轨迹信息</view>
              <uv-steps
                  v-else
                  current="0"
                  direction="column"
                  activeColor="#EE6D46"
                  inactiveColor="#E5E5E5"
              >
                <uv-steps-item
                    v-for="(item, index) in expressData"
                    :key="index"
                    :title="item.acceptStation"
                    :desc="item.acceptTime"
                ></uv-steps-item>
              </uv-steps>
            </view>
          </view>
        </view>
      </view>
      <view class="bottom-bar-bg"></view>

      <view
          class="order-actions bottom-bar"

      >
        <view class="order-actions-left">
        </view>
        <view class="order-actions-btns">
          <!--待付款-->
          <view
              v-if="orderInfoData._status._type === '0'"
              class="order-actions-delete"
              @tap="showModal(1)"
          >
            取消订单
          </view>
          <view
              v-if="orderInfoData._status._type === '0'"
              class="order-actions-primary"
              @tap="handlePay"
          >
            立即付款
          </view>
          <!-- 除了待付款和已取消 -->
          <view
              v-if="!['0','5','-1','-2'].includes(orderInfoData._status._type)"
              class="order-actions-delete"
              @tap="toSelectRefundGood(orderInfoData)"
          >
            申请退款
          </view>
          <!-- 已完成 -->
          <view
              v-if="['4'].includes(orderInfoData._status._type)"
              class="order-actions-primary"
              @tap="showModal(0)"
          >
            删除订单
          </view>
          <!-- 已发货 待收货 -->
          <view
              v-if="orderInfoData._status._type === '2'"
              class="order-actions-primary"
              @tap="showModal(2)"
          >
            确认收货
          </view>

        </view>
      </view>

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

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


</template>

<script setup>
import { orderDetailsBg, orderAddressIcon } from "@/utils/images";
import { computed, ref, unref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { orderCancel, orderDelete, orderExpress, orderInfo, orderTake } from '@/api/order'
import { orderReStatus } from '@/config'
import { useRouter } from "@/hooks/useRouter";
import { useShearPlate } from "@/hooks/useShearPlate";
import { useGlobalProperties } from "@/hooks";
import PayPopup from "@/components/PayPopup/index.vue";
import Modal from "@/components/Modal/index.vue";
import { useInterface } from "@/hooks/useInterface";
import {formatRemainTime} from "@/utils/utils";


const {$timeFormat} = useGlobalProperties()

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

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

const {setData} = useShearPlate();


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) {
    console.log(parseInt(res._status._type),'parseInt(res._status._type)')
    if(parseInt(res._status._type) === 2){
      remainTimeStr.value = formatRemainTime(res._status._payRemainTime)
    }
    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 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
    }
  })
}

// 去评价
const toEvaluate = (item) => {
  push({url: '/pages/evaluate/evaluate'}, {
    data: {
      unique: item.unique,
      orderId: item.orderId
    },
    type:'redirectTo'
  })
}

const toSelectRefundGood = () => {
  push({url: '/pages/selectRefundGood/selectRefundGood'}, {
    data: {
      id: orderInfoData.value.id
    }
  })
}

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



const modalRef = ref()
const modalType = ref(0) // 0删除 1取消 2确认收货
const modalTitle = computed(()=>{
  const tipsArr = ['确认删除订单吗？','确认取消订单吗？','确认要确认收货吗？']
  return tipsArr[modalType.value]
})

/**
 * 打开弹窗
 * @param {number} type 0删除记录 1撤销申请 2确认收货
 */
function showModal(type){
  modalType.value = type
  unref(modalRef).show()
}

/**
 * 确认弹窗
 */
function confirmModal(){
  const funcArr = [doDeleteRequest,doCancelRequest,doTakeRequest]
  funcArr[modalType.value]()
}

async function doDeleteRequest(){
  await orderDelete({
    uni: orderInfoData.value.orderId
  })
  toast({title: '删除成功'});
  setTimeout(()=>{
    goList()
  },2000)
}

async function doCancelRequest(){
  await orderCancel({
    id: orderInfoData.value.orderId
  })
  toast({title: '取消成功'});
  setTimeout(()=>{
    goList()
  },2000)
}

async function doTakeRequest(){
  let option = {
    uni: orderInfoData.value.orderId,
  }
  await orderTake(option)
  toast({title: '收货成功'});
  await handleOrderInfo({
    key: option.uni
  })
}


// ============================== 支付相关 ===============================
const payPopupRef = ref()

function openPay(orderId) {
  unref(payPopupRef).show(orderId)
}


function paySuccess() {
  push({url: '/pages/payStatus/index?type=1'})
}


onLoad((options) => {
  const params = getParams(options)
  handleOrderInfo({
    key: params.orderId
  })
})


</script>

<style lang="scss">
@import "../../style/images";
.orderList {
  padding: 20rpx 0;
}

.order-header {
}

.order-status-info {
  padding: 50rpx 0;


  .order-status {
    display: flex;
    align-items: center;
    height: 42rpx;
    font-size: 30rpx;
    color: #FFFFFF;
    margin-bottom: 20rpx;
    padding-left: 50rpx;
    background-size: 40rpx 40rpx;
    background-position: left center;
    background-repeat: no-repeat;

    .image {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    &.order-status-0,&.order-status--1,&.order-status-4,&.order-status-5,&.order-status-6,&.order-status-7 {
      background-image: $orderStateMoney;
    }

    &.order-status-1, &.order-status-99 {
      background-image: $orderStateReturn;
    }

    &.order-status-2, &.order-status-3 {
      background-image: $orderStateFinish;
    }
  }

  .order-date {
    height: 33rpx;
    font-size: 24rpx;
    color: #FFFFFF;
  }

}

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

  &:after {
    content: '';
  }
}

.no-express{
  font-size: 26rpx;
  padding: 20rpx 14rpx 30rpx;
}
</style>
