<script setup lang="ts">
import type { MapMarker, MapPolyline } from '@uni-helper/uni-types'
import { OrderStatus, handleCommonCancelOrder, handleCommonDeleteOrder, handleCommonOrderReceive, handleCommonOrderStatusText } from '../utils/order-data'
import { StaticUrl } from '@/config'
import router from '@/router'
import { getWxCommonPayment, handleCommonPayMent } from '@/subPack-xsb/utils/confirm-order'

const plugins = requirePlugin('logisticsPlugin')
const { statusBarHeight, MenuButtonHeight } = storeToRefs(useSysStore())
const { userInfo } = storeToRefs(useUserStore())
definePage({
  name: 'xsb-orderDetaile',
  islogin: true,
  style: {
    navigationBarTitleText: '订单详情',
    navigationStyle: 'custom',
  },
})
const collapse = ref(true)
const orderInfo = ref<Api.xsbOrderList>()
const orderNum = ref()
const mapInfo = ref<Api.RiderInfo>()
const mapMarkers = ref<MapMarker[]>([])
const mapPolyLine = ref<MapPolyline[]>([])
const showNode = ref(false)
const NodeList = ref<Api.DeliveryNode[]>([])
const viewDevyBtn = computed(() => {
  return orderInfo.value?.actualTotal && orderInfo.value.dvyType === 1
})
const showMapStatus = [OrderStatus.OrderAccepted, OrderStatus.OrderWaitDelivery, OrderStatus.OrderDelivering, OrderStatus.OrderArrived]
const mapStaticShopImg = {
  [OrderStatus.OrderAccepted]: `${StaticUrl}/order-map-jian.png`,
  [OrderStatus.OrderWaitDelivery]: `${StaticUrl}/order-map-wait.png`,
  [OrderStatus.OrderDelivering]: `${StaticUrl}/order-map-qishou.png`,
  [OrderStatus.OrderArrived]: `${StaticUrl}/order-map-qishou.png`,
}
const mapTextShop = {
  [OrderStatus.OrderAccepted]: '商家拣货中',
  [OrderStatus.OrderWaitDelivery]: orderInfo.value?.dvyType === 3 ? '等待骑手配送' : '待发货',
  [OrderStatus.OrderDelivering]: orderInfo.value?.dvyType === 3 ? '骑手配送中' : '待收货',
  [OrderStatus.OrderArrived]: '已送达',
}

const mapLation = computed(() => {
  const lation = {
    latitude: mapInfo.value?.shopLatitude,
    longitude: mapInfo.value?.shopLongitude,
    scale: 16,
  }
  if (orderInfo.value && mapInfo.value) {
    const lations = calculateCenterPointSpherical({ lat: orderInfo.value.latitude, lng: orderInfo.value.longitude }, { lat: mapInfo.value.shopLatitude as number, lng: mapInfo.value.shopLongitude as number })
    lation.latitude = lations.lat
    lation.longitude = lations.lng
    lation.scale = 6
  }
  return lation
})
onLoad((options: any) => {
  orderNum.value = options.id
  getDetail(options.id)
})
async function getDetail(id: string) {
  const { data } = await Apis.xsb.orderInfo({
    data: {
      orderNo: id,
    },
  })
  orderInfo.value = data
  if (showMapStatus.includes(data.hbOrderStatus)) {
    getOrderMapInf()
  }
}

