<template>
  <cwg-page-wrapper>
    <cwg-header :showBack="true" :title="title[type]">
      <view v-if="type == 2" @click="goRechargeRecord">
        <cwg-icon name="icon_history" :size="24" color="#000" />
      </view>
    </cwg-header>

    <view class="page page-shadow">
      <u-form ref="formRef" class="kyc-form">
        <template v-if="type == '1'">
          <cwg-input v-model:value="infoForm.cardNumber1" fkey="cardNumber1" :required="true"
            :label="`${t('card.Form.f24')}:`" :rules="rules.cardNumber1" @change="handleChange" />
          <cwg-input v-model:value="infoForm.activeCode" fkey="activeCode" :required="true"
            :label="`${t('card.Form.f26')}:`" :rules="rules.activeCode" @change="handleChange" />
          <cwg-input v-model:value="infoForm.pin" fkey="pin" :required="true" :maxlength="6" :label="t('card.Info.s26')"
            :rules="rules.pin" @change="handleChange" />
          <cwg-input v-model:value="infoForm.password" fkey="password" :required="true" :maxlength="6"
            :label="`${t('card.Btn.Confirm')}:`" :rules="rules.password" @change="handleChange" />
          <view class="pwd">
            <view calss="lis" v-t="'card.vaildate.v32'" :class="{ fit: rule1 }"></view>
            <view calss="lis" v-t="'card.vaildate.v33'" :class="{ fit: rule2 }"></view>
          </view>
        </template>
        <template v-if="type == '2'">
          <cwg-input v-model:value="infoForm.cardNumber1" fkey="cardNumber1" :required="true"
            :label="`${t('card.Form.f24')}:`" :rules="rules.cardNumber1" @change="handleChange" />
          <cwg-input v-model:value="infoForm.amount" fkey="amount" type="number" :label="`${t('card.Form.f28')}:`"
            :required="true" :min="rechargeMinQuota" :max="rechargeMaxQuota" :placeholder="t('card.vaildate.v26')"
            @change="handleChange">
          </cwg-input>
          <view class="balance-info">
            <text class="balance-key">{{ t("card.Form.f56") }}</text>
            <text class="balance-value">{{ userBalance }} USD</text>
            <view class="all-btn" @click="allBalance">{{
              t("card.Form.f57")
              }}</view>
          </view>
          <view class="balance-info">
            <text class="balance-key">{{ t("card.Form.f58") }}</text>
            <text class="balance-value">{{ exchangeRate }}%</text>
            <text></text>
          </view>
          <view class="balance-info">
            <text class="balance-key">{{ t("card.Form.f59") }}</text>
            <text class="balance-value">{{ fee }}</text>
            <text></text>
          </view>
        </template>
        <template v-if="type == '3'">
          <cwg-input v-model:value="infoForm.cardNumber1" fkey="cardNumber1" :required="true"
            :label="`${t('card.Form.f24')}:`" :rules="rules.cardNumber1" @change="handleChange" />
          <cwg-input v-model:value="infoForm.pin" fkey="pin" :required="true" :label="t('card.Info.s26')" :maxlength="6"
            :rules="rules.pin" @change="handleChange" />
          <cwg-input v-model:value="infoForm.password" fkey="password" :required="true" :maxlength="6"
            :label="`${t('card.Btn.Confirm')}:`" :rules="rules.password" @change="handleChange" />

          <view class="pwd">
            <view calss="lis" v-t="'card.vaildate.v32'" :class="{ fit: rule1 }"></view>
            <view calss="lis" v-t="'card.vaildate.v33'" :class="{ fit: rule2 }"></view>
          </view>
        </template>
        <template v-if="type == '4' || type == '5'">
          <cwg-input v-model:value="infoForm.cardNumber1" fkey="cardNumber1" :required="true"
            :label="`${t('card.Form.f24')}:`" :rules="rules.cardNumber1" @change="handleChange" />
          <cwg-input v-model:value="infoForm.clientRemark" fkey="clientRemark" :label="`${t('card.Form.f27')}:`"
            @change="handleChange" />
        </template>

        <view v-if="infoForm.authStatus != 1" class="fixed-btn">
          <view class="cwg-button">
            <u-button type="primary" block @click="infoSubmit">{{
              t("card.Btn.Submit")
              }}</u-button>
          </view>
        </view>
      </u-form>
    </view>
  </cwg-page-wrapper>
</template>

<script setup lang="ts">

