<template>
  <div class="page">
    <h-navbar>
      <template v-slot:left>
        <div class="titleLight flex-ct" @click="openUserinfo">
          <h-img width=".8rem" type="local" class="back" src="base/fanhui.png" />
          <span>Cashback</span>
        </div>
      </template>
      <template v-slot:right>
        <div class="titleRight flex-ct" @click="openUserinfo">
          <h-img width=".5rem" src="turntable/wd.png" />
          <span>
            R$
            {{
              userStore.userInfo ? formatDigit(Math.trunc(Number(userStore.userInfo.coins / 10000))) : '0.00'
            }}
          </span>
        </div>
      </template>
    </h-navbar>
    <div class="page-body">
      <div class="page-body-top">
        <div class="page-body-top-mon flex-sb">
          <div>
            <h-img type="local" src="base/R$.png" width="1rem" />
            <span>{{ scheduleData ? scheduleData.rebate : 0 }}% Cashback</span>
            <span
              >Max:{{
                tableData.length > 0
                  ? tableData[tableData.length - 1].rebate
                  : 0
              }}%</span
            >
          </div>
          <div>
            <h-img type="local" src="base/VIP_hg.png" width="0.4rem" />
            <div class="lv">N {{ scheduleData ? scheduleData.leave : 0 }}</div>
          </div>
        </div>
        <div class="line">
          <div
            class="line-p"
            :style="{
              width: `${percentage}%`,
            }"
          ></div>
        </div>
        <p>
          {{ nextBetNum === 0 ? "Max nivel" : `${nextBetNum} Apostas to` }}
          <span
            >N
            {{
              scheduleData.leave == 10
                ? scheduleData.leave
                : scheduleData.leave + 1
            }}</span
          >
        </p>
      </div>
      <div class="page-body-mid">
        <div class="left flex-sb">
          <h-img type="local" src="base/icon_0.png" width="2.3rem" />
          <div class="left-text">
            <h2>Seu CashbacK Semanal</h2>
            <p>Voce ganhara ??? BRL em cashback jogandoesta semana.</p>
          </div>
        </div>
        <div class="right">
          <p style="color: red; font-size: 0.35rem">
            Periodo
            {{
              fomartDate(rebateData.cycleBeginTime, "YYYY-MM-DD HH:mm:ss")
            }}~{{ nextCycleBeginTime }}
          </p>
          <div @click="openCashback" class="btn">
            <span>Reivindicar Agora</span>
          </div>
          <div class="font-box" :class="{ 'font-box-color': showFontColor }">
            <p>Tempo de reivindicação</p>
            <p>
              {{
                fomartDate(
                  rebateData.cycleReceicveBeginTime,
                  "YYYY-MM-DD HH:mm:ss"
                )
              }}~{{ nextCycleReceicveBeginTime }}
            </p>
          </div>
        </div>
      </div>
      <div class="page-body-table">
        <div class="header">Status Nível Cashback</div>
        <div class="row">
          <div class="row-one">
            <div>Nível</div>
            <div>APOSTA</div>
            <div>CASHBACK</div>
          </div>
          <div
            v-for="(item, index) in tableData"
            :key="index"
            :class="{ rowBackGround: (index + 1) % 2 !== 0 }"
          >
            <div>{{ index + 1 }}</div>
            <div>{{ item.betNum / 10000 }} + BRL</div>
            <div>{{ item.rebate }} %</div>
          </div>
        </div>
      </div>
      <div class="page-body-btn">
        <h2>TERMOS E REGRAS</h2>
        <p>1. O cashback semanal é dado como recompensa todas as semanas.</p>
        <p>
          2. O período sobre o qual é calculado o cashback semanal vai de
          segunda-feira às 00:00 a domingo às 23:59.
        </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 não for resgatado.
        </p>
        <p>
          4. O número de Perdas de dinheiro real multiplicado pela % de
          reembolso é o reembolso/cashback da semana.
        </p>
        <p>
          5. Caso você não tenha apostado durante o período em que o cashback
          estava ativo ou se seus ganhos da última semana ou ganhos totais são
          maiores que suas perdas, você não receberá cashback.
        </p>
        <p>
          6. Limite máximo de recompensa de cashback por pessoa por semana:
          10000 BRL.
        </p>
        <p>
          7. O valor do cashback pode ser sacar diretamente ou utilizado para
          continuar jogando.
        </p>
      </div>
    </div>
    <h-center-popup
      contentBgcolor="#004B42"
      v-model="showCashback"
      title="Cashback"
      :lockScroll="false"
    >
      <div class="box">
        <div class="table-box">
          <div>
            <div
              style="
                border-bottom: 1px solid #00fab4;
                border-right: 1px solid #00fab4;
              "
            >
              Semana passada perda
            </div>
            <div
              style="
                border-bottom: 1px solid #00fab4;
                border-right: 1px solid #00fab4;
              "
            >
              Nível
            </div>
            <div style="border-bottom: 1px solid #00fab4">Quantidade</div>
          </div>
          <div>
            <div style="border-right: 1px solid #00fab4">
              {{ rebateData.lastWeek.profitCoins / 10000 }}
            </div>
            <div style="border-right: 1px solid #00fab4">
              {{ scheduleData ? scheduleData.leave : 0 }}
            </div>
            <div>
              {{
                (
                  Math.abs(rebateData.lastWeek.profitCoins / 10000) *
                  (scheduleData.rebate / 100)
                ).toFixed(2)
              }}
            </div>
          </div>
        </div>
        <div
          class="btn-box"
          :style="{
            backgroundColor:
              rebateData.lastWeek.profitCoins < 0 ? '#CE7B0D' : '#383837',
            cursor:
              rebateData.lastWeek.profitCoins == 0 ? 'no-drop' : 'pointer',
          }"
          @click="receber"
        >
          Receber
        </div>
      </div>
    </h-center-popup>
  </div>
