<template>
  <window-size>
    <payment-countdown @onFinish="countdownFinished = true"></payment-countdown>
    <div class="to-be-paid-wrapper">
      <div class="label">
        收款单位：<span>长沙泰和医院</span>
      </div>
      <div class="label">
        缴费类别：<span>{{ createOrderRequest.body }}</span>
      </div>
      <div class="label money-box">
        待缴金额：
        <span class="money">{{ psnCashpayAmt }}</span>
        <div v-if="createOrderRequest.orderType !== 6" class="detail-box">
          <div>
            <div>
              总计金额：{{makeMoneyStyle(createOrderRequest.totalFee)}}
            </div>
            <div>
              医保报销：{{makeMoneyStyle(createOrderRequest.fundpayAmt)}}
            </div>
            <div>
              个账支付：{{makeMoneyStyle(createOrderRequest.acctpayAmt)}}
            </div>
            <div>
              卡券优惠：{{makeMoneyStyle(createOrderRequest.couponAmt)}}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div style="margin: 0 12px">
      <van-coupon-cell
          v-if="createOrderRequest.orderType !== 6"
          :coupons="usableCoupons"
          :chosen-coupon="chosenCouponIndex"
          @click="showCouponList = true"
      />
      <van-popup
          v-model:show="showCouponList"
          round
          position="bottom"
          style="height: 90%; padding-top: 4px;"
      >
        <van-coupon-list
            :coupons="usableCoupons"
            :chosen-coupon="chosenCouponIndex"
            :disabled-coupons="unusableCoupons"
            @change="onCouponChange"
            :show-exchange-bar="false"
        />
      </van-popup>

      <div style="margin-top: 32px">
        <van-button block type="success" @click="weChatPay" :disabled="countdownFinished">微信支付</van-button>
      </div>
    </div>
  </window-size>
</template>

<script setup>
import store from "@/store";
import {computed, onMounted, ref} from "vue";
import {getMyCoupons} from "@/api/coupon";
import {createPayOrder, queryOrderState} from "@/api/wx-jsapi";
import router from "@/router";
import PaymentCountdown from '@/components/countdown-for-payment/index.vue'
import {getDeptPos} from "@/api/appointment";

const countdownFinished = ref(false)
const createOrderRequest = store.getters.getCreateOrderRequest

const psnCashpayAmt = computed(() => {
  let cashpayAmt = createOrderRequest.totalFee - createOrderRequest.fundpayAmt -
      createOrderRequest.acctpayAmt - createOrderRequest.couponAmt
  cashpayAmt = cashpayAmt < 0 ? 0 : cashpayAmt
  createOrderRequest.cashpayAmt = cashpayAmt.toFixed(2)
  return makeMoneyStyle(cashpayAmt)
})

const showCouponList = ref(false);
const chosenCouponIndex = ref(-1);
const usableCoupons = ref([])
const unusableCoupons = ref([])

const onCouponChange = (index) => {
  showCouponList.value = false;
  chosenCouponIndex.value = index;
  if (index === -1) {
    createOrderRequest.couponId = null
    createOrderRequest.couponAmt = 0
  } else {
    const coupon = usableCoupons.value[index]
    createOrderRequest.couponId = coupon.id
    if (coupon.availableCharge) {
      let targetChargeFee = getTargetChargeFee(coupon.availableCharge)
      let couponValue = coupon.value > targetChargeFee ? targetChargeFee : coupon.value
      createOrderRequest.couponAmt = couponValue / 100
    } else {
      createOrderRequest.couponAmt = coupon.value / 100
    }
  }
}

function getTargetChargeFee(code) {
  for (let i = 0; i < createOrderRequest.chargeList.length; i++) {
    let charge = createOrderRequest.chargeList[i]
    if (charge.itemCode === code) {
      return charge.itemTotalFee
    }
  }
  return 0
}

function makeMoneyStyle(m) {
  return '￥' + m.toFixed(2)
}

function weChatPay() {
  createPayOrder(createOrderRequest).then((order) => {
    createOrderRequest.tradeNo = order.tradeNo
    store.dispatch({
      type: 'storeYjReqNo',
      yjReqNo: null
    })
    if (Number(createOrderRequest.cashpayAmt) === 0) {
      queryOrderTradeState(order.tradeNo)
    } else {
      executePaymentAction(order)
    }
  })
}

function executePaymentAction(order) {
  WeixinJSBridge.invoke('getBrandWCPayRequest', {
    appId: order.appId,
    timeStamp: order.timeStamp,
    nonceStr: order.serialNo,
    package: order.prepayId,
    signType: order.signType,
    paySign: order.paySign,
    totalFee: order.cashpayAmt
  }, () => {
    queryOrderTradeState(order.tradeNo)
  })
}

function queryOrderTradeState(tradeNo) {
  queryOrderState(tradeNo).then((response) => {
    createOrderRequest.payTime = response
    store.dispatch({
      type: 'storeCreateOrderRequest',
      createOrderRequest
    }).then(() => {
      router.push('/paymentSuccess');
    })
  })
}

function getHisOrdNum() {
  switch (createOrderRequest.orderType) {
    case 1:
      return 'REGISTER'
    case 2:
      return createOrderRequest.hisOrdNum
    case 3:
      return 'INPATIENT_PREPAY'
    default:
      return 'UNKNOWN';
  }
}

onMounted(() => {
  if (createOrderRequest.orderType === 1) {
    getDeptPos(createOrderRequest.deptCode).then(res => {
      createOrderRequest.deptPos = res
    })
  }
  const chargeCodeList = []
  if (createOrderRequest.chargeList) {
    createOrderRequest.chargeList.forEach((item) => {
      chargeCodeList.push(item.itemCode)
    })
  }
  if (createOrderRequest.orderType !== 6) {
    const hisOrdNum = getHisOrdNum()
    getMyCoupons({hisOrdNum, chargeCodeList}).then(res => {
      usableCoupons.value = res.usableCoupons
      unusableCoupons.value = res.unusableCoupons
    });
  }
})
</script>

<style scoped>
.to-be-paid-wrapper {
  padding: 6px 12px 12px 12px;
  border-radius: 8px;
  box-shadow: #777777 1px 0 3px 0;
  margin: 12px;
  background-color: white;
}

.to-be-paid-wrapper > .label {
  font-size: 14px;
  color: #7a7a7a;
  padding: 16px 0;
  border-bottom: 1px solid #e1e1e1;
}

.label > span {
  color: #333333;
}

.to-be-paid-wrapper .money {
  margin-top: 8px;
  font-size: 26px;
  font-weight: bold;
  color: orangered;
}

.money-box {
  border: none!important;
  position: relative;
}

.detail-box{
  font-size: 10px;
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  display: flex;
  align-items: center;
}
</style>