<template>
  <view>
    <!-- 导航栏 -->
    <!-- <u-navbar back-icon-color="#000000" title-color="#000000" title="确认支付">
      <view slot="right" class="pr-base" @tap="$u.routeAuth('/pages/auxiliary_cart/index')">
        <image class="w-48rpx h-48rpx" src="/static/images/cart/short-cart.png" mode="scaleToFill" />
      </view>
    </u-navbar> -->
    <!--  -->

    <loading-view v-if="isFirstLoading"></loading-view>

    <view class="bg-white h-750rpx rounded-b-xs px-base">
      <view class="text-xl text-txBase font-extrabold pt-40rpx pl-base">{{ detail.status | payStatusText }}</view>
      <view class="pl-base text-bgSubtitle text-lg mt-rowLg border-b border-txBorder pb-rowLg"
        >剩余时间：<u-count-down v-if="expiresAt" :timestamp="expiresAt" font-size="32" color="#f0ad4e" separator-color="#f0ad4e" @end="onCountEnd">
        </u-count-down>
      </view>
      <view class="px-base pt-rowLg text-lg text-txGray">
        <view class="pt-base">订单编号：{{ detail.sn }}</view>
        <view class="pt-base" v-if="detail.total_points>0">抵扣积分：{{ detail.total_points }}</view>
        <view class="pt-base">订单金额：{{ detail.products_total_amount }}元</view>
        <view class="pt-base" v-if="!!detail.consignee_name">收货人：{{ detail.consignee_name }}</view>
        <view class="pt-base" v-if="!!detail.consignee_telephone"> 联系方式：{{ detail.consignee_telephone }}</view>
      </view>
    </view>
    <view class="bg-white w-710rpx m-auto shdow -mt-130rpx">
      <radio-group class="" @change="radioChange">
        <label v-for="(item, index) in payList" :key="index" class="flex items-center px-base py-rowLg border-b border-txBorder">
          <radio
            class="mr-base"
            color="#2ab31c"
            style="transform: scale(0.8)"
            :value="String(item.pay_way)"
            :checked="item.pay_way == payWay"
            :disabled="item.disabled"
          ></radio>
          <view class="flex">
            <view class="text-xl text-txBase">{{ item.name }}</view>
            <view class="text-xl text-txBase" v-if="item.pay_way == 'balance'">（{{ balance.balance }}）</view>
            <view class="text-xl text-txBase" v-if="item.pay_way == 'wallet'">（{{ wallet.balance }}）</view>
          </view>
        </label>
      </radio-group>
    </view>
    <!--  -->
    <view class="flex items-center justify-end bg-white shadow-up fixed right-0 left-0 bottom-0 cu-bar tabbar">
      <view class="text-lg text-bgSubtitle mr-rowLg" v-if="discountCount">-￥{{ discountCount }}</view>
      <view class="text-md text-txBase">
        合计: <text class="text-xl text-txSvip">￥{{ detail.total_amount }}</text>
      </view>
      <view class="w-180rpx h-66rpx leading-66rpx text-center text-lg ml-40rpx text-white bg-primary rounded-lg mr-base" @tap="onPay">确认支付</view>
    </view>

    <!-- 输入密码 -->
    <password-popup v-model="passwordShow" @getPassword="onPwdChange">
      <view v-if="passwordError" class="text-center text-error">密码错误</view>
    </password-popup>
    <!-- 没有密码 -->
    <cu-modal
      v-model="noPayPwdShow"
      title="您还未设置支付密码？"
      :showCancelButton="true"
      confirmText="去设置"
      @confirm="$u.routeAuth('/pageA/reset_password/secure')"
      content="提示：请先设置后在进行操作～"
    ></cu-modal>

    <!-- 放弃支付 -->
    <cu-modal
      v-model="giveuUpPayShow"
      showCancelButton
      title="确定放弃付款吗？"
      confirmText="继续支付"
      cancelText="忍痛离开"
      @cancel="onBack()"
      content="好货不等人，请尽快支付～"
    ></cu-modal>
  </view>
</template>