import { ref, onMounted, watch, computed } from "vue";
import { showToast } from "@/utils/toast";
import { useI18n } from "vue-i18n";
import useRouter from "@/hooks/useRouter";
import { onLoad } from '@dcloudio/uni-app'
import { ucardApi } from "@/api/ucard";
import config from "@/config";
const { t } = useI18n();
const router = useRouter();
const form = ref({});
const formRef = ref();
const infoForm = ref({
  password: undefined,
  cardNumber1: undefined,
  cardNo: undefined,
  activeCode: undefined,
  pin: undefined,
  amount: undefined,
  clientRemark: undefined,
});
const title = ref({
  1: t('card.Btn.b1'),
  2: t('card.Btn.b3'),
  3: t('card.Btn.b4'),
  4: t('card.Btn.b5'),
  5: t('card.Btn.b6')
})
const type = ref()
const id = ref()
onLoad((options) => {
  id.value = options.id
  type.value = options.type
})
// 动态限制
const exchangeRate = ref(0);
const rechargeMinQuota = ref(0);
const rechargeMaxQuota = ref(0);
const rechargeFixedFee = ref(0);
const userBalance = ref(0);
const pictLoading = ref(false);
const rules = {
  pin: [
    { required: true, message: t("card.vaildate.v23") },
    { pattern: config.Pattern.Pin, message: t("card.vaildate.v23") },
  ],
  password: [
    { required: true, message: t("card.vaildate.v31") },
    { pattern: config.Pattern.Pin, message: t("card.vaildate.v31") },
  ],
  cardNumber1: [
    {
      required: true,
      message: t("card.vaildate.v22"),
      trigger: "blur",
    },
  ],
  amount: [
    {
      required: true,
      message: t("card.vaildate.v26"),
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => validateAmount(value, callback),
      trigger: "blur",
    },
  ],
  activeCode: [
    {
      required: true,
      message: t("card.vaildate.v24"),
      trigger: "blur",
    },
  ],
};

const formData = ref<typeof infoForm.value>({ id } as any);
const headerTitleMap: Record<number, string> = {
  1: "card.tab10",
  2: "card.tab11",
  3: "card.tab12",
  4: "card.tab13",
  5: "card.tab14",
};

// 根据 type 自动取标题
const maxRecharge = computed(() => {
  const balance = Number(userBalance.value) || 0;
  const rate = Number(exchangeRate.value) / 100;
  if (balance <= 0) return 0;
  return Math.floor((balance / (1 + rate)) * 100) / 100;
});
const fee = computed(() => {
  if (!formData.value.amount) {
    return 0;
  }
  if (rechargeFixedFee.value) {
    return rechargeFixedFee.value;
  }
  const amount = Math.ceil(formData.value.amount);
  return ((amount * exchangeRate.value) / 100).toFixed(2);
});
function goRechargeRecord() {
  router.push(`/pages/recharge-record/list?cardNo=${formData.value?.cardNo}`);
}
// 根据 type 自动取标题
const headerTitle = computed(() => {
  const key = Number(type.value);
  const i18nKey = headerTitleMap[key];
  return i18nKey ? t(i18nKey) : t("common.unknown");
});
const showBack = computed(() => {
  return ["/", "/cards", "/finance", "/mine", "/login"].includes(route.path);
});
// 计算属性 rule1
const rule1 = computed(() => {
  if (!formData.value.pin) return false;
  return /^(\d)\d{5}$/.test(formData.value.pin);
});

// 计算属性 rule2
const rule2 = computed(() => {
  if (!formData.value.pin) return false;
  return config.Pattern.Pin.test(formData.value.pin);
});
async function infoSubmit() {
  if (formData.value.cardNumber1 != infoForm.value.cardNumber) {
    showToast(t("card.vaildate.v22"));
    return;
  }
  try {
    switch (type.value) {
      case "1":
        await formRef.value?.validate(["cardNumber1", "pin", "activeCode"]);
        ucardActivate();
        break;
      case "2":
        await formRef.value?.validate(["cardNumber1", "amount"]);
        ucardRecharge();
        break;
      case "3":
        await formRef.value?.validate(["cardNumber1", "pin"]);
        ucardResetPassword();
        break;
      case "4":
        await formRef.value?.validate(["cardNumber1"]);
        ucardFreeze();
        break;
      case "5":
        await formRef.value?.validate(["cardNumber1"]);
        ucardUnfreeze();
        break;
    }
  } catch (error) { }
}
function backActivity() {
  setTimeout(() => {
    router.back();
  }, 3000);
}
async function ucardActivate() {
  if (formData.value.pin != formData.value.password) {
    showToast(t("card.Msg.m11"));
    return;
  }
  const res = await ucardApi.ucardActivate(formData.value);
  if (res.code == 200) {
    showToast(t("card.Msg.m3"));
    backActivity();
  } else {
    showToast(res.msg);
  }
}
async function ucardResetPassword() {
  if (formData.value.pin != formData.value.password) {
    showToast(t("card.Msg.m11"));
    return;
  }
  const res = await ucardApi.ucardResetPassword(formData.value);
  if (res.code == 200) {
    showToast(t("card.Msg.m6"));
    backActivity();
  } else {
    showToast(res.msg);
  }
}
async function ucardFreeze() {
  const res = await ucardApi.ucardFreeze(formData.value);
  if (res.code == 200) {
    showToast(t("card.Msg.m4"));
    backActivity();
  } else {
    showToast(res.msg);
  }
}
async function ucardUnfreeze() {
  const res = await ucardApi.ucardUnfreeze(formData.value);
  if (res.code == 200) {
    showToast(t("card.Msg.m5"));
    backActivity();
  } else {
    showToast(res.msg);
  }
}
async function getCardInfo() {
  try {
    if (!id) return;
    const res = await ucardApi.getCardInfo({ id: id.value });
    infoForm.value = res.data;
    formData.value = res.data;
    exchangeRate.value = res.data.rechargeFeeRate;
    rechargeMaxQuota.value = res.data.rechargeMaxQuota;
    rechargeMinQuota.value = res.data.rechargeMinQuota;
    rechargeFixedFee.value = res.data.rechargeFixedFee;
  } catch (error) {
    console.log(error);
  }
}

