<template>
  <div class="deposito">
    <div class="bank-box">
      <p class="tips">Formas de Pagamentos</p>
      <div class="bank" :style="{ gridTemplateColumns: `repeat(${payList.length},1fr)` }">
        <div class="bank-item" :class="currentBankIndex == index ? 'active' : ''" v-for="(item, index) in payList"
          :key="index" @click="checkBank(index)">
          <div class="top">
            <h-img type="local" class="icon" src="deposit/pix2.png" />
            <span>({{ item.txt }})</span>
          </div>
          <div class="bottom">
            {{ item.amountLimitArea[0] / 10000 }} ~
            {{ item.amountLimitArea[1] / 10000 }} BRL
          </div>
        </div>
      </div>
    </div>
    <div class="my-field" v-if="isNeedAccount">
      <div class="field" style="border-radius:0.1rem;margin-bottom: 10px;">
        <p style="font-size: 16px; width: 50px;margin-left:10px;">Nome：</p>
        <van-field v-model="holder" :placeholder="`Nome do pagador`" type="text" />
      </div>
      <div class="field" style="border-radius:0.1rem;margin-bottom: 10px;">
        <p style="font-size: 16px; width: 50px;margin-left:10px;">CPF：</p>
        <van-field v-model="cpf" :maxlength="16" :placeholder="`CPF ou CNPJ (CPF ou CNPJ do pagador)`" type="digit" />
      </div>
    </div>
    <div class="field">
      <p>Quantia(BRL)</p>
      <van-field v-model="amount" :maxlength="16" :placeholder="`Insira BRL${(payLimit[0] / 10000) | 0} ~ ${(payLimit[1] / 10000) | 0
        }`" type="digit" />
      <div class="dia-box" v-if="amount && activeItemObj.length > 1 && checked === 1">
        {{ `+${activeItemObj[1].num / 10000} ${propNames(activeItemObj[1].propId)}` }}
      </div>
    </div>
    <div class="amount-box">
      <div class="ampuntList">
        <div class="amount-item" :class="currentAmountIndex == index ? 'active' : ''" v-for="(item, index) in amounts"
          :key="index" @click="checkAmount(index)">
          <h-img v-if="item.isHot" src="base/hot.png" class="hot" />
          <div><i>R$</i> {{ item.price / 10000 }}</div>
          <p v-if="item.propsList.length > 1 && checked === 1">
            <span style="color: #f3e615">
              +{{ item.propsList[1].num / 10000 }}
            </span>
            {{ propNames(item.propsList[1].propId) }}
          </p>
        </div>
      </div>
    </div>
    <div class="checked-box">
      <van-radio-group v-model="checked">
        <van-radio checked-color="#7CEC49" :name="1">Recompensa por participar do evento</van-radio>
        <van-radio checked-color="#7CEC49" :name="2">Sem recompensa por não participar do evento</van-radio>
      </van-radio-group>
    </div>
    <van-button v-if="isNeedAccount" size="large" color="#2F6368" :disabled="!amount || (holder === '' || cpf === '')" @click="submit">
      Depositar Agora
    </van-button>
    <van-button v-else size="large" color="#2F6368" :disabled="!amount" @click="submit">
      Depositar Agora
    </van-button>

    <div class="bt-tips">
      <p v-if="showOne">
        A primeira vez que os usuários de depósitos receberão um bónus de
        <span>50% -150%</span>
      </p>
      <p>
        1.Se você perder dinheiro real ao jogar o jogo, a 18n.com oferece um
        <span>Cashback em dinheiro de 25% toda semana</span>
      </p>
      <p>
        2.Os diamantes dados durante a recarga podem ser trocados por dinheiro
        após participar das apostas do jogo.
      </p>
      <p>
        3.Horário de solicitação do cashback: De segunda-feira da próxima semana
        06:00 a sexta-feira 23:59, expirará se nao for resgatado.
      </p>
    </div>
    <!-- iframe 跳转 -->
    <div v-if="showDeposit" class="box">
      <div class="close">
        <img :src="getAssets('base/close.png')" @click.stop="closeIframe" width="25" />
      </div>
      <iframe allow="fullscreen" id="iframe" :src="iframeRefSrc"
        style="width: 100%; height: 88vh; background-color: rgb(255, 255, 255)" frameborder="0">
      </iframe>
    </div>
    <van-overlay :z-index="999" :show="codeValue" :lock-scroll="false">
      <div class="qrCode-box">
        <div class="close">
          <img :src="getAssets('base/close.png')" @click.stop="closeCodeMode" width="25" />
        </div>
        <div class="content">
          <h-img type="local" style="width: 3rem" src="deposit/pix2.png" />
          <p>
            Por favor abra o seu aplicativo de pagamento e escaneie o código QR
            abaixo para pagar ou copie o código Pix abaixo e cole em seu app de
            pagamento para finalizar a compra.
          </p>
          <div class="amount">Total R$ {{ depostAmount }}</div>
          <div class="codeImg">
            <qrcode-vue class="code" :value="qrCode"></qrcode-vue>
          </div>
          <van-button color="#56B83F" style="
              margin-top: 0.8rem;
              width: 5rem;
              font-size: 0.4rem;
              font-weight: 600;
            " size="normal" @click="clipboard(qrCode)">
            <div style="display: flex; align-items: center">
              <span>Copiar Código Pix</span>
              <h-img style="margin-left: 0.2rem" width=".5rem" type="local" src="base/fuzhib.png"></h-img>
            </div>
          </van-button>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script setup lang="ts">
import QrcodeVue from "qrcode.vue";
import { ref, reactive, computed, onMounted, inject, watch } from "vue";
import { formatDigit, jumpOhterLink, getAssets, clipboard } from "@/utils";
import { useUserStore } from "@/stores/modules/user";
import socketApi from "@/socket/socketApi";
import { closeLoading, showLoading, toast } from "@/utils/toast";
import { showConfirmDialog } from "vant";
import global from "@/socket/config/Global";
import {
  buryingPointToFaceBook,
  buryingPointToGoogle,
  buryingPointToKwaiq,
} from "@/utils";
import http from "@/https";
import { propsStore } from "@/stores/modules/props";
import storage, { actions } from "@/utils/storage";

const propsDataStore = propsStore();
const propsData = computed(() => {
  if (storage.getStorage(actions.PROPS_DATA)) {
    return JSON.parse(storage.getStorage(actions.PROPS_DATA) || "") || [];
  } else {
    return propsDataStore.propsData;
  }
});
const propNames = computed(() => (propId: any) => {
  let obj: any = propsData.value.find((item: any) => item._id == propId);
  return obj && obj.propName === 'Moedas' ? 'R$' : '💎';
});

const checked = ref<number>(1);

const iframeRefSrc = ref("");

const sokcet: any = inject("socket");
const userStore = useUserStore();
const showOne = computed(() => {
  return userStore.userInfo && userStore.userInfo.totalPay == 0;
});
const activeItemObj = ref<any>([]);

const codeValue = ref(false);
const qrCode = ref("");
const showDeposit = ref(false);
interface DataProps {
  method: number | undefined;
  _id: string | undefined;
}

interface AmountProps {
  price: number;
  methods: string | Array<string>;
  propsList: Array<any>;
}

const currentBankIndex = ref(0);
const currentAmountIndex = ref(-1);
const amount = ref<number | undefined>(undefined);
const depostAmount = ref<number | undefined>(0);
const payLimit = ref<Array<any>>([]);
const data = reactive<DataProps>({
  method: undefined,
  _id: undefined,
});
watch(
  () => amount.value,
  () => {
    if (amount.value) {
      for (let i = 0; i < amounts.value.length; i++) {
        if (amount.value <= amounts.value[0].price / 10000) {
          if (amount.value < amounts.value[0].price / 10000) {
            watchAmountItem(-1);
            break;
          } else {
            watchAmountItem(0);
            break;
          }
        }
        if (
          amount.value > amounts.value[i].price / 10000 &&
          amount.value < amounts.value[i + 1].price / 10000
        ) {
          watchAmountItem(i);
          break;
        }
        if (amount.value == amounts.value[i].price / 10000) {
          watchAmount(i);
          break;
        } else {
          currentAmountIndex.value = -1;
          data._id = undefined;
          activeItemObj.value = [];
        }
        if (
          amount.value >=
          amounts.value[amounts.value.length - 1].price / 10000
        ) {
          watchAmountItem(amounts.value.length - 1);
          break;
        }
      }
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

const closeIframe = () => {
  showDeposit.value = false;
  iframeRefSrc.value = "";
};
const closeCodeMode = () => {
  codeValue.value = false;
  setTimeout(() => {
    qrCode.value = "";
    depostAmount.value = 0;
  }, 1000);
};
// 支付列表
const payList = ref<Array<any>>([]);
// 金额列表
const ampuntList = ref<Array<AmountProps>>([]);

onMounted(async () => {
  await getPayClass();
  await getData();
  await checkBank(0);
});

const amounts = computed(() => {
  console.log(ampuntList.value, "ampuntList.value");
  console.log(payList.value, "payList.value");
  if (ampuntList.value.length > 0) {
    let pay: Array<any> = ampuntList.value
      .filter((i: any) => {
        let payValue = payList.value[currentBankIndex.value]
          ? payList.value[currentBankIndex.value].value
          : undefined;

        if (payValue) {
          let m = i.methods;
          if (m.find((j: any) => j === payValue)) {
            return i;
          } else {
            return [];
          }
        }
      })
      .sort((i: any, j: any) => i.price - j.price);
    if (!userStore.userInfo.totalPay || Number(userStore.userInfo.totalPay) === 0) {
      for (let i = 0; i < pay.length; i++) {
        pay[i].propsList = [...pay[i].propsListFirstPay];
      }
    }
    return pay;
  }
  return [];
  // if (ampuntList.value[currentBankIndex.value]) {
  //   let pay: Array<any> = ampuntList.value
  //     .filter((i: any) => {
  //       let m = i.methods;
  //       if (Array.isArray(m)) {
  //         m = m.join(",");
  //       }
  //       if (payList.value.find((j: any) => i.methods.includes(j.value))) {
  //         return i;
  //       }
  //     })
  //     .sort((i: any, j: any) => i.price - j.price);
  //   if (Number(userStore.userInfo.totalPay) === 0) {
  //     for (let i = 0; i < pay.length; i++) {
  //       pay[i].propsList = [...pay[i].propsListFirstPay];
  //     }
  //   }
  //   return pay;
  // }
  // return [];
});
const holder = ref('');
const cpf = ref('');
// 提交充值
const submit = () => {
  if (Number(amount.value) < Number(payLimit.value[0] / 10000)) {
    return toast(
      "A quantia de compra inserida é muito pequena. Por favor, confirme e insira novamente."
    );
  }
  if (Number(amount.value) > Number(payLimit.value[1] / 10000)) {
    return toast(
      "A quantia de compra inserida é muito grande. Por favor, confirme e insira novamente."
    );
  }
  showLoading();
  let obj: any = {
    _id: data._id,
    method: 1,
    amount: Number(amount.value) * 10000,
    classValue: payList.value[currentBankIndex.value].value,
    goodsType: checked.value,
    holder: holder.value,
    cpf: cpf.value
  };
  depostAmount.value = amount.value;
  http.userDeposit(obj).then((res: any) => {
    if (res.code != 0) {
      closeLoading();
      toast(res.txt);
      return;
    }
    let price = amount.value;
    // jumpOhterLink(res.data.url);
    if (res.data.qrcode && res.data.qrcode != "") {
      codeValue.value = true;
      qrCode.value = res.data.qrcode;
    } else {
      iframeRefSrc.value = res.data.url;
      showDeposit.value = true;
    }
    reset();
    closeLoading();
    sokcet
      .on(`${global.EVENT_NAME.PAY_ORDER}_${res.data.orderId}`)
      .then(async (res: any) => {
        console.log(res, "?");
        console.log(userStore.userInfo, "?");
        /**
         * 充值成功监听
         */
        // 如果用户总充值等于0，则首充埋点
        if (userStore.userInfo.totalPay === 0) {
          buryingPointToFaceBook("firstDepositArrival", {
            content_name: userStore.userInfo.nickname,
            content_id: Number(userStore.userInfo.uid),
            content_type: "product",
            price: price,
            // quantity: 1,
            value: price,
            currency: "USD",
          });
        }
        // 充值埋点
        buryingPointToFaceBook("Purchase", {
          content_name: userStore.userInfo.nickname,
          content_id: Number(userStore.userInfo.uid),
          content_type: "product",
          price: price,
          // quantity: 1,
          value: price,
          currency: "USD",
        });
        buryingPointToGoogle("purchase", {
          currency: "USD",
          transaction_id: res.data.orderId,
          value: price,
          items: [
            {
              item_id: res.data.orderId,
              item_name: price,
            },
          ],
        });

        buryingPointToKwaiq("purchase", {
          content_id: res.data.orderId,
          content_type: "product",
          content_name: userStore.userInfo.nickname,
          quantity: 1,
          price: price,
          value: price,
          currency: "USD",
        });
        await userStore.getUserInfo();
        await getData();
        toast("Recargado com sucesso!", {
          size: 'large'
        });
      });
    // showConfirmDialog({
    //   title: "Confirmation",
    //   message: "Success！please go to the deposit page",
    //   showCancelButton: false,
    //   confirmButtonText: "Go now",
    //   confirmButtonColor: "#313160",
    //   width: "80%",
    // }).then(async () => {});
    // closeLoading();
  });
};

const reset = () => {
  data._id = undefined;
  amount.value = undefined;
  currentBankIndex.value = 0;
  currentAmountIndex.value = -1;
  data.method = payList.value[currentBankIndex.value].value;
  activeItemObj.value = [];
};
const getPayClass = async () => {
  const res = await http.getPayClass();
  if (res.code != 0) {
    toast(res.txt);
    return;
  }
  payList.value = Array.from(Object.values(res.data), (x) => x);
  payLimit.value = payList.value[0] ? payList.value[0].amountLimitArea : [];
  console.log(payList.value);
};

const getData = async () => {
  const res = await http.depositList();
  if (res.code != 0) {
    toast(res.txt);
    return;
  }
  ampuntList.value = res.data.rows;
  console.log(res.data, "++++++++++++=");
  // payLimit.value = res.data.payLimit || 0;
  data.method = payList.value[currentBankIndex.value].value;
  getUpdate(ampuntList.value)
};
const getUpdate = async (list) => {
  list = list.map(item => {
    return item.propsList.map(v => v.propId)
  })

  const res = await http.getPropsCache({
    propIds: list.flat()
  })
  if (res.data.props) {
    for (let i = 0; i < res.data.props.length; i++) {
      propsDataStore.setPropsData(res.data.props[i]);
    }
  }
}
const isNeedAccount = ref(false);
const checkBank = (index: number) => {
  console.log('====================================');
  console.log(index);
  console.log('====================================');
  currentBankIndex.value = index;
  const tempPay = payList.value[currentBankIndex.value];
  data.method = tempPay.value;
  isNeedAccount.value = tempPay.isNeedAccount;
  payLimit.value = payList.value[index]
    ? payList.value[index].amountLimitArea
    : [];
  cpf.value = '';
  holder.value = '';
};

const checkAmount = (index: number) => {
  currentAmountIndex.value = index;
  amount.value = amounts.value[index].price / 10000;
  data._id = amounts.value[index]._id;
  activeItemObj.value = amounts.value[index].propsList;
};

const watchAmount = (index: number) => {
  currentAmountIndex.value = index;
  data._id = amounts.value[index]._id;
  activeItemObj.value = amounts.value[index].propsList;
};
const watchAmountItem = (index: number) => {
  console.log(index);

  if (index == -1) {
    currentAmountIndex.value = index;
    data._id = undefined;
    activeItemObj.value = [];
    return;
  } else {
    if (amount.value == amounts.value[index].price / 10000) {
      currentAmountIndex.value = index;
    }
    data._id = amounts.value[index]._id;
    activeItemObj.value = amounts.value[index].propsList;
  }
};
</script>

<style lang="scss" scoped>
.deposito {
  padding: 0.2rem;
  font-weight: 500;
  text-align: center;
  position: relative;

  >.box {
    width: 100%;

    >.close {
      position: absolute;
      right: 0.4rem;
      top: 0.2rem;
      z-index: 99999;
      cursor: pointer;
    }

    >#iframe {
      position: absolute;
      top: 0;
      z-index: 9999;
      left: 0;
      overflow: hidden;
    }
  }

  .bank-box {
    .tips {
      font-size: 0.35rem;
      text-align: left;
      color: rgb(0, 231, 187);
    }

    .bank {
      // margin: 0.2rem 0;
      display: grid;
      gap: 0.2rem;
      overflow: auto;
      padding: 0.2rem 0;

      &-item {
        font-size: 0.3rem;
        width: 3.7rem;
        background: #232323;
        border-radius: 0.2rem;
        padding: 0.25rem 0.1rem;
        border: 1px solid #232323;
        @extend .transition;

        .top {
          display: flex;
          align-items: center;
          justify-content: center;

          .icon {
            width: 2rem;
          }

          span {
            font-size: 0.3rem;
            color: #b1b1b1;
          }
        }
      }

      .active {
        border: 1px solid rgb(0, 231, 187);

        .bottom {
          color: #fff;
        }
      }

      .bottom {
        color: rgb(141, 158, 154)
      }
    }
  }

  .field {
    display: flex;
    align-items: center;
    background-color: #222;
    border-radius: 0.1rem;
    position: relative;

    .dia-box {
      position: absolute;
      height: 100%;
      right: 0;
      top: 0;
      font-size: 0.3rem;
      display: flex;
      align-items: center;
      justify-content: center;
      color: rgb(243, 230, 21);
    }

    p {
      font-size: 0.4rem;
      color: rgb(0, 231, 187);
      width: 9rem;
    }

    :deep(.van-cell:after) {
      border: none !important;
    }

    .van-field {
      background: #222;
      font-size: 0.4rem;

      :deep(.van-field__control) {
        color: #ffe726 !important;
        font-weight: bold;
        font-size: 0.3rem;
      }
    }
  }

  .checked-box {
    padding: 0.2rem 0;

    :deep(.van-radio__label) {
      color: #fff;
      font-size: 0.3rem;
    }

    :deep(.van-radio) {
      margin-bottom: 0.2rem;
    }
  }

  .amount-box {
    .ampuntList {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 0.3rem;
      font-size: 0.45rem;
      margin: 0.2rem 0;

      .amount-item {
        background-color: #3f4754;
        border-radius: 0.2rem;
        padding: 0.2rem 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: relative;
        font-weight: bold;
        height: 1.2rem;
        @extend .transition;

        p {
          font-size: 0.35rem;
        }

        .hot {
          position: absolute;
          top: 0;
          width: 1.1rem;
        }
      }

      .active {
        background: $button-color;
      }
    }
  }

  .bt-tips {
    font-size: 0.35rem;
    text-align: left;
    margin-top: 0.2rem;
    font-weight: 500;

    p {
      margin-top: 0.2rem;
    }

    span {
      color: rgb(0, 231, 187);
    }
  }

  .qrCode-box {
    display: flex;
    flex-direction: column;
    align-content: center;
    height: 100%;
    position: relative;

    .close {
      width: 0.8rem;
      position: absolute;
      right: 0.5rem;
      top: 1rem;
    }

    .content {
      margin-top: 20%;
      height: 100%;
      background-color: #232323;
      padding: 0.5rem 2rem;

      >p {
        font-size: 0.3rem;
        color: #fff;
      }

      >.amount {
        margin: 0.3rem 0;
        font-size: 0.5rem;
        color: #fff;
      }

      >.codeImg {
        width: 3.5rem;
        margin: 0 auto;

        >.code {
          width: 100% !important;
          height: 100% !important;
          border: 1px solid #fff;
        }
      }
    }
  }
}
</style>
<style>
.my-field .van-field {
  padding: 10px !important;
  border-radius: 0.1rem !important;
}

.my-field .van-field__control {
  font-size: 12px !important;
}
</style>
