<template>
  <div class="signIn_body">
    <h-navbar title="Check-ins" />
    <div class="signIn">
      <div class="header">
        <img class="avatar" :src="getImage(userStore.userInfo.headUrl)" />
        <div class="userInfo">
          <p style="color: #98a2b2">Teb：{{ userStore.userInfo.mobile }}</p>
          <p>
            R$：{{
              formatDigit(Number(userStore.userInfo.coins / 10000).toFixed(2))
            }}
          </p>
        </div>
      </div>
      <div class="signIn-content">
        <div
          v-for="(item, index) in signInList"
          :key="index"
          :class="{
            item: index === 6,
          }"
        >
          <h-img type="local" :src="`signIn/0${item.value}.png`" />
          <div class="day">
            <span>{{ item.value }}</span> DAY
          </div>
          <div class="num">
            {{
              item.propsList.length > 0
                ? formatDigit((item.propsList[0].num / 10000).toFixed(2))
                : "0,00"
            }}
            BRL
          </div>
          <!-- 已签到 -->
          <div class="model flexBox" v-if="item.value <= weekCheckinCount">
            <h-img type="local" src="signIn/rydui.png" />
          </div>
          <!-- 今日签到 -->
          <div
            @click="signInToday(item,1)"
            class="todaySignIn flexBox"
            v-if="todaySignIn(item) && !(item.value <= weekCheckinCount)"
          >
            <h-img type="local" src="signIn/button.png" />
          </div>
          <!-- 补签 -->
          <div
            @click="signInToday(item,2)"
            class="model flexBox"
            v-if="showButton(item) && !(todaySignIn(item) && !(item.value <= weekCheckinCount))"
          >
            <h-img type="local" width="2rem" src="signIn/button_Repair.png" />
          </div>
        </div>
      </div>
    </div>
    <div class="statistics">
      <div>
        <p>{{ weekCheckinCount }}</p>
        <p>Número de Check-ins</p>
      </div>
      <span></span>
      <div>
        <p>{{ formatDigit(weekNum / 10000) }} BRL</p>
        <p>Total de recompensa de check-in</p>
      </div>
    </div>
    <div>
      <h-img type="local" src="signIn/bg_03.png" />
    </div>
    <!-- showToastData -->
    <h-center-popup
      v-model="showToastData"
      contentBgcolor="#002E2C"
      title="Prompt"
      @on-close="
        () => {
          showToastData = false;
          toastData = [];
        }
      "
    >
      <div class="toast-box">
        <p v-for="(item, index) in toastData" :key="index">
          {{ `${index + 1}. ${item.text}` }}
        </p>
      </div>
    </h-center-popup>
  </div>
</template>
<script setup lang='ts'>
import { ref, onMounted, computed } from "vue";
import { useUserStore } from "@/stores/modules/user";
import { formatDigit, getImage } from "@/utils";
import { closeLoading, showLoading, toast } from "@/utils/toast";
import useUserLevel from "@/hooks/useUserLevel";

import socketApi from "@/socket/socketApi";
import http from "@/https/index";

const userStore = useUserStore();
const TODAY_WEEK = Number(new Date().getDay()) === 0 ? 7 : Number(new Date().getDay());
const { currentLevel } = useUserLevel();
const showToastData = ref(false);
const toastData = ref<Array<any>>([]);
const allData = ref<any>({});
const signInList = ref<Array<any>>([]);
// 是否可以补签
const canSupplementary = ref(false);
// 今天是否可以签到
const checkinAt = ref(false);
// 周签到天数
const weekCheckinCount = ref<number>(0);