</template>
<script setup lang='ts'>
import { ref, onMounted, reactive, computed } from "vue";
import useUserLevel from "@/hooks/useUserLevel";
import socketApi from "@/socket/socketApi";
import { fomartDate, formatDigit } from "@/utils";
import { toast, showLoading, closeLoading } from "@/utils/toast";
import { useUserStore } from "@/stores/modules/user";
import router from "@/router";
import http from "@/https/index";

const userStore = useUserStore();
const { currentLevel } = useUserLevel();
const totalBet = ref<number>(0);

const tableData = ref<Array<any>>([]);
const rebateData = ref<any>({});
const showCashback = ref(false);
const showFontColor = ref(false);
onMounted(async () => {
  await getCycleRebate();
});
// 对应等级信息
const scheduleData = ref<any>({});
// 百分比
const percentage = ref(0);
const nextBetNum = computed(() => {
  for (let i = 0; i < tableData.value.length; i++) {
    console.log(scheduleData.value.leave, "++++++++==");
    if (scheduleData.value.leave === 10) return 0;
    if (scheduleData.value.leave === 1) {
      return ((tableData.value[1].betNum - totalBet.value) / 10000).toFixed(2);
    }
    if (tableData.value[i].leave === scheduleData.value.leave) {
      if (tableData.value[i - 1].betNum === totalBet.value) {
        return ((tableData.value[i].betNum - totalBet.value) / 10000).toFixed(
          2
        );
      } else {
        return (
          (tableData.value[i + 1].betNum - totalBet.value) /
          10000
        ).toFixed(2);
      }
    }
  }
});
// 上周奖励领取开始时间
const nextCycleBeginTime = computed(() => {
  let time = `${fomartDate(
    new Date(
      new Date(rebateData.value.cycleBeginTime).getTime() +
        86400000 * rebateData.value.days
    ),
    "YYYY-MM-DD"
  )} 00:00:00`;
  return fomartDate(
    new Date(new Date(time).getTime() - 1000),
    "YYYY-MM-DD HH:mm:ss"
  );
});
// 上周奖励领取结束时间
const nextCycleReceicveBeginTime = computed(() => {
  let time = `${fomartDate(
    new Date(
      new Date(rebateData.value.cycleReceicveBeginTime).getTime() +
        86400000 * rebateData.value.awardTime
    ),
    "YYYY-MM-DD"
  )} 00:00:00`;
  return fomartDate(
    new Date(new Date(time).getTime() - 1000),
    "YYYY-MM-DD HH:mm:ss"
  );
});
const getCycleRebate = async () => {
  const res = await http.getCycleRebate();
  console.log(res);
  if (res.code != 0) return;
  tableData.value = res.data.rebateConfig ? res.data.rebateConfig.rows : [];
  tableData.value.map((item: any, index: number) => {
    item.leave = index + 1;
  });
  rebateData.value = res.data.rebateData ? { ...res.data.rebateData } : {};
  totalBet.value = res.data.totalBet || 0;
  if (res.data.totalBet == 0) {
    scheduleData.value = res.data.rebateConfig.rows[0];
    percentage.value = 0;
    return;
  } else if (
    res.data.totalBet >
    res.data.rebateConfig.rows[res.data.rebateConfig.rows.length - 1].betNum
  ) {
    scheduleData.value =
      res.data.rebateConfig.rows[res.data.rebateConfig.rows.length - 1];
    percentage.value = 100;
    return;
  } else {
    for (let i = 0; i < res.data.rebateConfig.rows.length; i++) {
      if (totalBet.value == res.data.rebateConfig.rows[i].betNum) {
        if (i === res.data.rebateConfig.rows.length - 1) {
          scheduleData.value =
            res.data.rebateConfig.rows[res.data.rebateConfig.rows.length - 1];
          percentage.value = 100;
          return;
        } else {
          scheduleData.value = res.data.rebateConfig.rows[i];
          percentage.value = Number(
            (
              (totalBet.value / res.data.rebateConfig.rows[i + 1].betNum) *
              100
            ).toFixed(2)
          );
          return;
        }
      } else if (
        totalBet.value > res.data.rebateConfig.rows[i].betNum &&
        totalBet.value < res.data.rebateConfig.rows[i + 1].betNum
      ) {
        scheduleData.value = res.data.rebateConfig.rows[i];
        percentage.value = Number(
          (
            (totalBet.value / res.data.rebateConfig.rows[i + 1].betNum) *
            100
          ).toFixed(2)
        );
      }
    }
  }
};
const openCashback = () => {
  let starTime =
    new Date(rebateData.value.cycleReceicveBeginTime).getTime() -
    rebateData.value.days * 86400000;
  let endTime =
    new Date(nextCycleReceicveBeginTime.value).getTime() -
    rebateData.value.days * 86400000;
  let date = new Date().getTime();
  if (
    date >= starTime &&
    date <= endTime &&
    rebateData.value.lastWeek.profitCoins < 0
  ) {
    showCashback.value = true;
    showFontColor.value = false;
  } else {
    showFontColor.value = true;
  }
  setTimeout(() => {
    showFontColor.value = false;
  }, 2000);
};
const openUserinfo = () => {
  router.go(-1)
};
const receber = async () => {
  if (rebateData.value.lastWeek.profitCoins < 0) {
    showLoading();
    const res = await http.receiveCycleRebateLoss();
    closeLoading();
    if (res.code != 0) return toast(res.txt);
    showCashback.value = false;
    toast("Reclamado com sucesso");
    rebateData.value.lastWeek.profitCoins = 0;
    await userStore.getUserInfo()
  }
};
</script>
<style lang='scss' scoped>
.titleRight {
  font-size: 0.35rem;
  font-weight: 600;
  cursor: pointer;
}
.titleLight {
  span {
    font-size: 0.35rem;
    color: #f7e600;
    font-weight: 600;
  }
}
.box {
  .table-box {
    border: 1px solid #00fab4;
    border-radius: $border-radius;
    overflow: hidden;
    > div {
      display: grid;
      grid-template-columns: 50% 25% 25%;
      text-align: center;
      height: 1rem;
      line-height: 1rem;
      font-size: 0.35rem;
      color: #00e5d4;
      font-weight: 600;
    }
  }
  .btn-box {
    width: 45%;
    margin: 0.8rem auto 0.2rem auto;
    color: #fffa64;
    height: 1rem;
    text-align: center;
    line-height: 1rem;
    font-size: 0.5rem;
    font-weight: 600;
    border-radius: 0.1rem;
    cursor: pointer;
  }
}
.page-body {
  &-btn {
    text-align: left;
    padding: 0.2rem;
    background-color: #002a30;
    border-bottom-left-radius: $border-radius;
    border-bottom-right-radius: $border-radius;
    font-size: 0.3rem;
    h2 {
      font-size: 0.4rem;
    }
  }
  &-table {
    border-top-left-radius: $border-radius;
    border-top-right-radius: $border-radius;
    overflow: hidden;
    background-color: #00473d;
    font-size: 0.3rem;
    margin-top: 0.2rem;
    .row {
      > div {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        padding: 0.3rem 0;
      }
      &-one {
        color: #f8e700;
        font-weight: 600;
      }
      .rowBackGround {
        background-color: #004f43;
      }
    }
    .header {
      background-color: #006746;
      padding: 0.1rem 0.2rem;
      font-size: 0.4rem;
      text-align: left;
    }
  }
  &-mid {
    margin-top: 0.2rem;
    display: flex;
    padding: 0.2rem 0.5rem;
    background-color: #004c55;
    border-radius: $border-radius;
    justify-content: space-between;
    flex-direction: column;
    align-items: center;
    .left {
      &-text {
        text-align: right;
        width: 65%;
        font-size: 0.32rem;
        p {
          text-align: left;
        }
        h2 {
          color: red;
        }
      }
    }
    .right {
      text-align: left;
      font-size: 0.3rem;
      padding: 0 0.1rem;
      line-height: 0.6rem;
      width: 100%;
      .font-box {
        color: #89c2f7;
        font-size: 0.35rem;
      }
      .font-box-color {
        animation: 2s linear 0s 1 normal none running fontColor;
      }
      .btn {
        background-image: url("@/assets/img/base/button00.png");
        background-size: 100% 100%;
        padding: 0.1rem 0;
        font-weight: 600;
        text-align: center;
        cursor: pointer;
        font-size: .4rem;
      }
    }
  }
  &-top {
    background-color: #7e57b8;
    padding: 0.2rem;
    border-radius: $border-radius;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    .line {
      width: 100%;
      background: #000;
      height: 0.3rem;
      margin-top: 0.2rem;
      border-radius: $border-radius;
      position: relative;
      border-radius: 1rem;
      &-p {
        box-sizing: border-box;
        position: absolute;
        height: 100%;
        line-height: 100%;
        background: linear-gradient(to right, #4ea670, #afdf7b, #c3ea7d);
        border-radius: 1rem;
        font-size: 0.3rem;
        font-weight: bold;
        text-align: right;
        padding: 0 0.2rem;
        color: #606060;
      }
    }
    > p {
      width: 100%;
      text-align: right;
      margin-top: 0.2rem;
      font-size: 0.3rem;
      font-weight: 600;
      span {
        color: #f8e700;
      }
    }
    &-mon {
      width: 100%;
      flex-direction: row;
      > div {
        display: flex;
        align-items: center;
        font-size: 0.2rem;
        > span:nth-of-type(1) {
          color: #f8e700;
          font-size: 0.4rem;
          margin: 0 0.3rem;
          font-weight: 600;
        }
        .lv {
          height: 0.4rem;
          margin-left: 0.1rem;
          padding: 0 0.2rem;
          line-height: 0.4rem;
          background-color: #00b350;
          color: #f8e700;
          font-weight: 600;
          border-radius: 0.05rem;
        }
      }
    }
  }
  @keyframes fontColor {
    0% {
      color: red;
    }
    50% {
      color: #89c2f7;
    }
    100% {
      color: red;
    }
  }
}
</style>