function handleCollapse() {
  collapse.value = !collapse.value
}
async function handleCancel() {
  await handleCommonCancelOrder(orderInfo.value as Api.xsbOrderList)
  getDetail(String(unref(orderInfo)?.orderNumber))
}
async function handlePay() {
  const res = await handleCommonPayMent(String(unref(orderInfo)?.orderNumber))
  if (res.payType !== 1) {
    await getWxCommonPayment(res)
    getDetail(String(unref(orderInfo)?.orderNumber))
  }
  else {
    getDetail(String(unref(orderInfo)?.orderNumber))
  }
}
async function handelDel() {
  await handleCommonDeleteOrder(unref(orderInfo) as Api.xsbOrderList)
  router.back()
}
async function handleFinish() {
  uni.showLoading({ mask: true })
  setTimeout(async () => {
    await getDetail(String(unref(orderInfo)?.orderNumber))
    uni.hideLoading()
  }, 2000)
}
function handleCopy() {
  uni.setClipboardData({
    data: String(orderInfo.value?.orderNumber),
    showToast: true,
  })
}
async function handleAfterSale() {
  if (!orderInfo.value?.orderItemList) {
    useGlobalToast().show('商品异常！')
    return
  }
  await useSysStore().getRefunOrder(orderInfo.value.orderNumber as string)
}
async function getOrderMapInf() {
  const res = await Apis.xsb.riderInfo({ data: { orderNumber: orderNum.value } })
  mapInfo.value = res.data
  mapMarkers.value.push({
    id: 1,
    latitude: Number(mapInfo.value?.shopLatitude),
    longitude: Number(mapInfo.value?.shopLongitude),
    iconPath: mapStaticShopImg[orderInfo.value?.hbOrderStatus as keyof typeof mapStaticShopImg],
    width: 70,
    height: 80,
    label: {
      content: mapTextShop[orderInfo.value?.hbOrderStatus as keyof typeof mapTextShop],
      color: '#333',
      fontSize: 14,
      x: 0,
      y: 0,
      anchorX: 40,
      anchorY: -120,
      borderRadius: 8,
      borderWidth: 0,
      borderColor: '',
      bgColor: '#fff',
      padding: 5,
      display: 'BYCLICK',
      textAlign: 'left',
      customCallout: {
        display: 'BYCLICK',
        anchorX: 0,
        anchorY: 0,
      },
      ariaLabel: '',
      joinCluster: false,
    },
  }, {
    id: 2,
    longitude: Number(orderInfo.value?.longitude),
    latitude: Number(orderInfo.value?.latitude),
    iconPath: userInfo.value.avatarUrl || `${StaticUrl}/9.png`,
    width: 50,
    height: 50,
  })

  if (mapInfo.value?.riderLatitude && mapInfo.value?.riderLongitude) {
    mapMarkers.value.push({
      id: 3,
      longitude: Number(mapInfo.value?.riderLongitude),
      latitude: Number(mapInfo.value?.riderLatitude),
      iconPath: `${StaticUrl}/order-map-qishou.png`,
      width: 70,
      height: 80,
      label: {
        content: '骑手正在送货',
        color: '#333',
        fontSize: 14,
        x: 0,
        y: 0,
        anchorX: 40,
        anchorY: -120,
        borderRadius: 8,
        borderWidth: 0,
        borderColor: '',
        bgColor: '#fff',
        padding: 5,
        display: 'BYCLICK',
        textAlign: 'left',
        customCallout: {
          display: 'BYCLICK',
          anchorX: 0,
          anchorY: 0,
        },
        ariaLabel: '',
        joinCluster: false,
      },
    })
    mapPolyLine.value.push({
      points: [
        {
          longitude: Number(mapInfo.value?.riderLongitude),
          latitude: Number(mapInfo.value?.riderLatitude),
        },
        {
          longitude: Number(orderInfo.value?.longitude),
          latitude: Number(orderInfo.value?.latitude),
        },
      ],
      color: '#9ED605',
      width: 3,
    })
    // 绘制路径骑手和店家只能存在一个
    return
  }
  else {
    mapPolyLine.value.push({
      points: [
        {
          longitude: Number(orderInfo.value?.longitude),
          latitude: Number(orderInfo.value?.latitude),
        },
        {
          longitude: Number(mapInfo.value?.shopLongitude),
          latitude: Number(mapInfo.value?.shopLatitude),
        },
      ],
      color: '#9ED605',
      width: 3,
    })
  }

  console.log(mapPolyLine.value, 'mapPolyLine')
}
async function getOrderNode() {
  uni.showLoading({
    mask: true,
  })
  return new Promise((resolve, reject) => {
    Apis.xsb.deliveryNode({
      data: {
        orderNumber: String(orderInfo.value?.orderNumber),
      },
    }).then((res) => {
      NodeList.value = res.data
      resolve(res.data)
    }).catch((err) => {
      reject(err)
    }).finally(() => uni.hideLoading())
  })
}