const weekNum = computed(() => {
  let num = 0;
  for (let i = 0; i < signInList.value.length; i++) {
    if (signInList.value[i].value <= weekCheckinCount.value) {
      num += signInList.value[i].propsList[0].num;
    }
  }
  return num;
});
const todaySignIn = computed(() => {
  return (item: any) => {
    if (checkinAt.value && item.value === weekCheckinCount.value + 1) {
      return true;
    } else {
      if (weekCheckinCount.value === 0) {
        return item.value === weekCheckinCount.value + 1;
      }
      if (allData.value.todaySupplementaryCount > 0) {
        return item.value === weekCheckinCount.value;
      } else {
        return (
          item.value ===
          weekCheckinCount.value + allData.value.todaySupplementaryCount
        );
      }
    }
  };
});
// 补签
const showButton = computed(() => {
  return (item: any) => {
    if (canSupplementary.value && allData.value.supplementaryCount !== 0) {
      if (weekCheckinCount.value < TODAY_WEEK && weekCheckinCount.value > 0) {
        let day =
          weekCheckinCount.value +
          1 +
          allData.value.supplementaryCount -
          allData.value.todaySupplementaryCount;
        if (item.value > weekCheckinCount.value && item.value < day) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  };
});

const signInToday = async (item: any,type:number) => {
  let dl:any = null;
  if (canSupplementary.value && allData.value.supplementaryCount !== 0) {
    if (weekCheckinCount.value < TODAY_WEEK && weekCheckinCount.value > 0) {
      let day =
        weekCheckinCount.value +
        1 +
        allData.value.supplementaryCount -
        allData.value.todaySupplementaryCount;
      if (item.value > weekCheckinCount.value && item.value < day) {
        dl = true;
      } else {
        dl = false;
      }
    } else {
      dl = false;
    }
  } else {
    dl = false;
  }
  console.log(dl, "dl");
  if (!(item.value === weekCheckinCount.value + 1 || dl)) return;
  let userInfo = userStore.userInfo;
  // 普通签到
  if (type === 1) {
    // payType 普通签到 2今日充值 1 累积充值
    if (item.payType == 1) {
      if ((userInfo.totalPay || 0) < item.payLimit) {
        toastData.value.push({
          text: `O saldo restante para recarregar é ${formatDigit(
            (item.payLimit - (userInfo.totalPay || 0)) / 10000
          )}R$`,
        });
      }
    }
    if (item.payType == 2) {
      if (allData.value.todayPay < item.payLimit) {
        toastData.value.push({
          text: `Você ainda precisa recarregar ${formatDigit(
            (item.payLimit - allData.value.todayPay) / 10000
          )}R$ hoje.`,
        });
      }
    }
    if ((userInfo.totalBet || 0) < item.betLimit) {
      //下注流水 不满足签到要求
      toastData.value.push({
        text: `Ainda é necessário apostar ${formatDigit(
          (item.betLimit - (userInfo.totalBet || 0)) / 10000
        )}R$`,
      });
    }
    if (currentLevel.value.lv < item.vipLimit) {
      //vip 等级 不满足签到要求
      toastData.value.push({
        text: `O nível VIP precisa ser alcançado até o nível ${
          item.vipLimit - currentLevel.value.lv
        }`,
      });
    }

    if (!item.isLimit) {
      toastData.value = [];
    } else {
      if (toastData.value.length > 0) {
        showToastData.value = true;
        return;
      }
    }
  }
  if (type === 2) {
    // payType2 补签 2今日充值 1累积充值
    // 补签
    if (item.payType2 == 1) {
      if ((userInfo.totalPay || 0) < item.payLimit2) {
        toastData.value.push({
          text: `O saldo restante para recarregar é${formatDigit(
            (item.payLimit2 - (userInfo.totalPay || 0)) / 10000
          )}R$`,
        });
      }
    }
    if (item.payType2 == 2) {
      if (allData.value.todayPay < item.payLimit2) {
        toastData.value.push({
          text: `Você ainda precisa recarregar ${formatDigit(
            (item.payLimit2 - allData.value.todayPay) / 10000
          )}R$ hoje.`,
        });
      }
    }
    if ((userInfo.totalBet || 0) < item.betLimit2) {
      toastData.value.push({
        text: `Ainda é necessário apostar ${formatDigit(
          (item.betLimit2 - (userInfo.totalBet || 0)) / 10000
        )}R$`,
      });
    }
    if (currentLevel.value.lv < item.vipLimit2) {
      console.log(item);
      toastData.value.push({
        text: `O nível VIP precisa ser alcançado até o nível ${
          item.vipLimit2
        }`,
      });
    }
    if (toastData.value.length > 0) {
      showToastData.value = true;
      return;
    }
  }
  showLoading();
  console.log(type,"type")
  const res = await http.checkinDay({ type });
  console.log(res, "签到提交");
  if (res.code != 0) {
    closeLoading();
    return toast(res.txt);
  }
  await userStore.getUserInfo();
  await getCheckin();
  closeLoading();
  if (type == 1) {
    toast("Check-in bem sucedido");
  } else if (type == 2) {
    toast("Assinatura complementar bem sucedida");
  }
};

const getCheckin = async () => {
  const res = await http.getCheckin();
  console.log(res, "getCheckin");
  if (res.code != 0) return;
  allData.value = { ...res.data };
  signInList.value = [...res.data.rows.reverse()];
  canSupplementary.value = res.data.canSupplementary;
  weekCheckinCount.value = res.data.weekCheckinCount || 0;
  console.log(signInList.value, "signInList.value");
  let dateString = res.data.checkinAt || "";
  if (dateString) {
    let today = new Date();
    let givenDate = new Date(dateString);
    if (
      today.getFullYear() === givenDate.getFullYear() &&
      today.getMonth() === givenDate.getMonth() &&
      today.getDate() === givenDate.getDate()
    ) {
      //   console.log("给定日期等于今天的日期");
      checkinAt.value = false;
    } else {
      //   console.log("给定日期不等于今天的日期");
      checkinAt.value = true;
    }
  }
};
onMounted(async () => {
  await getCheckin();
});
</script>
<style lang='scss' scoped>
@import "./index.scss";
</style>