<template>
  <div class="body">
    <h-navbar title="Loteria" />
    <div class="content">
      <div class="text">
        <p>Convidar novos usuarios para ganhar pontos ou comprar pontos!</p>
        <h-img
          type="local"
          @click="
            () => {
              showActivityVisible = !showActivityVisible;
            }
          "
          width=".6rem"
          src="loteriaImg/wild.png"
        />
      </div>
      <div class="num-box">
        <p>
          Compartilhar: <span>{{ lotData.invitePoints || 0 }}</span>
        </p>
        <p>
          Comprado: <span>{{ lotData.buyPoints || 0 }}</span>
        </p>
        <p>
          Usado: <span>{{ lotData.usedPoints || 0 }}</span>
        </p>
        <p v-show="!showLoteriaMessage">
          Contagem regressiva:
          <span>{{
            `${times.days}dia ${
              times.hours < 10 ? "0" + times.hours : times.hours
            }:${times.minutes < 10 ? "0" + times.minutes : times.minutes}:${
              times.seconds < 10 ? "0" + times.seconds : times.seconds
            }`
          }}</span>
        </p>
      </div>
      <div v-if="!showLoteriaMessage">
        <div class="phone-img">
          <div
            class="phone-img-box"
            v-for="(item, index) in lotData.tasks"
            :key="index"
            @click="changeGift(index, item)"
          >
            <div class="father" :class="{ active: active === index }">
              <div class="left-box">
                <h-img type="local" width="2.3rem" src="loteriaImg/dihe.png" />
                <div class="left-box-text">
                  <p>{{ getProp(item.propsList[0].propId).propName }}</p>
                  <p>Quantidade:{{ item.recordsNum }}/{{ item.awardNum }}</p>
                </div>
                <img
                  class="left-box-phone"
                  :style="{
                    top:
                      getProp(item.propsList[0].propId).propName == 'IPhone'
                        ? '-0.2rem'
                        : '0.1rem',
                  }"
                  :src="getImage(getProp(item.propsList[0].propId).iconUrl)"
                />
              </div>
              <div class="right-box">
                <div class="num">
                  Última recompensa：
                  <span>{{
                    item.recentAwardUser
                      ? fomartName(item.recentAwardUser.nickname)
                      : ""
                  }}</span>
                </div>
                <div class="stepper">
                  <div
                    class="stepper-color"
                    :style="{
                      width: `${
                        (item.curProgress / item.totalProgress) * 100
                      }%`,
                    }"
                  ></div>
                  <div class="stepper-font">
                    {{ item.curProgress }} / {{ item.totalProgress }}
                  </div>
                </div>
                <div style="color: #a24100">
                  Participado/Disponivel para Participar：
                  <span style="color: #d75dff">
                    {{
                      getUserNum(item.userData || []) > item.progressPerUser
                        ? item.progressPerUser
                        : getUserNum(item.userData || [])
                    }}/{{ item.progressPerUser }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="message" v-if="showLoteriaMessage">
        <div class="message-text">
          {{ getProp(loteriaItem.propsList[0].propId).propName }}
        </div>
        <div
          class="message-img"
          :style="{
            top:
              getProp(loteriaItem.propsList[0].propId).propName == 'IPhone'
                ? '6rem'
                : '6.2rem',
          }"
        >
          <img
            :src="getImage(getProp(loteriaItem.propsList[0].propId).iconUrl)"
          />
        </div>
        <div class="stepper">
          <div
            class="stepper-color"
            :style="{
              width: `${
                (loteriaItem.curProgress / loteriaItem.totalProgress) * 100
              }%`,
            }"
          ></div>
          <div
            class="stepper-font"
            v-if="loteriaItem.curProgress < loteriaItem.totalProgress"
          >
            {{ loteriaItem.curProgress }} / {{ loteriaItem.totalProgress }}
          </div>
          <div class="stepper-font" v-else>Na lotaria...</div>
        </div>
        <h-img
          @click="openUser"
          class="message-wenhao"
          width=".6rem"
          type="local"
          src="loteriaImg/mark.png"
        />
        <div class="message-num">
          Última recompensa：
          <span>{{
            loteriaItem.recentAwardUser
              ? fomartName(loteriaItem.recentAwardUser.nickname)
              : ""
          }}</span>
        </div>
        <div class="message-num message-num2">
          Participado/Disponivel para Participar：
          <span>
            {{
              getUserNum(loteriaItem.userData || []) >
              loteriaItem.progressPerUser
                ? loteriaItem.progressPerUser
                : getUserNum(loteriaItem.userData || [])
            }}/{{ loteriaItem.progressPerUser }}
          </span>
        </div>
        <div class="btn">
          <van-button round color="#FFD746" @click="addNum(1)">+ 1</van-button>
          <van-button round color="#FFD746" @click="addNum(10)"
            >+ 10</van-button
          >
        </div>
        <div class="close" @click="closeItem">
          <h-img type="local" width="0.3rem" src="base/cha.png" />
        </div>
      </div>
      <div class="middle-btn">
        <van-button color="#42a5a6" :disabled="showBtn" @click="comprarBuy">Comprar</van-button>
        <van-button color="#42a5a6" :disabled="showBtn"  @click="compartilhar"
          >Compartilhar</van-button
        >
      </div>
      <div v-if="!showLoteriaMessage">
        <div class="table-box">
          <div class="title">Registro</div>
          <div class="coll-box">
            <div class="item item1">Tempo</div>
            <div class="item item2">Prêmio</div>
            <div class="item">Estado</div>
          </div>
          <div v-if="recordsList.length > 0">
            <div
              v-for="(item, index) in recordsList"
              class="coll-box"
              :key="index"
            >
              <div :title="`${fomartDate(item.updatedAt)}`" class="item3 item1">
                {{ fomartDate(item.updatedAt) }}
              </div>
              <div class="item3 item2">{{ item.awardName }}</div>
              <div class="item3" @click.stop="support(item.state)">
                {{
                  item.state == 1 ? "Support" : item.state == 2 ? "Emitido" : ""
                }}
              </div>
            </div>
          </div>
          <div v-else class="no-data">Opa! Ainda não há dados!</div>
          <!-- <h-table-paging
            :total="pageInfo.pageTotal"
            :page-size="pageInfo.pageSize"
            @on-previous="previous"
            @on-nextPage="nextPage"
          /> -->
        </div>
      </div>
    </div>
    <h-center-popup
      contentBgcolor="#244647"
      @on-close="
        () => {
          userLoteria = false;
        }
      "
      v-model="userLoteria"
      :z-index="1001"
      title="Explicacao"
    >
      <div class="userMessage">
        <p>
          Você participou
          <span>{{ getUserNum(loteriaItem.userData || []) }}</span> vezes, tendo
          <span
            >{{ getUserNum(loteriaItem.userData || []) }}/{{
              loteriaItem.totalProgress
            }}</span
          >
          de chance de ganhar este prêmio.
        </p>
        <p>
          Este prêmio aumenta em
          <span>{{ lotData.pointPrice }}</span>
          a chance de ganhar a cada
          <span>1</span> pontos consumidos
        </p>
      </div>
    </h-center-popup>
    <h-center-popup
      v-model="showVisible"
      :z-index="1001"
      contentBgcolor="#244647"
      title="Comprar"
    >
      <div class="pay-box">
        <p>
          Deseja gastar <span>{{ (lotData.amount / 10000 || 0) }}</span> R$ para
          comprar
          <span>{{ ((lotData.amount * lotData.pointPrice) / 10000) || 0 }}</span>
          pontos?
        </p>
        <div class="pay-box-bg">
          <h-img type="local" src="loteriaImg/icon_jinbi.png" />
        </div>
        <van-button color="#DC7B33" @click="beforeBuy">Confirmar</van-button>
        <div class="celar" @click="() => (showVisible = false)">Cancelar</div>
      </div>
    </h-center-popup>
    <!-- 支付列表 -->
    <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>
    <!-- 分享弹框 -->
    <h-center-popup
      v-model="modelValue"
      :z-index="1001"
      title="Share"
      contentBgcolor="#004f43"
      @on-close="closeShare"
    >
      <div class="share-box">
        <div class="label">1. Convide ammigos para ajudar com saques</div>
        <div class="box-top">
          <div class="icons">
            <h-img
              class="icon"
              v-for="(item, index) in shareList"
              :index="index"
              :src="item.icon"
              :key="index"
              @click="goLink(item.path, item.type)"
            />
          </div>
          <div class="share-link">
            <span>{{ shareUrl }}</span>
            <h-img
              src="turntable/icon_08.png"
              width="1.1rem"
              height=".9rem"
              @click="clipboard(shareUrl)"
            />
          </div>
        </div>
        <div class="label">2. Enviar convite para jogador aleatório ajudar</div>
        <div class="box-bottom">
          <div class="mobile">
            <span v-for="(item, index) in mobileList" :key="index">
              {{ item }}
            </span>
          </div>
        </div>
        <div class="send">
          <div
            class="block"
            @click="goLink(shareList[2].path, shareList[2].type)"
          >
            <span>
              Enviar Mensagem no
              <span style="color: #f3e615">WhatsAPP</span>
            </span>
            <h-img width="1.6rem" src="turntable/icon_03.png" />
          </div>
          <div class="block" @click="onSend">
            <h-img width="1rem" src="turntable/icon_07.png" />
            <span>Enviar Mensagem <span style="color: #f3e615">SMS</span></span>
          </div>
        </div>
      </div>
    </h-center-popup>
    <!-- 提示弹框 -->
    <h-center-popup
      v-model="showActivityVisible"
      :z-index="1001"
      contentBgcolor="#08563E"
      title="Descrição"
      @on-close="
        () => {
          showActivityVisible = false;
        }
      "
    >
      <div class="activity-box">
        <p>
          1、Todos os jogadores podem participar gratuitamente deste evento, e
          todos os usuários que participarem terão a chance de ganhar prêmios.
        </p>
        <p>
          2、Os prêmios podem ser ganhos através de pontos acumulados. Quanto
          mais pontos você usar para participar, maior a chance de ganhar.
        </p>
        <p>
          3、Você pode ganhar pontos convidando amigos. Os pontos adicionais
          podem ser obtidos quando os jogadores convidados recarregam, apostam
          ou sacam.
        </p>
        <p>
          4、Quando o progresso de participação de um prêmio atingir 100%, um
          prêmio será concedido até que todos os prêmios sejam distribuídos.
        </p>
        <p>
          5、Os vencedores de prêmios físicos devem entrar em contato com o
          serviço de atendimento ao cliente para receber o prêmio físico ou
          trocá-lo por dinheiro.
        </p>
        <p>
          6、Os vencedores de prêmios em dinheiro terão o valor enviado
          imediatamente para suas carteiras e poderão sacá-lo imediatamente.
        </p>
      </div>
    </h-center-popup>
    <!-- 客服 -->
    <div v-if="serviceShow" class="service-box">
      <div class="close">
        <img
          :src="getAssets('base/close.png')"
          @click.stop="closeIService"
          width="25"
        />
      </div>
      <iframe
        allow="fullscreen"
        id="iframe"
        :src="serviceSrc"
        style="width: 100%; height: 100vh; background-color: rgb(255, 255, 255)"
        frameborder="0"
      >
      </iframe>
    </div>
  </div>
