<script setup lang="ts">
import { clearCart, getOrderPayMent, getWxCommonPayment, handleCommonPayMent, payError, paySuccess } from '../utils/confirm-order'
import router from '@/router'

definePage({
  name: 'xsb-confirmOrder',
  islogin: true,
  style: {
    navigationBarTitleText: '提交订单',
  },
})
const { selectedAddress, userInfo } = storeToRefs(useUserStore())
const { SelectShopInfo } = storeToRefs(useSysXsbStore())
const orderInfo = ref<Api.shoppingCartOrderConfirm>()
const { totalProduct } = storeToRefs(useSmqjhCartStore())
const isPay = ref(false)
const remarks = ref('')

const offsetPoints = computed(() => {
  const money = (Number(unref(orderInfo)?.transfee) * 100) + (Number(unref(orderInfo)?.price) * 100)
  if (Number(unref(orderInfo)?.offsetPoints) > money) {
    return money
  }
  return Number(unref(orderInfo)?.offsetPoints)
})
const deliveryType = ref(1)
onLoad((options: any) => {
  console.log(options.data)
  orderInfo.value = JSON.parse(options.data)
})
onShow(() => {
  useUserStore().getuserAddresslist()
  if (selectedAddress.value) {
    getDevryList()
  }
})

async function getDevryList() {
  const res = await Apis.xsb.delivery({
    data: {
      memberId: userInfo.value.id,
      shopId: SelectShopInfo.value.shopId,
      addressId: selectedAddress.value?.id,
    },
  })
  deliveryType.value = res.data.deliveryType
  console.log(res)
}

async function handlePay() {
  if (!selectedAddress.value) {
    useGlobalToast().show({ msg: '请选择收货地址' })
    return
  }
  if (!orderInfo.value) {
    useGlobalToast().show({ msg: '网络异常！请联系客服' })
    return
  }
  isPay.value = true
  try {
    const orderItemList = orderInfo.value?.skuList.map((it) => {
      return {
        prodCount: it.num,
        skuId: it.skuId,
      }
    })

    const orderNumber = await getOrderPayMent(orderInfo.value.transfee, 'XSB', deliveryType.value, Number(orderInfo.value?.skuList[0].shopId || SelectShopInfo.value.shopId), orderItemList, unref(remarks))
    const res = await handleCommonPayMent(orderNumber)
    await clearCart(orderInfo.value.skuList)
    totalProduct.value = null
    if (res.payType !== 1) {
      await getWxCommonPayment(res)
      await paySuccess()
      isPay.value = false
    }
    else {
      await paySuccess()
      isPay.value = false
    }
  }
  catch {
    await payError()
    isPay.value = false
  }
}
</script>

<template>
  <view class="page px20rpx py20rpx">
    <view class="mb20rpx rounded-16rpx bg-white p24rpx" @click="router.push({ name: 'common-addressList', params: { type: 'select' } })">
      <view class="flex items-center justify-between">
        <view v-if="!selectedAddress" class="flex items-center">
          <wd-icon name="location" size="18px" />
          <view class="ml10rpx text-28rpx">
            请添加收货地址
          </view>
        </view>
        <view v-else>
          <view class="flex items-center">
            <view v-if="selectedAddress.defaulted" class="mr20rpx">
              <wd-tag type="primary">
                默认
              </wd-tag>
            </view>
            <view class="flex items-center text-28rpx font-semibold">
              <view>{{ selectedAddress?.consigneeName }} </view>
              <view class="ml20rpx">
                {{ selectedAddress?.consigneeMobile }}
              </view>
            </view>
          </view>
          <view class="mt20rpx flex items-center text-24rpx text-#AAAAAA">
            {{ selectedAddress?.province }} {{ selectedAddress?.city }} {{ selectedAddress?.detailAddress }}
          </view>
        </view>
        <wd-icon name="arrow-right" size="18px" color="#aaa" />
      </view>
    </view>

    <view class="rounded-16rpx bg-white p24rpx">
      <view class="flex items-center text-28rpx font-semibold">
        {{ orderInfo?.shopName }}
      </view>
      <view class="my24rpx h2rpx w-full bg-#F0F0F0" />
      <CollapsePanel :line-height="150">
        <view v-for="item in orderInfo?.skuList" :key="item.id" 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.num || 1 }}
            </view>
          </view>
        </view>
      </CollapsePanel>
    </view>
    <view class="mt20rpx rounded-16rpx bg-white p24rpx">
      <view class="mb28rpx flex items-center justify-between text-28rpx">
        <view>商品金额</view>
        <view class="text-#FF4D3A font-semibold">
          ￥{{ orderInfo?.price }}
        </view>
      </view>
      <view class="mb28rpx flex items-center justify-between text-28rpx">
        <view v-if="deliveryType == 3">
          配送费（即时配送）
        </view>
        <view v-if="deliveryType == 1">
          快递
        </view>
        <view class="text-#FF4D3A font-semibold">
          ￥{{ orderInfo?.transfee }}
        </view>
      </view>
      <view class="flex items-center justify-between text-28rpx">
        <view>积分（{{ orderInfo?.offsetPoints }}）</view>
        <view class="text-#FF4D3A font-semibold">
          - ￥{{ offsetPoints / 100 }}
        </view>
      </view>
      <view class="my24rpx h2rpx w-full bg-#F0F0F0" />
      <view class="flex items-center justify-between text-28rpx">
        <view class="font-semibold">
          总计：
        </view>
        <view class="text-#FF4D3A font-semibold">
          ￥ {{ orderInfo?.totalPrice }}
        </view>
      </view>
    </view>
    <view class="mt20rpx flex items-center rounded-16rpx bg-white p24rpx">
      <view class="w80rpx">
        备注
      </view>
      <view class="flex-1">
        <wd-input v-model="remarks" placeholder="选填，请先和商家协商一致，付款后商家可见" no-border clearable />
      </view>
    </view>
    <view class="h250rpx" />
    <view class="ios footer fixed bottom-0 left-0 box-border w-full rounded-t-16rpx bg-white px24rpx">
      <view class="box-border w-full flex items-center justify-between py20rpx">
        <view class="flex items-center text-#FF4D3A">
          <view class="font-semibold10 flex items-baseline text-36rpx">
            <text class="text-24rpx">
              ￥
            </text> {{ orderInfo?.totalPrice }}
          </view>
          <view class="ml20rpx text-22rpx">
            共减￥{{ offsetPoints / 100 }}
          </view>
        </view>
        <view class="w180rpx">
          <wd-button size="large" :loading="isPay" :disabled="isPay" @click="handlePay">
            立即支付
          </wd-button>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
  .footer{
    box-shadow: 0rpx -6rpx 12rpx 2rpx rgba(0,0,0,0.05);
  }
  .page{
    :deep(){
      .wd-button{
        width: 180rpx !important;
      }
    }
  }
</style>