<script>
let loadingBtn = false;
import { sub } from '@/utils';
import { wxpay, alipay } from '@/utils/pay.js';
import { payWay as payWayTool } from '@/utils/tools.js';
export default {
  data() {
    return {
      isFirstLoading: true,
      passwordShow: false,
      noPayPwdShow: false,
      passwordError: false,
      giveuUpPayShow: false, //  退出拦截
      id: '',
      payData: null,
      payWayArr: [
        {
          name: '微信支付',
          pay_way: 'wxpay',
        },
        // {
        //   name: '支付宝',
        //   pay_way: 'alipay',
        // },
        // {
        //   name: '可提',
        //   pay_way: 'wallet',
        // },
        // {
        //   name: '余额',
        //   pay_way: 'balance',
        // },
      ],
      payWay: 'wxpay',
      detail: {},
      payList: [],
    };
  },
  async onLoad({ id }) {
    this.id = id;
    await this.$store.dispatch('app/getConfit');
    this.$store.dispatch('user/getUserInfo');
    this.getDetail();
    this.getPayList();
  },
  onBackPress() {
    if (this.giveuUpPayShow) {
      return false;
    }
    this.giveuUpPayShow = true;
    return true;
  },
  computed: {
    userInfo() {
      return this.$store?.getters?.user;
    },
    wallet() {
      return this.userInfo?.wallet ?? {};
    },
    balance() {
      return this.userInfo?.balance ?? {};
    },
    discountCount() {
      return sub(this.detail?.products_total_amount ?? 0, this.detail?.total_amount ?? 0);
    },
    payWayShow() {
      return this.$store.getters.hiddenConfig?.pay_way ?? this.payWayArr.map(({ pay_way }) => pay_way);
    },
    expiresAt() {
      return this.detail?.expires_at ?? 0;
    },
  },
  methods: {
    getPayList() {
      const arr = this.payWayArr.filter(({ pay_way }) => this.payWayShow.findIndex((e) => e == pay_way) >= 0);
      const list = arr.filter(({ pay_way }) => {
        let isShow = true;
        if (pay_way == 'wallet') {
          if (this.wallet.is_frozen) {
            isShow = false;
          } else {
            isShow = true;
          }
        }
        if (pay_way == 'balance') {
          if (this.balance.is_frozen) {
            isShow = false;
          } else {
            isShow = true;
          }
        }
        return isShow;
      });
      this.payList = list;
    },
    //密码确认
    async onPwdChange(e) {
      this.passwordShow = false;
      try {
        await this.$api.post('/v1/wallet/pay', { ...this.payData, pay_password: e, pay_way: this.payWay }, { custom: { toast: false } });
        this.getPlayResults('success');
      } catch (error) {
        if (error.errcode == 10001) {
          this.passwordError = true;
          this.passwordShow = true;
        } else {
          this.$u.toast(error.message ?? '系统繁忙，请稍后再试');
        }
      }
    },

    //支付结果页面
    getPlayResults(type) {
      // this.giveuUpPayShow = true
      this.$u.routeAuth({
        url: '/pages/payment_results/payment_results',
        type: 'redirectTo',
        params: {
          id: this.id,
          type: type,
        },
      });
    },

    radioChange(e) {
      this.payWay = e.detail.value;
    },
    async onPay() {
      if (loadingBtn) return;
      loadingBtn = true;
      try {
        let payWay = this.payWay;
        //微信支付
        if (this.payWay == 'wxpay') {
          payWay = payWayTool.wxValue;
        } else if (this.payWay == 'alipay') {
          payWay = payWayTool.aliValue;
        } else if (this.payWay == 'wallet') {
          if (!this.wallet.has_password) return (this.noPayPwdShow = true);
          if (sub(this.wallet.balance, this.detail.total_amount) < 0) return this.$u.toast('可提不足');
        } else if (this.payWay == 'balance') {
          if (!this.wallet.has_password) return (this.noPayPwdShow = true);
          if (sub(this.balance.balance, this.detail.total_amount) < 0) return this.$u.toast('余额不足');
        }

        const resData = await this.$api.post(`/v1/order/orders/${this.id}/pay`, {
          pay_way: payWay,
        });
        this.payData = resData.data;
        if (this.payWay == 'wxpay') {
          wxpay(resData.data).then((res) => {
            this.getPlayResults(res);
          });
        } else if (this.payWay == 'alipay') {
          alipay(resData.data).then((res) => {
            this.getPlayResults(res);
          });
        } else if (this.payWay == 'wallet' || this.payWay == 'balance') {
          this.passwordShow = true;
        }
      } catch (error) {
        // this.getPlayResults('fail');
      } finally {
        loadingBtn = false;
      }
    },
    onChangePayWay(e) {
      this.payWay = e;
    },
    async getDetail() {
      try {
        const resData = await this.$api.get(`/v1/order/orders/${this.id}`);
        this.detail = resData;
        if (this.detail.status != 0) {
          this.$u.route({ url: `/pages/order_details/index`, type: 'redirectTo', params: { id: this.id } });
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.isFirstLoading = false;
      }
    },
    async onCountEnd() {
      this.getDetail();
    },
    onBack() {
      uni.navigateBack();
    },
  },
};
</script>

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