<template>
  <cwg-page-wrapper :isHeaderFixed="true">
    <cwg-header class="wallet-header" :title="t('wallet1.title')"
      backgrounds="hhh" />
    <view class="page">

      <view class="wallet-banner">
        <view class="balance">
          <view class="balance-item">
            <view class="r l" @click="setModelValue1">
              <image :src="imageSrc(balance)" alt="" srcset="" />
              <text>{{ balance }}</text>
              <cwg-icon name="icon_dropdown" :size="24" />
            </view>
            <view class="r">
              <text>$ {{ currencyList[0]?.amount }}</text>
              <text class="decimal">{{ currencyList[0]?.decimal }}</text>
            </view>
          </view>
        </view>
      </view>

      <view class="wallet-actions">
        <view class="cwg-button two-btn">
          <u-button type="primary" block @click="goToVaultody">{{ t('pages.wallet.vaultody') }}</u-button>
          <u-button plain block class="prev-btn" @click="goToWithdraw">{{ t('pages.wallet.withdraw') }}</u-button>
        </view>
      </view>
      <view class="wallet-page">
        <view class="global-title">{{ t("global.title1") }}</view>
        <view class="global-con">
          <view class="global-con-l">
            <image src="/static/images/currency/USD.png" alt="" srcset="" />
            <view class="r">
              <view>USD</view>
            </view>
          </view>
          <cwg-icon name="icon_transfer" :size="23" color="#1a1a1a" />
          <view class="global-con-r" @click="setModelValue">
            <image :src="imageSrc(currency)" alt="" srcset="" />
            <view class="r">
              <view>{{ currency }}</view>
            </view>
            <cwg-icon name="icon_dropdown" :size="24" />
          </view>
        </view>
        <view class="cwg-button">
          <u-button type="primary" block @click="goToGlobalRemit">{{
            t("global.title1")
          }}</u-button>
        </view>
        <view class="trans-header">
          <view class="record-title">{{ t("global.title") }} </view>

          <view class="all" @click="goRechargeRecord">{{
            t("card.Status.t22")
          }}</view>

        </view>


        <view class="transaction-list">
          <template v-if="globalOrdersList.length > 0">
            <view v-for="item in globalOrdersList" :key="item.id" class="transaction-item"
              @click="goToDeductionDetail(item)">
              <view class="transaction-left">
                <view class="transaction-icon">
                  <text class="icon-text"><cwg-icon name="icon_transfer" :size="23" color="#1a1a1a" /></text>
                </view>
                <view class="transaction-info">
                  <text class="transaction-status">{{ item.merchantOrderNo }}</text>
                  <text class="transaction-time">{{ item.addTime }}</text>
                </view>
              </view>

              <view class="transaction-right">
                <text class="transaction-amount">{{ item.deductionAmount }} {{ item.sendCurrency }}</text>
              </view>
            </view>
          </template>
          <cwg-empty-state v-if="globalOrdersList.length == 0" />
        </view>
      </view>
      <cwg-currency-select v-model="modelValue" :show-search="true" :options="globalCurrenciesDropdown"
        @select="changeSelect" :placeholder="t('common.country')" />
      <cwg-currency-select v-model="modelValue1" :show-search="true" :options="globalCurrenciesDropdown"
        @select="changeSelect1" />
    </view>
  </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from "vue";
