<template>
  <teleport to="#app">
    <van-overlay :show="show" :z-index="zIndex">
      <div class="bg-box">
        <h-img class="close-img" src="base/close.png" @click="close" />
        <div class="di-img">
          <h-img src="perfil/tu3.png" />
          <div class="box flex-cl">
            <div class="block" :style="{
              backgroundImage: `url(${getStaticImage(item.icon)})`,
            }" :class="{
              active: index === active,
              not_receive:
                oneOfThreePayIds && !oneOfThreePayIds.includes(item._id),
            }" v-for="(item, index) in list" :key="index" @click="itemBorder(index)">
              <div class="item-tips" v-show="showTips == index">
                <div class="close" @click.stop="closeTips"></div>
                <div class="tip-top">
                  <div class="gold">
                    {{ formatDigit(item.propsList[0].num / 10000) }}
                  </div>
                  <div class="diamond">
                    {{
                      formatDigit(item.propsList[1].num / 10000 / item.keepDay)
                    }}
                  </div>
                </div>
                <div class="tip-bottom">
                  <div class="ganhos-diarios">
                    {{
                      formatDigit(item.propsList[1].num / 10000 / item.keepDay)
                    }}
                  </div>
                  <div class="day">{{ item.keepDay }}</div>
                </div>
              </div>
              <div class="left">
                <div class="jisuan flex-ct">
                  <h-img width="0.5rem" height="0.5rem" src="base/JB_R$.png" />
                  <span>{{ formatDigit(item.propsList[0].num / 10000) }}</span>
                  <span class="ped">+</span>
                  <h-img width="0.5rem" height="0.5rem" src="base/JB_zs.png" />
                  <span>{{ formatDigit(item.propsList[1].num / 10000) }}</span>
                  <span class="ped">=</span>
                  <span style="font-size: 0.3rem">R$</span>
                  <span class="origPrice">
                    {{ formatDigit(item.origPrice / 10000) }}
                  </span>
                </div>
              </div>
              <div class="right">
                <div class="per">{{ per(item) }}</div>
                <span class="zhi">R$</span>
                <span>{{ formatDigit(item.price / 10000) }}</span>
              </div>
            </div>
          </div>
          <van-button class="btn-box" v-if="!oneOfThreePayIds" :disabled="beforeBuyVisible" @click="beforeBuy">
            R$ {{ num }}
          </van-button>
          <van-button class="btn-box" v-else :disabled="receiveVisible" @click="receive">
            RECEBER
          </van-button>
          <p class="received-tips">
            <span style="color: #f3e615" class="time" ref="timeRef"></span>
          </p>
        </div>
      </div>
    </van-overlay>
    <!-- 支付列表 -->
    <h-center-popup v-model="showPaymentVisible" :z-index="1001" title="Método de pagamento">
      <div class="container">
        <div class="payment-list" style="margin-bottom: 10px;">
          <div class="payment" :class="payCurrent == index ? 'active' : ''" v-for="(item, index) in payList"
            :key="index" @click="select(index)">
            {{ item.txt }}
          </div>
        </div>
        <div class="my-field" v-if="isNeedAccount">
          <div class="field">
            <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="margin-top:10px;">
            <p style="font-size: 16px; width: 50px;margin-left:10px;">CPF</p>
            <van-field v-model="cpf" :placeholder="`CPF ou CNPJ (CPF ou CNPJ do pagador)`" type="digit" />
          </div>
        </div>
      </div>
      <van-button color="#42866b" size="large" @click="buy" :disabled="isNeedAccount && (holder === '' || cpf === '')">
        COMPRAR
      </van-button>
    </h-center-popup>
  </teleport>
</template>
<script setup lang="ts">
import { ref, computed, watchEffect, inject, watch } from "vue";
import socketApi from "@/socket/socketApi";
import {
  getStaticImage,
  formatDigit,
  fomartDate,
  jumpOhterLink,
  getCurrentTime,
} from "@/utils";
import { closeLoading, showLoading, toast } from "@/utils/toast";
import { useUserStore } from "@/stores/modules/user";
import { showConfirmDialog } from "vant";
import global from "@/socket/config/Global";
import dayjs from "dayjs";
import emitter from "@/utils/eventBus";
import http from "@/https/index";

const sokcet: any = inject("socket");
const userStore = useUserStore();

const props = defineProps({
  zIndex: { type: Number, default: 1000, required: false },
  info: { type: Object, default: {}, required: false },
});

const emit = defineEmits(["handle"]);

const list = ref<Array<any>>([]);
const payList = ref<Array<any>>([]);
const payCurrent = ref<number>(0);
const active = ref<number>(-1);
const showTips = ref<number>(-1);
const buyTime = ref<number>(0);
const showPaymentVisible = ref<boolean>(false);
const show = ref<boolean>(false);

// 倒计时
const countDownNum = ref();
const timeRef = ref();

const oneOfThreePayIds = computed(() => userStore.userInfo.oneOfThreePayIds);

watch(()=>showPaymentVisible.value,()=>{
  holder.value = '';
  cpf.value = '';
})

watchEffect(() => {
  if (show.value && props.info.rows) {
    list.value = props.info.rows.map((item: any) => {
      switch (item.sort) {
        case 1:
          item.icon = "perfil/di_1.png";
          break;
        case 2:
          item.icon = "perfil/di_2.png";
          break;
        case 3:
          item.icon = "perfil/di_3.png";
          break;
      }
      return item;
    });
    console.log(list.value);
    if (oneOfThreePayIds.value) {
      list.value.forEach((item, index) => {
        if (oneOfThreePayIds.value.includes(item._id)) {
          active.value = index;
        }
      });
    }
    buyTime.value = Number(fomartDate(props.info.oneOfThreeAt, "DD"));
  } else {
    clearInterval(countDownNum.value);
    countDownNum.value = null;
  }
});

