<route lang="json5">
{
  style: {
    navigationBarTitleText: '确认订单',
    navigationBarBackgroundColor: '#fff',
  },
}
</route>

<script setup lang="ts">
import TiltedButton from '@/components/tilted-button.vue'
import Product from '../components/product.vue'
import { shoppingBag } from '@designer-hub/assets/src/assets/svgs/index'
import InvertedTrapezoidButton from '@/components/inverted-trapezoid-button.vue'
import TrapeziumButton from '@/components/trapezium-button.vue'
import Card from '@/components/card.vue'
import SectionHeading from '@/components/section-heading.vue'
import BottomAppBar from '@/components/bottom-app-bar.vue'
import { requestToast } from '../../../../core/utils/common'
import { getProductCoupons, orderPay } from '../../../../core/libs/requests'
import { useUserStore } from '../../../../store'
import { storeToRefs } from 'pinia'
import { useRouter } from '../../../../core/utils/router'
import dayjs from 'dayjs'
import { Coupon } from '../../../../core/libs/models'
import CouponCard from '@/pages/common/components/coupon-card.vue'
import { select, sort } from 'radash'
import CouponsSelector from '@/pages/common/components/coupons-selector.vue'
import { right } from '../../../../core/libs/svgs'

const router = useRouter()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const show = ref(false)
const a = ref(1)
const data = ref()
const selectedCoupons = ref<Coupon[]>()
const { data: coupons, run: setCoupons } = useRequest(() =>
  getProductCoupons({
    userId: userInfo.value.userId,
    productIds: data.value.list.map((it) => it.productId).join(','),
    isUse: 0,
  }),
)
const offerPoints = computed(() => {
  const products = sort(data.value?.list, (it: any) => it.points).reverse()
  let sumBrandPoints = 0
  products.forEach((product: any) => {
    if (selectedCoupons.value) {
      selectedCoupons.value.forEach((coupon) => {
        if (
          coupon.buinessId === product.vendorId &&
          coupon.productIds.split(',').includes(product.productId)
        ) {
          sumBrandPoints += product.points
        }
      })
    }
  })
  console.log(sumBrandPoints)
  return Number(sumBrandPoints)
})
const paidPoints = computed(() => {
  return (data.value?.totalsPoints - offerPoints.value || 0).toString()
})
const handlePay = async () => {
  console.log(111)

  const couponList =
    selectedCoupons.value?.map((it) => ({
      couponId: it.id,
      projectIds: it.productIds,
      buinessId: it.buinessId,
    })) || []
  const { code } = await requestToast(
    () =>
      orderPay({
        ...data?.value,
        couponList,
      }),
    { success: true, successTitle: '兑换成功' },
  )
  if (code === 0) {
    router.replace('/pages/home/mall/purchased/success/index')
  }
}
const handleQ = async () => {
  // await setCoupons()
  show.value = true
}
const handleSelect = (coupon: Coupon) => {
  selectedCoupons.value = [coupon]
  show.value = false
}
onLoad(async (query: { data: string }) => {
  data.value = JSON.parse(query.data)
})
</script>

<template>
  <view class="flex-grow flex flex-col px-3.5 py-5.5 gap-6">
    <Card>
      <div class="flex flex-col gap-6">
        <template v-for="(it, i) in data?.list" :key="i">
          <div class="flex gap-3">
            <div class="w-16 h-16 bg-[#f6f6f6] rounded-lg overflow-hidden">
              <wd-img width="100%" height="100%" :src="it.orderImgUrl"></wd-img>
            </div>
            <div class="flex flex-col justify-between flex-1">
              <div class="text-black/40 text-base font-normal font-['PingFang_SC'] leading-normal">
                {{ it.productName }}
              </div>
              <div class="text-black/40 text-xs font-normal font-['PingFang_SC'] leading-normal">
                {{ it.points }}积分
              </div>
            </div>
            <div>
              <div class="text-black/90 text-sm font-normal font-['PingFang_SC'] leading-[10.18px]">
                ×{{ it.nums }}
              </div>
            </div>
          </div>
        </template>
      </div>
    </Card>
    <Card>
      <div class="flex flex-col gap-8">
        <SectionHeading
          title="总积分"
          :end-text="data?.totalsPoints.toString()"
          size="sm"
        ></SectionHeading>
        <div @click="handleQ">
          <SectionHeading
            title="优惠券"
            :end-text="`已选${selectedCoupons?.length || 0}张`"
            end-arrow
            size="sm"
          >
            <template #start>
              <div
                v-if="selectedCoupons?.length"
                class="px-1 py-.75 rounded border border-solid border-[#ef4343] justify-center items-center gap-2.5 inline-flex"
              >
                <div
                  class="text-[#ef4343] text-[9px] font-normal font-['PingFang_SC'] leading-[10.18px]"
                >
                  已选{{ selectedCoupons?.length }}张
                </div>
              </div>
            </template>
            <template #append>
              <div class="flex items-center gap-1">
                <template v-if="!selectedCoupons?.length">
                  <div
                    class="text-black/40 text-sm font-normal font-['PingFang SC'] leading-[10.18px]"
                  >
                    选择优惠券
                  </div>
                </template>
                <template v-else>
                  <div
                    class="text-[#ef4343] text-sm font-normal font-['PingFang SC'] leading-[10.18px]"
                  >
                    -{{ offerPoints }}
                  </div>
                </template>
                <wd-img :src="right" width="12" height="12"></wd-img>
              </div>
            </template>
          </SectionHeading>
        </div>
        <SectionHeading title="实付积分" :end-text="paidPoints" size="sm"></SectionHeading>
      </div>
    </Card>
    <BottomAppBar fixed placeholder>
      <div class="h-[63px] bg-white backdrop-blur-[20px] flex px-3.5 items-center justify-between">
        <div class="flex">
          <div class="text-[#ef4343] text-2xl font-normal font-['D-DIN Exp'] leading-normal">
            {{ paidPoints }}
          </div>
          <div class="text-black/40 text-base font-normal font-['PingFang_SC'] leading-[34px]">
            积分
          </div>
        </div>
        <div class="">
          <TrapeziumButton size="large">
            <div class="text-white text-base font-normal font-['PingFang_SC'] leading-tight">
              <div
                class="text-white text-base font-normal font-['PingFang_SC'] leading-tight"
                @click="handlePay"
              >
                确认兑换
              </div>
            </div>
          </TrapeziumButton>
        </div>
      </div>
    </BottomAppBar>
    <CouponsSelector
      v-model="selectedCoupons"
      type="product"
      :show="show"
      :products="data?.list"
      @close="show = false"
    ></CouponsSelector>
    <!-- <CouponsSelector></CouponsSelector> -->
    <!-- <wd-action-sheet title="优惠券" v-model="show">
      <view class="">
        <wd-tabs>
          <wd-tab title="可用优惠券"></wd-tab>
          <wd-tab title="不可用优惠券"></wd-tab>
        </wd-tabs>
        <div class="bg-[#f6f6f6] py-3.5 flex flex-col gap-4">
          <template v-for="(it, i) in coupons" :key="i">
            <CouponCard
              :options="{ couponType: 2, ...it }"
              canSelect
              :selected="selectedCoupons?.map(({ id }) => id).includes(it.id)"
              @select="handleSelect"
            ></CouponCard>
          </template>
        </div>
      </view>
    </wd-action-sheet> -->
  </view>
</template>

<style scoped lang="scss"></style>
