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

<script setup lang="ts">
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 { getOrderAmount, getProductCoupons, orderPay } from '../../../../core/libs/requests'
import { useUserStore } from '../../../../store'
import { storeToRefs } from 'pinia'
import { useRouter } from '../../../../core/utils/router'
import { Coupon } from '../../../../core/libs/models'
import { sort } from 'radash'
import CouponsSelector from '@/pages/common/components/coupons-selector.vue'
import { right } from '../../../../core/libs/svgs'
import ButtonEvo from '@/components/button-evo.vue'
import { handleClickInstruction } from '../../../../core/libs/actions'
import { useMessage } from 'wot-design-uni'

const router = useRouter()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const show = ref(false)
const { alert } = useMessage()
const data = ref()
const selectedCoupons = ref<Coupon[]>([])
const requestData = computed(() => ({
  ...data.value,
  couponList:
    selectedCoupons.value?.map((it) => ({
      couponId: it.id,
      projectIds: it.productIds,
      buinessId: it.buinessId,
    })) || [],
}))
const { data: confirmOrder, run: setConfirmOrder } = useRequest(() =>
  getOrderAmount(requestData.value),
)
const { data: coupons, run: setCoupons } = useRequest(
  () =>
    getProductCoupons({
      userId: userInfo.value?.userId,
      productIds: data.value?.list.map((it) => it.productId).join(','),
    }),
  {},
)
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 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) {
    await 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
}
const handleClose = () => {
  show.value = false
  setConfirmOrder()
}
onLoad(async (query: { data: string }) => {
  data.value = JSON.parse(query.data)
  await Promise.all([setCoupons(), setConfirmOrder()])
  // await setConfirmOrder()
})
</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="confirmOrder?.totalsPoints.toString()"
          size="sm"
        ></SectionHeading>
        <div @click="handleQ">
          <!--          {{ selectedCoupons }}-->
          <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-sm font-normal font-['PingFang_SC'] leading-[10.18px]"
                    :class="coupons.length ? 'text-[#ef4343]' : 'text-black/40'"
                  >
                    {{ coupons.length ? `${coupons.length}张可用` : '无可用' }}
                  </div>
                </template>
                <template v-else>
                  <div
                    class="text-[#ef4343] text-sm font-normal font-['PingFang_SC'] leading-[10.18px]"
                  >
                    -{{ confirmOrder.totalsCouponPoints }}
                  </div>
                </template>
                <wd-img :src="right" width="12" height="12"></wd-img>
              </div>
            </template>
          </SectionHeading>
        </div>
        <SectionHeading
          title="实付积分"
          :end-text="String(confirmOrder?.totalsCurrPoints)"
          size="sm"
        ></SectionHeading>
      </div>
    </Card>
    <BottomAppBar fixed placeholder>
      <div class="h-[63px] bg-white backdrop-blur-[20px] flex items-center justify-between">
        <div class="flex items-end gap-1.25">
          <div class="text-[#ef4343] text-2xl font-normal font-['D-DIN_Exp'] leading-7">
            {{ confirmOrder?.totalsCurrPoints }}
          </div>
          <div class="text-black/40 text-base font-normal font-['PingFang_SC']">积分</div>
        </div>
        <div class="">
          <ButtonEvo @click="handlePay">确认兑换</ButtonEvo>
        </div>
      </div>
    </BottomAppBar>
    <CouponsSelector
      v-model="selectedCoupons"
      type="product"
      :show="show"
      :products="data?.list"
      @close="handleClose"
      @click-instruction="(e) => handleClickInstruction(alert, e)"
    ></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>
