<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>
    <!-- {{ 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 : ''"
          @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
          class="flex items-center"
          title="平台积分支付"
          :desc="`剩余积分:${orderData.User?.integral || 0}`"
          @click="cellClick(2, orderData.User?.integral === 0)">
          <template #icon>
            <IconFont size="30" :name="require('../../../static/pt.png')" />
          </template>
          <template #link>
            <nut-radio
              :disabled="orderData.User?.integral === 0"
              :label="2"></nut-radio>
          </template>
        </nut-cell>
        <nut-cell
          class="flex items-center"
          title="天才小猪积分支付"
          :desc="`剩余积分:${orderData.integral || 0}`"
          @click="cellClick(3, orderData.integral === 0)">
          <template #icon>
            <IconFont size="30" :name="require('../../../static/jh.png')" />
          </template>
          <template #link>
            <nut-radio
              :disabled="orderData.integral === 0"
              :label="3"></nut-radio>
          </template>
        </nut-cell> -->
      </nut-cell-group>
    </nut-radio-group>
    <view class="w-[90%] mt-[100px]">
      <nut-button
        shape="square"
        :loading="isLoading"
        type="primary"
        block
        @click="pay"
        >确认支付
      </nut-button>
    </view>

    <nut-short-password
      title="请输入交易密码"
      tips="忘记密码"
      desc=" "
      :error-msg="error_msg"
      v-model="shortVal"
      v-model:visible="visible"
      :length="6"
      :close-on-click-overlay="false"
      @focus="showKeyboard = true"
      @complete="shortComplete"
      @close="shortClose"
      @tips="onTips">
    </nut-short-password>
    <nut-number-keyboard
      v-model="shortVal"
      v-model:visible="showKeyboard"
      @blur="showKeyboard = false">
    </nut-number-keyboard>

    <nut-dialog
      title="设置交易密码"
      content="您还未设置交易密码，请前往设置"
      cancel-text="其他支付方式"
      ok-text="设置交易密码"
      v-model:visible="visible2"
      @cancel="visible2 = false"
      @ok="onTips">
    </nut-dialog>
  </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, checkTradePwd, getPayList} from '@/api/goods';
import {getUserPoint} from '@/api/admin';
import {payOrder} from '@/api/order';
import {isCheckTradePwd} from '@/api/user';
import * as dayjs from 'dayjs';

const payVal = ref();

const t_id = ref();

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

const error_msg = ref('');

const shortVal = ref('');

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

const visible = ref(false);

const showKeyboard = ref(false);

const isLoading = ref(false);

const visible2 = 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({});
  // console.log(res);
  payList.value = res.data.data || [];
};

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,
  };

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

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

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

const pay = async () => {
  try {
    isLoading.value = true;
    if (!payVal.value)
      return Taro.showToast({title: '请选择支付方式', icon: 'none'});
    if (payVal.value !== 1) {
      const res = await isCheckTradePwd();
      if (res.data.pay_password) {
        visible.value = true;
        showKeyboard.value = true;
      } else {
        isLoading.value = false;
        visible2.value = true;
      }
    } else {
      await confirmPay();
    }
  } catch (error) {
    isLoading.value = false;
    Taro.showToast({
      title: error.msg,
      icon: 'none',
    });
  }
};

const shortComplete = async value => {
  try {
    await checkTradePwd({
      pay_password: value,
    });
    shortClose(false);
    await confirmPay();
  } catch (error) {
    error_msg.value = error.msg;
    shortVal.value = '';
  }
};

const confirmPay = async () => {
  try {
    const res = await payOrder({
      // oid: opt.value.oid.map(item => item.oid),
      oid: opt.value.oid,
      OrderType: payVal.value,
      PayType: payVal.value,
    });
    switch (payVal.value) {
      case 1:
        if (typeof res.data.data === 'object') {
          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',
              });
            },
            fail: function () {
              Taro.showToast({
                title: '支付失败',
                icon: 'none',
              });
            },
            complete: function () {
              // Taro.redirectTo({
              //   url: `/pages/users/order_list_detail/index?orderId=${opt.value.oid}&OrderType=1`,
              // });
              Taro.redirectTo({
                url: `/pages/users/order_list/index?type=0`,
              });
            },
          });
        } else {
          Taro.showToast({
            title: '参数获取失败，请重试~',
            icon: 'none',
          });
        }
        break;
      default:
        Taro.showToast({
          title: res.msg,
          icon: 'none',
        });
        setTimeout(() => {
          // Taro.redirectTo({
          //   url: `/pages/users/order_list_detail/index?orderId=${opt.value.oid}&OrderType=1`,
          // });
          Taro.redirectTo({
            url: `/pages/users/order_list/index?type=0`,
          });
        }, 2000);
        break;
    }
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
    Taro.showToast({
      title: err.msg,
      icon: 'none',
    });
  }
};

const shortClose = (isMsg: boolean = true) => {
  showKeyboard.value = false;
  visible.value = false;
  isLoading.value = false;
  shortVal.value = '';
  error_msg.value = '';
  if (isMsg) Taro.showToast({title: '支付取消', icon: 'none'});
};

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);
};

const onTips = () => {
  Taro.redirectTo({
    url: '/pages/users/pwd/index',
  });
};

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

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

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