<template>
  <view class="flex flex-col items-center justify-center">
    <!--    <view class="mt-6 text-[#8C8C8C] text-[25px]"-->
    <!--    >交易剩余时间：{{ tStr }}-->
    <!--    </view>-->
    <!--    <view class="flex items-center mt-5 mb-5">-->
    <!--      <nut-price :price="a" size="large" />-->
    <!--      <view class="line"></view>-->
    <!--      <nut-price position="after" symbol="积分" :price="b" size="large" />-->
    <!--    </view>-->
    <!--  商品信息  -->
    <view class="w-full" v-for="(itm, idx) in orderData" :key="idx">
      <view class="order-card">
        <view class="mb-[10px] text-[28px] text-[#9C9C9C]"
          >{{ itm.Store.name }}
        </view>
        <view
          class="center mb-[20px]"
          v-for="(item, index) in itm.OrderGoods"
          :key="index">
          <view class="top">
            <image :src="item.Goods.cover" />
            <view class="flex flex-col justify-between flex-1 h-[150px]">
              <view class="title line-clamp-2 text-[25px]"
                >{{ item.Goods?.name }}
              </view>
              <view class="text-[#F83D3D] mt-5">
                <view
                  >￥{{ item.pay_price }}元
                  <text v-if="item.pay_integral > 0"
                    >+{{ item.pay_integral }}积分</text
                  >
                </view>
              </view>
            </view>
            <view class="right">
              <view>x{{ item.number }}</view>
            </view>
          </view>
        </view>
        <!-- <view class="line"></view> -->
        <view
          class="flex justify-between items-center mt-2 mb-2 text-[25px] text-right">
          <text class="text-[#9C9C9C] text-[28px]"
            >共{{ itm.count }}件商品
          </text>
          <text class="text-[26px]"
            >应付款: ￥{{ itm.discount_price }}元
            <text v-if="itm.exchange > 0"> 积分抵扣: {{ itm.exchange }}</text>
          </text>
          <!-- <view class="line"></view> -->
        </view>
      </view>
    </view>

    <!-- {{ payVal }} -->
    <nut-radio-group class="w-[95%]" v-model="payVal">
      <nut-cell-group class="w-full">
        <nut-cell class="text-[#333333]" title="支付方式"></nut-cell>
        <nut-cell
          v-for="(item, index) in payList"
          :key="index"
          class="flex items-center"
          :title="item.name"
          :desc="
            item.number > 0
              ? `可用积分:${item.number}`
              : item.name.includes('微信')
                ? '微信全额支付'
                : ''
          "
          @click="cellClick(item.ID)">
          <template #icon>
            <IconFont size="30" :name="item.icon" />
          </template>
          <template #link>
            <nut-radio :label="item.ID"></nut-radio>
          </template>
        </nut-cell>
      </nut-cell-group>
    </nut-radio-group>
    <view class="w-[90%] mt-[30px]">
      <nut-button
        shape="square"
        :loading="isLoading"
        :disabled="isLoading"
        type="primary"
        block
        @click="pay"
        >确认支付
      </nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import Taro from '@tarojs/taro';
import { IconFont } from '@nutui/icons-vue-taro';
import { onUnmounted, ref } from 'vue';
import { getActiveOrderDetail, getPayList } from '@/api/goods';
import { payOrder } from '@/api/order';
import * as dayjs from 'dayjs';

const payVal = ref();

const t_id = ref();

const tStr = ref('00:00');

const orderData = ref<any>([]);

const isLoading = ref(false);

const opt = ref<any>({});

Taro.useLoad(e => {
  const { oid, bid, OrderType } = e;
  opt.value = e;
  get_pay_list();
  getData(oid, bid, OrderType);
});

// const a = ref(0);
// const b = ref(0);

const payList = ref<any>([]);

const get_pay_list = async () => {
  const res = await getPayList({});
  payList.value = res.data.data || [];
  payVal.value = payList.value[0].ID;
};

const getData = async (oid: string, bid: string, OrderType: number) => {
  // const user_info = Taro.getStorageSync('userInfo');
  // const data = await getUserPoint({
  //   phone: user_info.data.phone,
  //   bid,
  // });

  const res = await getActiveOrderDetail({
    oid,
    OrderType: Number(OrderType),
  });

  // let a = 0;
  // let b = 0;

  // orderData.value = {
  //   ...res.data.data[0],
  //   ...data.data,
  // };

  orderData.value = res.data.data || [];

  // console.log(orderData.value)

  // a.value = 0;
  // b.value = 0;

  // res.data.data.forEach(item => {
  //   a.value += item.price;
  //   b.value += item.discount_integral;
  // });

  if (!orderData.value.length)
    return Taro.showToast({
      title: '未获取到订单信息~',
      icon: 'none',
    });
  // countdownTime();
};

const pay = async () => {
  try {
    if (isLoading.value) return;
    isLoading.value = true;
    if (!payVal.value)
      return Taro.showToast({ title: '请选择支付方式', icon: 'none' });
    await confirmPay();
  } catch (error) {
    Taro.showToast({
      title: error.msg,
      icon: 'none',
    });
  }
};

const confirmPay = async () => {
  try {
    const res = await payOrder({
      oid: opt.value.oid,
      OrderType: payVal.value,
      PayType: payVal.value,
    });
    Taro.requestPayment({
      timeStamp: res.data.data.timeStamp,
      nonceStr: res.data.data.nonceStr,
      package: res.data.data.package,
      signType: res.data.data.signType,
      paySign: res.data.data.paySign,
      success: function () {
        Taro.showToast({
          title: '支付成功',
          icon: 'success',
        });
        isLoading.value = false;
      },
      fail: function () {
        Taro.showToast({
          title: '支付失败',
          icon: 'none',
        });
      },
      complete: function () {
        setTimeout(() => {
          Taro.redirectTo({
            url: `/pages/users/order_list/index?type=0`,
          });
        }, 2000);
        // isLoading.value = false;
      },
    });
  } catch (err) {
    Taro.showToast({
      title: err.msg,
      icon: 'none',
    });
  } finally {
    // isLoading.value = false;
  }
};

const cellClick = (val: number) => {
  payVal.value = val;
};

const countdownTime = () => {
  if (!orderData.value.expires) return;
  t_id.value = setInterval(() => {
    const nowTime = dayjs().valueOf();
    const endTime = orderData.value.expires * 1000;
    const time = endTime - nowTime;
    tStr.value = dayjs(time).format('mm:ss');
  }, 1000);
};

Taro.useDidHide(() => {
  clearInterval(t_id.value);
});

onUnmounted(() => {
  clearInterval(t_id.value);
});
</script>

<style lang="scss">
@import './index.scss';
</style>
