<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="orderData.price" size="large" />
      <view class="line"></view>
      <nut-price
        :decimal-digits="0"
        position="after"
        symbol="积分"
        :price="orderData.exchange"
        size="large" />
    </view>
    <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
          class="flex items-center"
          title="微信支付"
          @click="cellClick(1, false)">
          <template #icon>
            <IconFont size="30" :name="require('../../../static/wx.png')" />
          </template>
          <template #link>
            <nut-radio :label="1"></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" />
  </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} 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} = e;
  opt.value = e;
  getData(oid, bid);
});

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

  orderData.value = {
    ...res.data.data,
    ...data.data,
  };
  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,
      OrderType: orderData.value.pay_type,
      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}`,
              });
            },
          });
        } 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}`,
          });
        }, 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, isTrue: boolean) => {
  if (isTrue) {
    Taro.showToast({
      title: '该支付暂不可用！',
      icon: 'none',
    });
    payVal.value = undefined;
  } else {
    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>
