<template>
  <div class="first" v-loading="loading">
    <div class="payment-view">
      <div>
        <div class="info-wrap">
          <el-input
              v-model="amount"
              style="width: 100%"
              placeholder="Please input"
              class="input-with-select"
          >
            <template #append>
              <el-select v-model="currency" placeholder="Select" style="width: 115px">
                <el-option label="CNY" value="CNY"/>
                <el-option label="USD" value="USD"/>
                <el-option label="USDM" value="USDM"/>
              </el-select>
            </template>
          </el-input>
          <el-col style="text-align: right; margin-top: 12px" :span="24" v-loading="ARS_amount_loading">
            Exchange Rate: 1.00{{currency}} = <span style="font-size: 12px">{{ARS_amount}}ARS</span>
          </el-col>
          <el-col style="text-align: right; margin-top: 12px">
            <el-button type="primary" @click="createOrderFn">Submit</el-button>
          </el-col>
        </div>
        <br>
        <div v-if="order.payUrl">
          <div class="info-wrap">
            <div class="trans-no">
                <span style="vertical-align: inherit;">
                    <span style="vertical-align: inherit;">{{ order.orderNo }}</span>
                </span>
            </div>
            <div class="van-divider"></div>
            <div class="info-box">
              <div class="key">
                <span style="vertical-align: inherit;">
                  <span style="vertical-align: inherit;">Valor</span>
                </span>
              </div>
              <div class="val">
                <span style="vertical-align: inherit;">
                  <span style="vertical-align: inherit;">{{order.amount}} ARS</span>
                </span>
              </div>
            </div>
          </div>
          <div class="qrcode-wrap">
            <p class="tips">
              <span style="vertical-align: inherit;">
                <span style="vertical-align: inherit;">Por favor, use el pago flash en la nube para escanear
                  el pago.
                </span>
              </span>
            </p>
            <p class="tips">
              <span style="vertical-align: inherit;">
                <span style="vertical-align: inherit;">Código de pago único, no repita el pago, de lo
                  contrario causará una entrada Anormal.</span>
              </span>
            </p>
            <div class="qrcode-box">
              <div id="qrCodeContent">
                <img :src="order.payUrl" id="vaImg" class="vaImg" style="display: inline-block;">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed, watch} from 'vue'
import {createOrder, getOrder, getConversionFactors} from '@/api'
import {useRoute} from 'vue-router';
import _ from 'lodash'
import md5 from "md5";
import {getRateData} from '@/utils/index.js'

import dayjs from "dayjs";

function getNewOutOrderNo() {
  return "PVSTEST" + dayjs().format("YYYYMMDDHHmmss");
}

const loading = ref(false);
const route = useRoute()
const orderNo = route.query.t || ''
const mchId = route.query.mchId || ''
const amount = ref(0)
const ARS_amount = ref(0)
const currency = ref('');
const  ARS_amount_loading = ref(false);
import {ElMessage} from 'element-plus';


const basePre = 'data:image/png;base64,';
const order = ref({
  orderNo: '',
  amount: 0,
  payUrl: '',
  returnUrl: '',
  status: 0
})


const getOrderInfo = async function () {
  if(!orderNo) return
  const data = await getOrder({
    orderNo
  });
  console.log(data)
  order.value.orderNo = data.orderNo;
  order.value.amount = data.amount;
  order.value.returnUrl = data.returnUrl;
  order.value.status = data.status;
  order.value.payUrl = basePre + data.payUrl;
  if (+order.value.status === 0) {
    return;
  }
  if (+order.value.status === 1) {
    ElMessage({message: 'El pedido ha sido pagado y saltará a la página del comerciante', type: 'success'})
  }
  if (+order.value.status === 2 || +order.status === 3) {
    ElMessage({
      message: 'El pedido ha expirado, por favor regrese a la página del comerciante para reiniciar',
      type: 'warning'
    })
  }
  setTimeout(() => {
    window.location = order.value.returnUrl
  }, 1000)
}

function convertStringToNumberWithTwoDecimals(input) {
  // 将输入转换为浮点数
  let number = parseFloat(input);
  
  // 检查转换是否成功，如果失败则默认为0
  if (isNaN(number)) {
    number = 0;
  }
  
  // 将数字格式化为带两位小数的字符串，然后再转换为数字类型
  return parseFloat(number.toFixed(2));
}