</template>
<script setup lang='ts'>
import socketApi from "@/socket/socketApi";
import {
  ref,
  onMounted,
  computed,
  inject,
  reactive,
  onBeforeUnmount,
  watch,
} from "vue";
import {
  getImage,
  jumpOhterLink,
  clipboard,
  fomartDate,
  fomartName,
  getAssets,
} from "@/utils";
import { useUserStore } from "@/stores/modules/user";
import { toast, showLoading, closeLoading } from "@/utils/toast";
import { showConfirmDialog } from "vant";
import global from "@/socket/config/Global";
import useShare from "@/hooks/useShare";
import { useBaseStore } from "@/stores/modules/base";
import http from "@/https/index";

const baseStore = useBaseStore();
const sokcet: any = inject("socket");
const { shareMessage, shareList, shareUrl, goLink, onSendSms } = useShare();
const showPaymentVisible = ref(false);
const modelValue = ref(false);
const showActivityVisible = ref(false);
const payCurrent = ref<number>(0);
const showVisible = ref(false);
const mobileList = ref<Array<any>>([]);
const userStore = useUserStore();
const lotData = ref<any>({});
const usePoints = ref<number>(0);
const propsListValue = ref<Array<any>>([]);
const active = ref<number>(-1);
const payList = ref<Array<any>>([]);
const userLoteria = ref(false);
const pageInfo = reactive<PageProps>({
  pageIndex: 1,
  pageSize: 5,
  pageTotal: 0,
});
const showLoteriaMessage = ref(false);
const loteriaItem = ref<any>({});
const recordsList = ref<Array<any>>([]);
const serviceShow = ref(false);
const serviceSrc = ref("");
const closeIService = () => {
  serviceShow.value = false;
};