// 一键填充最大金额
function allBalance() {
  infoForm.value.amount = maxRecharge.value;
}

// 金额验证函数（配合 Vant <Field /> 的 rules）
function validateAmount(value: string | number) {
  const num = Number(value);
  if (!num || num <= 0) {
    return t("card.vaildate.v34"); // 请输入有效金额
  } else if (maxRecharge.value === 0) {
    return `${t("card.Form.f56")} 0 USD`;
  } else if (num > maxRecharge.value) {
    return `${t("card.vaildate.v35")} ${maxRecharge.value} USD`;
  } else if (num < rechargeMinQuota.value) {
    return `${t("card.vaildate.v36")} ${rechargeMinQuota.value} USD`;
  } else if (num >= rechargeMaxQuota.value) {
    return `${t("card.vaildate.v37")} ${rechargeMaxQuota.value} USD`;
  }
  return true;
}

// 获取钱包余额
async function walletBalance() {
  try {
    const res = await ucardApi.walletBalance();
    if (res.code === 200) {
      userBalance.value = res.data.balance || 0;
    } else {
      showToast(res.msg);
      userBalance.value = 0;
    }
  } catch (err) {
    userBalance.value = 0;
  }
}

// 银行卡充值
async function ucardRecharge() {
  const amount = Number(formData.value.amount);
  const cardNo = formData.value.cardNo;

  if (validateAmount(amount) !== true) {
    showToast(validateAmount(amount));
    return;
  }

  pictLoading.value = true;
  try {
    const res = await ucardApi.ucardRecharge({ amount, cardNo });
    if (res.code === 200) {
      showToast(t("card.Msg.m2"));
      setTimeout(() => {
        router.push(`/cards`);
      }, 1000);
    } else {
      showToast(res.msg);
    }
  } catch (err) {
    console.log(err);
  } finally {
    pictLoading.value = false;
  }
}
onMounted(() => {
  getCardInfo();

  if (type.value == "2") {
    walletBalance();
  }
});

function handleChange(value: any) {
  formData.value = { ...formData.value, [value.key]: value.value };
}
</script>

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

.pointer-none {
  pointer-events: none;
}

.f {
  display: flex;
  align-items: flex-end;
  gap: px2rpx(12);

  .l {
    flex: 1;
  }

  .r {
    width: px2rpx(273);
  }
}

.pwd {
  line-height: px2rpx(20);

  li {
    list-style-type: disc;
    line-height: 1.2;
    margin: px2rpx(4) 0 px2rpx(4) px2rpx(20);
    color: #c0c4cc;
  }

  .fit {
    color: #009deb;
  }
}

.balance-info {
  width: 100%;
  color: #bdbdbd;
  font-size: px2rpx(14);
  margin-bottom: px2rpx(44);
  display: flex;
  align-items: center;
  /* justify-content: space-between; */
}

.balance-value {
  width: px2rpx(140);
  color: var(--white);
  font-weight: bold;
  margin: 0 px2rpx(8);
}

.balance-key {
  color: #8e8a8a;
  width: px2rpx(130);
}

.all-btn {
  min-width: px2rpx(30);
  display: flex;
  padding: px2rpx(4) px2rpx(12);
  justify-content: center;
  align-items: center;
  gap: px2rpx(10);
  border-radius: px2rpx(35);
  border: 1px solid #ea002a;
  color: var(--Brand-color, #ea002a);
  font-family: Roboto;
  font-size: px2rpx(14);
  font-style: normal;
  font-weight: 600;
  line-height: px2rpx(20);
  letter-spacing: px2rpx(0.07);
}
</style>