import { showToast } from "@/utils/toast";
import { onLoad } from '@dcloudio/uni-app'
import useRouter from "@/hooks/useRouter";
import { useI18n } from "vue-i18n";
import { ucardApi } from "@/api/ucard";
import _ from "lodash";
import useCardStore from "@/stores/use-card-store";
const cardStore = useCardStore();
const { t } = useI18n();
const router = useRouter();
onLoad((options) => {
  // id.value = options.id
  // type.value = options.type
})
const currency = ref("EUR");
const balance = ref("USD");
const modelValue = ref(false);
const modelValue1 = ref(false);
const currencyList = ref([]);
const allAmount = ref(0);
async function getBalance() {
  try {
    const res = await ucardApi.walletBalance();
    const n = Number.parseFloat(res.data.balance).toFixed(2);
    const { amount, decimal } = splitNumber(n);

    allAmount.value = n;
    currencyList.value.push({
      name: "USD",
      amount,
      decimal,
    });
  } catch (error) { }
}
async function getGlobalFieldParams() {
  try {
    const res = await ucardApi.getGlobalFieldParams();
    const sorted = res.data
      .sort((a, b) => {
        return (a.sorting || 0) - (b.sorting || 0);
      }).map((item) => {
        return { fieldUserType: item.fieldUserType, fieldName: item.fieldName, fieldType: item.fieldType }
      });
    cardStore.saveGlobalFieldParams(sorted);
  } catch (error) { }
}
function imageSrc(currency: string) {
  return `/static/images/currency/${currency}.png`;
}
const goToDeductionDetail = (record: RecordItem) => {
  console.log(record, 1212);
  cardStore.saveOrderDetail(record);
  router.push({
    path: '/pages/wallet/global-detail',
    query: { id: record.id }
  });
};

function splitNumber(n) {
  if (
    n === undefined ||
    n === null ||
    n === 0 ||
    (typeof n !== "number" && typeof n !== "string") ||
    (typeof n === "string" && !/^\d+(\.\d+)?$/.test(n))
  ) {
    return { amount: 0, decimal: "" };
  }
  const str = n.toString();
  if (!str.includes(".")) {
    return { amount: str, decimal: "" };
  }
  const [int, dec] = str.split(".");
  return {
    amount: `${int}.`,
    decimal: dec || "",
  };
}

function setModelValue() {
  modelValue.value = true;
}
function setModelValue1() {
  return;
  //   modelValue1.value = true

}
function goRechargeRecord() {
  router.push(`/pages/wallet/global-list`);
}
function goToGlobalRemit() {
  router.push(
    `/pages/wallet/global-order?currency=${currency.value}`
  );
}
function goToVaultody() {
  router.push(`/pages/wallet/vaultody`);
}
function goToWithdraw() {
  router.push(`/pages/wallet/withdraw?allAmount=${allAmount.value}`);
}
function changeSelect(e) {
  currency.value = e.value;
}
function changeSelect1(e) {
  balance.value = e.value;
}
const globalCurrenciesDropdown = ref([]);
const getGlobalCurrenciesDropdown = async () => {
  const res = await ucardApi.globalCurrenciesDropdown({ code: "", status: 'online' });
  if (res.code === 200 || res.code === 0) {
    globalCurrenciesDropdown.value = res.data.map((i) => {
      return { currency: i.payoutCurrency, text: i.country, value: i.payoutCurrency };
    }) || [];
    const data = _.cloneDeep(res.data);
    cardStore.saveCurrencyList(data)
  }
};
const globalOrdersList = ref<TransferInfo[]>([]);
async function getGlobalOrdersList() {
  try {
    const res = await ucardApi.globalOrdersList({ page: { current: 1, row: 5 } });
    if (res.code === 200) {
      globalOrdersList.value = res.data;
    } else {
      globalOrdersList.value = [];
    }
  } catch (error) {
    showToast(t("common.error"));
  }
}
function goToTransferDetail(id: string) {
  router.push(`/transfer/detail?id=${id}`);
}
onMounted(() => {
  getGlobalCurrenciesDropdown()
  getGlobalOrdersList()
  getBalance();
  getGlobalFieldParams()
});
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.page-wrapper {
  padding-left: 0 !important;
  padding-right: 0 !important;
  border: 0 !important;
}

.page {
  box-sizing: border-box;
  background: var(--main-bg);
}

.wallet-page {
  padding: 0 px2rpx(24);
  box-sizing: border-box;
}

.wallet-header {
  // position: relative;
  // background: linear-gradient(90deg, #ea002a 0%, #eb4e6b 100%);
  // z-index: 1113;
}

.banner-title {
  color: #fff;
  font-family: Roboto;
  font-size: px2rpx(22);
  font-style: normal;
  font-weight: 600;
  line-height: px2rpx(28);
  padding: px2rpx(12) 0 px2rpx(31) 0;
}