interface CountdownResult {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
  finished: boolean;
}
const times = ref<CountdownResult>({
  days: 0,
  hours: 0,
  minutes: 0,
  seconds: 0,
  finished: false,
});

const showBtn = computed(() => {
  return (
    times.value.days == 0 &&
    times.value.hours == 0 &&
    times.value.minutes == 0 &&
    times.value.seconds == 0
  );
});

const intervalId = ref();
const countdown = (data: any) => {
  clearInterval(intervalId.value);
  intervalId.value = null;
  if (!data.endAt || (new Date(data.startAt).getTime() > new Date().getTime()))
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      finished: false,
    };
  const targetDate = new Date(data.endAt);
  intervalId.value = setInterval(() => {
    const currentDate = new Date();
    const timeDifference = targetDate.getTime() - currentDate.getTime();
    if (timeDifference <= 0) {
      clearInterval(intervalId.value);
      times.value = {
        days: 0,
        hours: 0,
        minutes: 0,
        seconds: 0,
        finished: true,
      };
      return;
    }
    const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
    const hours = Math.floor(
      (timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    );
    const minutes = Math.floor(
      (timeDifference % (1000 * 60 * 60)) / (1000 * 60)
    );
    const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);

    times.value = {
      days: days,
      hours: hours,
      minutes: minutes,
      seconds: seconds,
      finished: false,
    };
  }, 1000); // 每秒更新一次
};
onBeforeUnmount(() => {
  clearInterval(intervalId.value);
});
const addNum = async (num: number) => {
  if (
    usePoints.value === 0 ||
    usePoints.value < num * loteriaItem.value.pointToProgress
  ) {
    toast("Pontos insuficientes");
    return;
  }
  showLoading();
  let apiData = {
    manageId: loteriaItem.value.manageId,
    taskId: loteriaItem.value._id,
    count: num,
  };
  const res = await http.pddAddProbability(apiData);
  closeLoading();
  if (res.code != 0) {
    toast(res.txt);
    return;
  }
  loteriaItem.value.curProgress += num;
  usePoints.value -= num * loteriaItem.value.pointToProgress;
  console.log("loteriaItem.value", loteriaItem.value);
  lotData.value.usedPoints += num * loteriaItem.value.pointToProgress;
  let uidData = loteriaItem.value.userData
    ? loteriaItem.value.userData.find(
        (item: any) => item.uid === userStore.userInfo.uid
      )
    : undefined;
  if (!uidData) {
    let obj = {
      uid: userStore.userInfo.uid,
      progress: num,
    };
    loteriaItem.value.userData.push(obj);
  } else {
    uidData.progress += num;
  }
};
const isNeedAccount = ref(false);
const cpf = ref('');
const holder = ref('');

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