const isNeedAccount = ref(false);
const select = (index: number) => {
  payCurrent.value = index;
  const tempPay = payList.value[payCurrent.value];
  isNeedAccount.value = tempPay.isNeedAccount;
  cpf.value = '';
  holder.value = '';
};

const closeTips = () => {
  showTips.value = -1;
};

const beforeBuy = () => {
  http.getPayClass().then((res: any) => {
    if (res.code !== 0) return toast(res.txt);
    payList.value = Array.from(Object.values(res.data), (x) => x);
    showPaymentVisible.value = true;
  });
};

const holder = ref('');
const cpf = ref('');
const buy = () => {
  showLoading();
  const params = {
    _id: list.value[active.value]._id,
    method: payList.value[payCurrent.value].method[0],
    classValue: payList.value[payCurrent.value].value,
    holder:holder.value,
    cpf:cpf.value
  };
  http.oneOfThreeBuy(params).then((res: any) => {
    if (res.code !== 0) {
      closeLoading();
      toast(res.txt);
      return;
    }
    closeLoading();
    showConfirmDialog({
      title: "Confirmation",
      message: "Success！please go to the deposit page",
      showCancelButton: false,
      confirmButtonText: "Go now",
      confirmButtonColor: "#313160",
      width: "80%",
    }).then(async () => {
      jumpOhterLink(res.data.url);
      showPaymentVisible.value = false;
      sokcet
        .on(`${global.EVENT_NAME.PAY_ORDER}_${res.data.orderId}`)
        .then(async () => {
          await userStore.getUserInfo();
          toast("Compra bem sucedida!");
          emit("handle");
        });
    });
  });
};
// 领取
const receive = () => {
  showLoading();
  http.receiveOneOfThree().then(async (res: any) => {
    if (res.code !== 0) {
      closeLoading();
      toast(res.txt);
      return;
    }
    await userStore.getUserInfo();
    if (oneOfThreePayIds.value.length == 0) {
      clearInterval(countDownNum.value);
      timeRef.value.innerHTML = "";
      countDownNum.value = null;
    }
    closeLoading();
    toast("Recebido com sucesso!");
    emit("handle");
  });
};

const per = (item: any) => {
  return (((item.origPrice - item.price) / item.price) * 100).toFixed(0) + "%";
};

const countdown = () => {
  clearInterval(countDownNum.value);
  countDownNum.value = null;
  const time = getCurrentTime();
  const endTime = dayjs()
    .date(new Date().getDate() + 1)
    .startOf("day")
    .unix();
  var d, h, m, s;
  var lastTime = Number(endTime) - time;
  if (lastTime && timeRef.value) {
    countDownNum.value = setInterval(() => {
      lastTime--;
      d = Math.floor(lastTime / 60 / 60 / 24);
      h = Math.floor(lastTime / 60 / 60) % 24;
      m = Math.floor((lastTime / 60) % 60);
      s = lastTime % 60;
      s = s < 10 ? "0" + s : s;
      m = m < 10 ? "0" + m : m;
      timeRef.value.innerHTML = h + ":" + m + ":" + s;
      if (h == 0 && m == 0 && s == 0) {
        clearInterval(countDownNum.value);
        timeRef.value.innerHTML = "";
        countDownNum.value = null;
      }
    }, 1000);
  }
};

const num = computed(() => {
  if (list.value.length && active.value !== -1) {
    return list.value[active.value].price / 10000;
  }
  return 0;
});

const beforeBuyVisible = computed(() => {
  if (active.value === -1) return true;
  return false;
});

const receiveVisible = computed(() => {
  if (!show.value) return false;
  if (!oneOfThreePayIds.value && !oneOfThreePayIds.value.length) {
    return true;
  }
  const date = Number(fomartDate(new Date(), "DD"));
  // 当前天数剪去购买天数
  const diff = date - buyTime.value;
  if (diff < 0) return true;
  let remain = 0;
  if (list.value[active.value]) {
    remain = list.value[active.value].keepDay - diff;
  }
  if (oneOfThreePayIds.value && oneOfThreePayIds.value.length < remain) {
    countdown();
    return true;
  }
  return false;
});

function itemBorder(index: number) {
  if (oneOfThreePayIds.value) return;
  active.value = index;
  showTips.value = index;
}

const open = () => {
  show.value = true;
};

const close = () => {
  clearInterval(countDownNum.value);
  countDownNum.value = null;
  timeRef.value.innerHTML = "";
  show.value = false;
  active.value = -1;
  showTips.value = -1;
};

emitter.on("openThreeInOne", open);
emitter.on("closeThreeInOne", close);

defineExpose({
  open,
  close,
});
</script>
<style lang="scss" scoped>
@import "./index.scss";

.field {
  display: flex;
  align-items: center;
  border-radius: 0.1rem;
  justify-content: space-between;
  position: relative;
  p {
    font-size: 0.4rem;
    color: #009165 !important;
    width: 1.5rem !important;
  }

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

  .van-field {
    background: #677678;
    font-size: 0.4rem;
    margin-left: 10px;

    :deep(.van-field__control) {
      font-weight: bold;
      font-size: 0.3rem;
    }
  }
}
</style>

<style>
.my-field {
  margin: 10px 0;
}

.my-field .van-field {
  padding: 10px !important;
  border-radius: 0.1rem !important;
}

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