.wallet-banner {
  background: linear-gradient(90deg, #ea002a 0%, #eb4e6b 100%);
  margin-bottom: px2rpx(20);
  padding: 0 px2rpx(31) px2rpx(62) px2rpx(31);
  color: #fff;

  .balance {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
  }

  .balance-item {
    width: 100%;
    display: flex;
    padding: px2rpx(16) px2rpx(24);
    justify-content: center;
    align-items: center;
    gap: px2rpx(31);
    border-radius: px2rpx(8);
    border: 1px solid var(--Netural-color-content-color-stoke, #f4f4f4);
    background: #fff;
    color: var(--white);
    flex-direction: column;

    .r {
      display: flex;
      justify-content: center;
      align-items: flex-end;
    }

    .l {
      align-items: center;
    }

    text {
      color: #000;
      font-family: Roboto;
      font-size: px2rpx(44);
      font-style: normal;
      font-weight: 600;
      text-align: left;
    }

    .decimal {
      color: #1a1a1a;
      font-family: Roboto;
      font-size: px2rpx(14);
      font-style: normal;
      font-weight: 600;
      letter-spacing: px2rpx(0.07);
    }

    .l {
      text {
        color: #474747;
        font-size: px2rpx(31);
        line-height: px2rpx(44);
      }
    }

    image {
      width: px2rpx(28);
      height: px2rpx(28);
      margin-right: px2rpx(12);
      display: inline-block;
    }
  }
}

.global-title {
  margin: px2rpx(44) 0 px2rpx(36) 0;
  color: #000;
  font-family: Roboto;
  font-size: px2rpx(22);
  font-style: normal;
  font-weight: 600;
  line-height: px2rpx(28);
}

.global-con {
  display: flex;
  width: 100%;
  margin: px2rpx(44) 0;
  align-items: center;
  gap: px2rpx(12);
  color: #1a1a1a;

  .global-con-l,
  .global-con-r {
    display: flex;
    flex: 1;
    padding: px2rpx(12) px2rpx(8);
    align-items: center;
    gap: px2rpx(6);
    border-radius: px2rpx(12);
    box-shadow: 0px px2rpx(10) px2rpx(30) 0px rgba(5, 0, 1, 0.1);
    color: var(--white);

    view {
      color: #000;
      font-family: Roboto;
      font-size: px2rpx(24);
      font-style: normal;
      font-weight: 600;
      line-height: px2rpx(44);
    }

    image {
      width: px2rpx(36);
      height: px2rpx(36);
      border: 1px solid #f4f4f4;
      border-radius: 50%;
    }
  }
}

.trans-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.record-title {
  margin: px2rpx(44) 0 px2rpx(44) 0;
  color: #000;
  font-family: Roboto;
  font-size: px2rpx(22);
  font-style: normal;
  font-weight: 600;
  line-height: px2rpx(28);
}

.transaction-list {
  display: flex;
  flex-direction: column;

  .transaction-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: px2rpx(16) 0;
    border-bottom: 1px solid #f3f4f6;
  }

  .transaction-item:last-child {
    border-bottom: none;
  }

  .transaction-left {
    display: flex;
    align-items: center;
    gap: px2rpx(12);
  }

  .transaction-icon {
    width: px2rpx(40);
    height: px2rpx(40);
    background-color: #f9fafb;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .icon-text {
    font-size: px2rpx(20);
    color: #6b7280;
  }

  .transaction-info {
    display: flex;
    flex-direction: column;
    gap: px2rpx(4);
  }

  .transaction-status {
    font-size: px2rpx(14);
    color: #111827;
  }

  .transaction-time {
    font-size: px2rpx(12);
    color: #9ca3af;
  }

  .transaction-right {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
  }

  .transaction-amount {
    font-size: px2rpx(16);
    font-weight: 600;
    color: #111827;
  }

  .transaction-amount.negative {
    color: #ef4444;
  }
}

.wallet-actions {
  padding: px2rpx(16) px2rpx(24);
}

.wallet-actions .two-btn {
  display: flex;
  gap: px2rpx(16);
}

.wallet-actions .prev-btn {
  border: 1px solid var(--main-yellow) !important;
  color: #fff !important;
  background: transparent;
}
</style>