const closeShare = async () => {
  await getPddTask();
  modelValue.value = false;
};

const openUser = () => {
  userLoteria.value = true;
};

const changeGift = (index: number, item: any) => {
  active.value = index;
  loteriaItem.value = { ...item };
  showLoteriaMessage.value = true;
};

const comprarBuy = () => {
  showVisible.value = true;
};

const compartilhar = () => {
  http.getPopularizePhones().then((res: any) => {
    if (res.code != 0) {
      toast(res.txt);
      return;
    }
    mobileList.value = res.data.phones;
    modelValue.value = true;
  });
};

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 getUserNum = computed(() => {
  return (data: any) => {
    if (data.length === 0) return 0;
    let uid = userStore.userInfo.uid;
    let uidData = data.find((item: any) => item.uid === uid);
    if (!uidData) return 0;
    return uidData.progress;
  };
});

const getProp = computed(() => {
  return (id: any) => {
    let data = propsListValue.value.find((item: any) => item._id == id);
    if (!data) return "";
    return data;
  };
});

const closeItem = async () => {
  await getPddTask();
  showLoteriaMessage.value = false;
  loteriaItem.value = {};
};

const pddAwardRecords = async () => {
  const res = await http.pddAwardRecords({
    pageIndex: pageInfo.pageIndex,
    pageSize: pageInfo.pageSize,
  });
  console.log(res, "res");
  if (res.code != 0) {
    toast(res.txt);
    return;
  }
  recordsList.value = res.data.rows;
  pageInfo.pageTotal = res.data.total;
};
const previous = async (page: number) => {
  pageInfo.pageIndex = page;
  await pddAwardRecords();
};