async function handleMarkerTap(e: UniHelper.MapOnMarkertapEvent) {
  console.log(e, 'sadada')
  if (orderInfo.value?.dvyType === 3) {
    await getOrderNode()
    showNode.value = true
  }
  if (viewDevyBtn.value) {
    uni.showLoading({ mask: true })
    try {
      const res = await Apis.xsb.getWaybillToken({ data: { orderNumber: String(orderInfo.value?.orderNumber) } })
      uni.hideLoading()
      const jsData = JSON.parse(res.data)
      if (jsData.errmsg === 'ok') {
        plugins.openWaybillTracking({
          waybillToken: jsData.waybill_token,
        })
      }
    }
    catch {
      uni.hideLoading()
    }
  }
}
async function handleReceive() {
  await handleCommonOrderReceive(orderInfo.value as Api.xsbOrderList)
  getDetail(String(unref(orderInfo)?.orderNumber))
}
</script>

<template>
  <page-meta :page-style="showNode ? 'overflow: hidden;' : ''" />
  <view
    v-if="orderInfo" class="page-xsb"
    :style="{ paddingTop: `${showMapStatus.includes(orderInfo?.hbOrderStatus) ? '850rpx' : (`${Number(statusBarHeight) + Number(MenuButtonHeight) + 10}px`)}` }"
  >
    <wd-navbar
      title="订单详情" :bordered="false" :z-index="99" safe-area-inset-top left-arrow fixed
      @click-left="router.back()"
    />
    <view v-if="showMapStatus.includes(orderInfo?.hbOrderStatus)">
      <map
        id="orderMap" :polyline="mapPolyLine" :scale="mapLation.scale" :markers="mapMarkers"
        :latitude="mapLation.latitude" :longitude="mapLation.longitude" class="fixed top-0 z80 h-900rpx w-screen"
        @markertap="handleMarkerTap"
      />
    </view>

    <view class="relative z-90 box-border bg-#f6f6f6 px24rpx">
      <view class="pt20rpx">
        <view class="text-36rpx font-semibold">
          <view v-if="orderInfo.hbOrderStatus === OrderStatus.PaddingPay">
            <view class="flex items-center">
              请在
              <wd-count-down format="mm:ss" :time="handleCommonOrderStatusText(orderInfo)" @finish="handleFinish">
                <template #default="{ current }">
                  <view class="flex items-center">
                    <view> {{ current.minutes }} 分</view>
                    <view> {{ current.seconds }} 秒</view>
                  </view>
                </template>
              </wd-count-down>
              内支付
            </view>
            <view class="mt20rpx text-28rpx text-#AAAAAA">
              现在支付：预计10:40-10:55送达
            </view>
            <view class="btn mt20rpx flex items-center justify-between">
              <view class="info-btn mr20rpx w226rpx">
                <wd-button type="info" @click="handleCancel">
                  取消订单
                </wd-button>
              </view>
              <view class="ml20rpx flex-1">
                <wd-button @click="handlePay">
                  立即支付￥{{ orderInfo.actualTotal }}
                </wd-button>
              </view>
            </view>
          </view>
          <view
            v-if="orderInfo.hbOrderStatus !== OrderStatus.PaddingPay" class="flex items-center"
            @click="handleCollapse"
          >
            <view v-if="orderInfo.hbOrderStatus === OrderStatus.OrderAccepted" class="mr10rpx">
              商家拣货中
            </view>
            <view v-if="orderInfo.hbOrderStatus === OrderStatus.OrderWaitDelivery" class="mr10rpx">
              订单待配送
            </view>
            <view v-if="orderInfo.hbOrderStatus === OrderStatus.OrderDelivering" class="mr10rpx">
              订单配送中
            </view>
            <view v-if="orderInfo.hbOrderStatus === OrderStatus.OrderCancelAudit" class="mr10rpx">
              订单取消审核
            </view>
            <view v-if="orderInfo.hbOrderStatus === OrderStatus.OrderCancel" class="mr10rpx">
              订单取消
            </view>
            <view v-if="orderInfo.hbOrderStatus === OrderStatus.OrderArrived" class="mr10rpx">
              订单已送达
            </view>
            <view v-if="orderInfo.hbOrderStatus === OrderStatus.OrderCompleted" class="mr10rpx">
              订单已完成
            </view>
            <view :class="[collapse ? 'rotate-90' : '']">
              <wd-icon name="arrow-right" size="22px" />
            </view>
          </view>
          <view v-if="orderInfo.hbOrderStatus === OrderStatus.OrderCancel" class="mt20rpx text-28rpx text-#AAAAAA">
            取消原因：{{ orderInfo.cancelReason }}
          </view>
        </view>
      </view>
      <view class="mt20rpx rounded-16rpx bg-white p24rpx">
        <view v-if="orderInfo.dvyFlowId" class="mb24rpx text-24rpx">
          <view class="mb20rpx">
            {{ orderInfo.dvyName }}
          </view>
          <view class="text-48rpx font-semibold">
            {{ orderInfo.dvyFlowId }}
          </view>
        </view>
        <view class="grid grid-cols-5 text-28rpx text-#222">
          <view
            v-if="orderInfo.hbOrderStatus === OrderStatus.OrderArrived" class="flex flex-col items-center"
            @click="handleReceive"
          >
            <image :src="`${StaticUrl}/orderDetaile-submit-order.png`" class="h40rpx w40rpx" />
            <view class="mt40rpx">
              确认收货
            </view>
          </view>
          <view
            v-if="[OrderStatus.OrderCancel, OrderStatus.OrderCompleted].includes(Number(orderInfo.hbOrderStatus))"
            class="flex flex-col items-center" @click="handelDel"
          >
            <image :src="`${StaticUrl}/orderDetaile-del.png`" class="h40rpx w40rpx" />
            <view class="mt40rpx">
              删除订单
            </view>
          </view>
          <view class="contact relative flex flex-col items-center">
            <image :src="`${StaticUrl}/orderDetaile-wx.png`" class="h40rpx w40rpx" />
            <Zcontact>
              <view class="mt40rpx text-28rpx">
                联系商家
              </view>
            </Zcontact>
          </view>
          <view
            v-if="orderInfo.refundStatus == 2 || [OrderStatus.OrderCompleted, OrderStatus.OrderWaitDelivery, OrderStatus.OrderAccepted].includes(orderInfo.hbOrderStatus)"
            class="flex flex-col items-center" @click="handleAfterSale"
          >
            <image :src="`${StaticUrl}/orderDetaile-shou.png`" class="h40rpx w40rpx" />
            <view class="mt40rpx">
              申请售后
            </view>
          </view>

          <!-- <view class="flex  flex-col items-center " @click="router.push({ name: 'common-revalue' })">
          <image
            :src="`${StaticUrl}/orderDetaile-pj.png`"
            class="h40rpx w40rpx"
          />
          <view class="mt40rpx">
            评价晒单
          </view>
        </view> -->
          <!-- <view class="flex  flex-col items-center">
          <image
            :src="`${StaticUrl}/orderDetaile-bao.png`"
            class="h40rpx w40rpx"
          />
          <view class="mt40rpx">
            再次购买
          </view>
        </view> -->
        </view>
      </view>
      <view class="mt20rpx rounded-16rpx bg-white p24rpx">
        <view class="flex items-center">
          <image :src="`${StaticUrl}/orderDetaile-user.png`" class="mr20rpx h40rpx w40rpx" />
          <view class="text-32rpx text-#222 font-semibold">
            {{ orderInfo?.consigneeName }} {{ orderInfo?.consigneeMobile }}
          </view>
        </view>
        <view class="mt20rpx text-28rpx text-#AAAAAA">
          {{ orderInfo?.consigneeAddress }}
        </view>
      </view>
      <view class="mt20rpx rounded-16rpx bg-white p24rpx">
        <view class="flex items-center">
          <image :src="`${StaticUrl}/order-icon.png`" class="h36rpx w36rpx" />
          <view class="ml20rpx text-32rpx font-semibold">
            {{ orderInfo?.shopName }}
          </view>
        </view>
        <view class="my24rpx h2rpx w-full bg-#F0F0F0" />
        <CollapsePanel :line-height="150">
          <view v-for="item in orderInfo?.orderItemList" :key="item.skuId" class="mb20rpx w-full flex items-center">
            <view class="mr20rpx w120rpx flex-shrink-0">
              <image :src="item.pic" class="h120rpx w120rpx" />
            </view>
            <view class="flex-1">
              <view class="w-full flex items-center justify-between font-semibold">
                <view class="text-28rpx">
                  {{ item.skuName }}
                </view>
                <view class="text-32rpx text-#FF4D3A">
                  ￥{{ item.price }}
                </view>
              </view>
              <view class="text-24rpx text-#AAAAAA">
                规格：{{ item.spec }}
              </view>
              <view class="text-24rpx text-#AAAAAA">
                ×{{ item.prodCount }}
              </view>
            </view>
          </view>
        </CollapsePanel>

        <view class="mt24rpx h2rpx w-full bg-#F0F0F0" />
        <view class="mt24rpx flex items-center justify-between">
          <view class="text-28rpx">
            商品金额
          </view>
          <view class="text-#FF4A39 font-semibold">
            ￥{{ orderInfo?.total }}
          </view>
        </view>
        <view class="mt24rpx flex items-center justify-between">
          <view v-if="orderInfo.dvyType == 3">
            配送费（即时配送）
          </view>
          <view v-if="orderInfo.dvyType == 1">
            快递
          </view>
          <view class="text-#FF4A39 font-semibold">
            ￥{{ orderInfo?.freightAmount }}
          </view>
        </view>
        <view class="mt24rpx flex items-center justify-between">
          <view class="text-28rpx">
            积分
          </view>
          <view class="text-#FF4A39 font-semibold">
            -￥{{ Number(orderInfo?.offsetPoints) / 100 }}
          </view>
        </view>
        <view class="my24rpx h2rpx w-full bg-#F0F0F0" />
        <view class="flex items-center justify-end">
          <view class="text-28rpx">
            总计{{ orderInfo.orderMoney }} 共减 {{ Number(orderInfo.offsetPoints) / 100 }}
          </view>
          <view class="ml20rpx text-28rpx text-#FF4D3A font-semibold">
            {{ [OrderStatus.PaddingPay, OrderStatus.OrderCancel].includes(Number(orderInfo.hbOrderStatus)) ? '需' : '实'
            }}付款￥{{
              orderInfo.actualTotal }}
          </view>
        </view>
      </view>
      <view class="mt20rpx rounded-16rpx bg-white p24rpx">
        <view class="mb24rpx text-28rpx font-semibold">
          订单信息
        </view>
        <view class="pb20rpx">
          <view class="mb28rpx flex items-center justify-between">
            <view class="text-28rpx text-#AAAAAA">
              订单编号
            </view>
            <view class="flex items-center">
              <text class="text-#222">
                {{ orderInfo?.orderNumber }}
              </text>
              <view class="ml10rpx" @click="handleCopy">
                <wd-icon name="file-copy" size="22px" />
              </view>
            </view>
          </view>
          <view class="mb28rpx flex items-center justify-between">
            <view class="text-28rpx text-#AAAAAA">
              支付方式
            </view>
            <view class="text-#222">
              微信支付
            </view>
          </view>
          <view class="mb28rpx flex items-center justify-between">
            <view class="text-28rpx text-#AAAAAA">
              下单时间
            </view>
            <view class="text-#222">
              {{ orderInfo?.createTime }}
            </view>
          </view>
          <view class="mb28rpx flex items-center justify-between">
            <view class="text-28rpx text-#AAAAAA">
              备注信息
            </view>
            <view class="text-#222">
              {{ orderInfo?.remarks || '无' }}
            </view>
          </view>
        </view>
      </view>
      <view class="h80rpx" />
    </view>
    <Zpopup v-model="showNode" :showfooter="false">
      <view class="p24rpx">
        <view class="text-center text-32rpx font-semibold">
          订单追踪
        </view>
        <wd-steps :active="0" vertical dot>
          <wd-step v-for="item in NodeList" :key="item.id">
            <template #title>
              {{ item.content }}
            </template>
            <template #description>
              {{ item.createTime }}
            </template>
          </wd-step>
        </wd-steps>
      </view>
    </Zpopup>
  </view>
</template>

<style scoped lang="scss">
.page-xsb {
  :deep() {
    .info-btn .wd-button {
      background: #fff !important;
      color: #aaa !important;
    }

    .btn .wd-button {
      width: 100% !important;
    }

    .wd-count-down {
      color: #FF4D3A !important;
      font-size: 36rpx !important;
    }

    .contact .wd-button {
      font-size: 28rpx !important;
      height: 40rpx !important;
      padding: 0 !important;
      margin-top: 40rpx !important;
    }
  }
}
</style>