const getAmount = async () => {
  // if(currency.value === 'CNY')  {
  //   return amount.value * 144.38
  // }
  const  res = await getConversionFactors({
    currency: currency.value,
    amount: Number(amount.value).toFixed(2)
  })
  return res.amount
}

watch(currency, async () => {
  // if(currency.value === 'CNY')  return
  ARS_amount_loading.value = true
  const  res = await getConversionFactors({
    currency: currency.value,
    amount: '1.00'
  })
  ARS_amount.value = res.amount
  ARS_amount_loading.value = false
})

const createOrderFn = async () => {
  loading.value = true
  if(_.isNumber(amount.value) && amount.value < 1) {
    loading.value = false
    ElMessage({message: 'Please enter a valid amount', type: 'warning'})
    return
  }
  const formDate = {
    mchId: "TEST",
    outOrderNo: getNewOutOrderNo(),
    notifyUrl: "http://157.175.73.225/api/admin/dj/open/notifyTest",
    returnUrl: "https://www.baidu.com",
    amount: convertStringToNumberWithTwoDecimals(await getAmount()),
    payType: "QRCODE",
    userIp: "127.0.0.1",
    userId: "test",
    currency: 'ARS',
  }
  if(formDate.amount > 99999999) {
    loading.value = false
    ElMessage({message: 'Your amount is too large to create a payment order', type: 'warning'})
    return
  }
  // return
  const signStr = md5(signSort(formDate) + `&key=${key.value}`)
  try {
    const res = await createOrder({
      ...formDate,
      sign: signStr
    });
    order.value = {
      ...res,
      amount: formDate.amount,
      payUrl: `data:image/png;base64, ${res.hasOwnProperty('qrImage') ? res.qrImage :  res?.payUrl}`
    }
  } catch (err) {
    console.log(192, err);
    // data.value = JSON.stringify(err);
  } finally {
    loading.value = false
  }
}
const key = ref("32394ae8b550485c53326f10764f8492");

const defaultForm = {
  mchId: "TEST",
  outOrderNo: getNewOutOrderNo(),
  notifyUrl: "http://157.175.73.225/api/admin/dj/open/notifyTest",
  returnUrl: "https://www.baidu.com",
  amount: 100,
  payType: "",
  userIp: "127.0.0.1",
  userId: "test",
  currency: 'USD'
};

const sign = computed(() => {
  return md5(signSort(form.value) + `&key=${key.value}`);
});

function signSort(args) {
  var keys = Object.keys(args);
  keys = keys.sort();
  var newArgs = {};
  keys.forEach(function (key) {
    newArgs[key] = args[key];
  });
  
  var string = "";
  for (var k in newArgs) {
    string += "&" + k + "=" + newArgs[k];
  }
  string = string.substr(1);
  return string;
}

// http://localhost:8001/admin/dj/open/pvs/conversion-factors?currency=USDM&amount=100.00


onMounted(() => {
  getOrderInfo()
  currency.value = "CNY"
})
</script>

<style scoped lang="less">
.payment-view {
  max-width: 550px;
  padding: 30px;
  margin: 0 auto;
}

.info-wrap {
  line-height: 24px;
  color: #969799;
  border: 1px solid #dde7f0;
  border-radius: 8px;
  padding: 15px 15px;
}

.trans-no {
  text-align: right;
  color: #999;
  font-size: 12px;
}

.van-divider {
  border-top: 1px dashed #dde7f0;
  border-color: #dde7f0;
  margin: 10px 0;
}

.info-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.key {
  font-size: 14px;
  color: #222;
}

.val {
  font-size: 32px;
  font-weight: 700;
  color: #222;
}

.qrcode-wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 1px solid #dde7f0;
  border-radius: 8px;
  padding: 15px 15px;
  margin-top: 15px;
}

.tips {
  text-align: center;
  font-size: 14px;
  font-weight: 700;
  color: #111;
  margin-top: 0;
}

.qrcode-box {
  position: relative;
  width: 244px;
  height: 244px;
  margin-top: 15px;
}

.vaImg {
  width: 240px;
  height: 240px;
  overflow: hidden;
  margin: 0;
}
</style>