const support = (state: any) => {
  if (state === 1) {
    serviceSrc.value = baseStore.globalConfig.platformConfig.web_gm_tg;
    serviceShow.value = true;
  }
};

const nextPage = async (page: number) => {
  pageInfo.pageIndex = page;
  await pddAwardRecords();
};
const getPddTask = async () => {
  const res = await http.getPddTask();
  console.log(res, ".pointToProgress");
  if (res.code != 0) return;
  console.log(res, ".pointToProgress");
  lotData.value = { ...res.data } || {};
  usePoints.value =
    Number(lotData.value.invitePoints) +
    Number(lotData.value.buyPoints) -
    Number(lotData.value.usedPoints);
  let propsIDs = [];
  for (let i = 0; i < lotData.value.tasks.length; i++) {
    propsIDs.push(lotData.value.tasks[i].propsList[0].propId);
  }
  const propsData = await http.getPropsCache({ propIds: propsIDs });
  if (propsData.code != 0) return;
  propsListValue.value = [...propsData.data.props];
};

const buy = () => {
  if(isNeedAccount.value){
    if(holder.value === '' || cpf.value === ''){
    }
  }
  showLoading();
  let params = {
    manageId: lotData.value._id,
    method: payList.value[payCurrent.value].method[0],
    classValue: payList.value[payCurrent.value].value,
    holder:holder.value,
    cpf:cpf.value
  };
  http.pddPointsBuy(params).then((res: any) => {
    closeLoading();
    if (res.code !== 0) {
      showPaymentVisible.value = false;
      showVisible.value = false;
      toast(res.txt);
      return;
    }
    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);
      toast("Compra bem sucedida!");
      showPaymentVisible.value = false;
      showVisible.value = false;
      setTimeout(async () => {
        showLoading();
        await getPddTask();
        closeLoading();
      }, 3000);
    });
  });
};
onMounted(async () => {
  await getPddTask();
  // await pddAwardRecords();
  countdown(lotData.value);
});
</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>
