<template>
  <div class="personal">
    <div class="top">
      <div class="left">
        <div class="container" @click="openHeader">
          <img class="avatar" :src="getImage(userStore.userInfo.headUrl)" />
          <div class="vip">VIP {{ currentLevel.lv }}</div>
          <h-img
            class="change-box"
            width=".5rem"
            type="local"
            src="base/qiehuan_icon.png"
          />
        </div>
      </div>
      <div class="right">
        <div class="info">
          <div class="nickname">
            <span>{{ userNickName }}</span>
            <h-img
              style="margin-left: 0.2rem"
              width=".35rem"
              @click.stop="modifyUserName"
              type="local"
              src="base/icon_bianji.png"
            />
          </div>
          <div class="id">
            ID:
            <span style="margin-left: 0.1rem">
              {{ userStore.userInfo.uid }}
            </span>
            <h-img
              style="margin-left: 0.2rem"
              width=".35rem"
              src="perfil/icon_fuzhi.png"
              @click.stop="clipboard(`${userStore.userInfo.uid}`)"
            />
          </div>
          <div class="mobile">
            Teb:
            <span v-if="userStore.userInfo.mobile">
              {{
                userStore.userInfo.mobile
                  ? userStore.userInfo.mobile
                  : "No ligar"
              }}
            </span>
            <van-button
              size="mini"
              color="#154846"
              v-else
              @click="goPage('/bind-phone')"
            >
              Bind
            </van-button>
            <h-img
              style="margin-left: 0.2rem"
              width=".35rem"
              @click.stop="modifyUserTeb"
              type="local"
              src="base/icon_bianji.png"
            />
          </div>
        </div>
        <div class="icons">
          <h-img
            width="0.6rem"
            src="perfil/icon_youxiang.png"
            @click.stop="goPage('/email')"
          />
          <h-img
            width="0.6rem"
            src="perfil/icon_shezhi.png"
            @click.stop="goPage('/setting')"
          />
          <div class="red-box" v-show="emailShow != 0"></div>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="bottom-left">
        <div class="block flex-ct" @click="goPage('/deposit')">
          <h-img width=".5rem" type="local" src="base/JB_R$.png" />
          <span>
            R$
            {{
              formatDigit(Number(userStore.userInfo.coins / 10000).toFixed(2))
            }}
          </span>
        </div>
        <div class="block flex-ct">
          <div
            @click.stop="openExchangeSpecies"
            style="display: flex; align-items: center"
          >
            <h-img width=".5rem" type="local" src="base/JB_zs.png" />
            <span>
              {{
                formatDigit(
                  Number(userStore.userInfo.diamond / 10000 || 0).toFixed(2)
                )
              }}
            </span>
            <h-img
              style="margin-left: 0.4rem"
              width=".4rem"
              type="local"
              src="base/duihuan.png"
            />
            <h-img width=".4rem" type="local" src="base/JB_R$.png" />
          </div>
          <h-img
            width=".4rem"
            style="margin-left: 0.3rem"
            type="local"
            src="base/icon_wenhao.png"
            @click.stop="openShowSpeciesWay"
          />
        </div>
      </div>
      <div class="flex-ct" @click="renew">
        <h-img width=".6rem" type="local" src="base/sx_icon.png" />
      </div>
    </div>
    <!-- 修改电话 -->
    <h-center-popup
      v-model="showUerTeb"
      contentBgcolor="#002E2C"
      :title="title"
    >
      <div class="teb-box" v-if="!showPrompt && !submitCodeShow">
        <div class="teb-box-phone">
          <span>Teb:</span>{{ userStore.userInfo.mobile }}
        </div>
        <div class="teb-box-code">
          <span>código:</span>
          <h-input
            v-model="tebCode"
            :center="true"
            color="#FFF044"
            background="#1B2923"
            placeholder="código"
          />
          <van-button
            color="#00D100"
            @click="getCode(userStore.userInfo.mobile)"
          >
            Enviar
          </van-button>
        </div>
        <div>
          <van-button color="#1A795B" @click="submitUserTeb">
            Confirmar
          </van-button>
        </div>
      </div>
      <div class="phonePsw-box" v-if="submitCodeShow">
        <div class="phonePsw-box-code">
          <span>Móvel:</span>
          <h-input
            v-model="changeTebFrom.mobile"
            :center="true"
            color="#FFF044"
            type="mobile"
            background="#1B2923"
            placeholder="Por favor,enter"
          />
        </div>
        <div class="phonePsw-box-code">
          <span>Senha:</span>
          <h-input
            type="password"
            v-model="changeTebFrom.pwd"
            :center="true"
            color="#FFF044"
            background="#1B2923"
            placeholder="Por favor,enter"
          />
        </div>
        <div class="phonePsw-box-code">
          <span>código:</span>
          <h-input
            v-model="changeTebFrom.vCode"
            :center="true"
            class="code-box"
            color="#FFF044"
            background="#1B2923"
            placeholder="código"
          />
          <van-button
            color="#00D100"
            @click="getCode(`55${changeTebFrom.mobile}`)"
          >
            Enviar
          </van-button>
        </div>
        <div>
          <van-button color="#1A795B" @click="submitFrom">
            Confirmar
          </van-button>
        </div>
      </div>
      <div v-if="showPrompt" class="pro-box">
        <p>Verificação de telefone bem sucedida</p>
        <p class="red">você precisa mudar para um novo número de telefone?</p>
        <div class="btn-box">
          <van-button color="#1A795B" @click="nextSubmit">
            Confirmar
          </van-button>
          <van-button color="#00D100" @click="clearAll"> Cancelar </van-button>
        </div>
      </div>
    </h-center-popup>
    <!-- 修改名称 -->
    <h-center-popup
      v-model="showUerName"
      contentBgcolor="#002E2C"
      title="nickName"
    >
      <div>
        <div style="font-size: 0.38rem; color: #fff">
          Por favor, introduz seu nome
        </div>
        <h-input
          v-model="userNameValue"
          :center="true"
          color="#FFF044"
          :maxlength="12"
          background="#1B2923"
          placeholder="Por favor nikeName"
        />
        <van-button
          loading-text="loading..."
          :loading="loadingUserName"
          color="#1A795B"
          @click="submitUserName"
        >
          Confirmar
        </van-button>
      </div>
    </h-center-popup>
    <!-- 钻石获取方式 -->
    <h-center-popup
      v-model="showSpeciesWay"
      title="Como conseguir diamantes"
      contentBgcolor="#002E2C"
      class="speciesWay"
    >
      <div class="speciesWay-content">
        <p>1.Depósito.</p>
        <p>2.Obtido em atividades de missão de jogo.</p>
        <p>3.Obtenha-o fazendo login todos os dias.</p>
        <p>4.Para mais formas, fique atento às atividades do jogo.</p>
      </div>
    </h-center-popup>
    <!-- 兑换钻石 -->
    <h-center-popup
      class="species"
      v-model="showSpecies"
      title="Conversão de bónus"
      contentBgcolor="#002E2C"
    >
      <div class="species-box flex-cl">
        <h2>
          Quando você perder em qualquer jogo, o diamante transferirá
          {{ baseStore.globalConfig.platformConfig.pay_rebate_percent }}% de
          compensação em dinheiro
        </h2>
        <div class="species-box-input flex-sb">
          <div class="flex-cl">
            <p>Diamante</p>
            <h-img class="icon" src="base/JB_zs.png" />
            <div class="num">{{ formatDigit(Number(diamond).toFixed(2)) }}</div>
          </div>
          <div class="flex-ct">
            <h-img src="base/jt_01.png" />
          </div>
          <div class="flex-cl">
            <p>Moedas</p>
            <h-img class="icon" src="base/JB_R$.png" />
            <div class="num">{{ formatDigit(Number(coins / 10000).toFixed(2)) }}</div>
          </div>
        </div>
        <van-button
          size="large"
          color="#42866b"
          :disabled="!amount"
          @click="submit"
        >
          Troca
        </van-button>
      </div>
    </h-center-popup>
    <!-- 更换头像 -->
    <h-center-popup
      v-model="showAvatar"
      title="Change your avatar"
      :lockScroll="false"
    >
      <div class="avatar">
        <div
          class="avatar-box"
          :class="{ active: activeHeader === index }"
          v-for="(item, index) in headList"
          :key="item._id"
          @click="selectedHeader(item._id, index)"
        >
          <img
            ref="iconRef"
            :src="getImage(item.iconUrl)"
            @error.once="moveErrorImg"
          />
        </div>
      </div>
      <div class="btn">
        <van-button
          color="#57B286"
          :disabled="headerShowBtn"
          loading-text="loading..."
          :loading="loadingBtn"
          @click="submitHeader"
        >
          confirmar
        </van-button>
      </div>
    </h-center-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watchEffect, reactive } from "vue";
import { clipboard, formatDigit, getImage, getAssets } from "@/utils";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { closeLoading, showLoading, toast } from "@/utils/toast";
import useUserLevel from "@/hooks/useUserLevel";
import socketApi from "@/socket/socketApi";
import https from "@/https";
import { useBaseStore } from "@/stores/modules/base";
const { currentLevel } = useUserLevel();

const baseStore = useBaseStore();
const title = ref("Validar");

const router = useRouter();

const headList = ref<Array<any>>([]);

const headerShowBtn = ref<boolean>(true);

const loadingBtn = ref<boolean>(false);

const showPrompt = ref<boolean>(false);

const userStore = useUserStore();
// 头像显示
const showAvatar = ref(false);
// 兑换钻石
const showSpecies = ref(false);

const showSpeciesWay = ref(false);

const showUerName = ref(false);

// 修改手机号
const showUerTeb = ref(false);
const userNameValue = ref("");
const tebCode = ref("");
const submitCodeShow = ref(false);
const loadingUserName = ref(false);
const changeTebFrom = reactive({
  mobile: "",
  pwd: "",
  vCode: "",
});
// 金币
const coins = ref<number>(0);
// 钻石
const diamond = ref<number>(0);
// 获取邮件 是否未读
const emailShow = ref<number>(0);
const userNickName = computed(() => {
  return unescape(userStore.userInfo.nickname);
});
const activeHeader = ref<number>(-1);

const _id = ref<any>("");

watchEffect(() => {
  if (userStore.newMail) {
    emailShow.value = userStore.newMail;
  }
});

const renew = async () => {
  console.log('bbb');
  showLoading();
  await userStore.getUserInfo();
  console.log('aaa');
  
  closeLoading();
};
const modifyUserName = () => {
  showUerName.value = true;
  userNameValue.value = unescape(userStore.userInfo.nickname);
};
const modifyUserTeb = () => {
  showUerTeb.value = true;
  submitCodeShow.value = userStore.userInfo.mobile ? false : true;
  changeTebFrom.mobile = "";
  changeTebFrom.pwd = "";
  changeTebFrom.vCode = "";
  tebCode.value = "";
};

const getCode = async (phone: any) => {
  if (!phone) return toast("Por favor, introduza o número");
  const res = await https.mobileCode({ mobile: phone });
  if (res.code != 0) return toast(res.txt);
  toast("Enviar bem sucedido");
};

const submitUserTeb = async () => {
  if (!tebCode.value) return toast("Por favor, introduza o código");
  const res = await https.verifyMobile({ vCode: tebCode.value });
  if (res.code != 0) return toast(res.txt);
  // submitCodeShow.value = true;
  tebCode.value = "";
  title.value = "Prompt";
  showPrompt.value = true;
};
const nextSubmit = () => {
  title.value = "Mudança";
  submitCodeShow.value = true;
  showPrompt.value = false;
};
const clearAll = async () => {
  showUerTeb.value = false;
  showLoading();
  title.value = "Validar";
  submitCodeShow.value = false;
  showPrompt.value = false;
  await userStore.getUserInfo();
  closeLoading();
};
const submitFrom = async () => {
  if (!changeTebFrom.mobile || !changeTebFrom.pwd || !changeTebFrom.vCode)
    return toast("Por favor, completa a informação");
  showLoading();
  const res = await https.bindMobile({
    mobile: `55${changeTebFrom.mobile}`,
    pwd: changeTebFrom.pwd,
    vCode: changeTebFrom.vCode,
  });

  if (res.code != 0) {
    closeLoading();
    return toast(res.txt);
  }
  title.value = "Validar";
  submitCodeShow.value = false;
  showPrompt.value = false;
  showUerTeb.value = false;
  await userStore.getUserInfo();
  closeLoading();
};
const submitUserName = async () => {
  if (
    escape(userNameValue.value).length < 2 ||
    userNameValue.value.length < 2
  ) {
    toast("Pelo menos dois caracteres");
    return;
  }
  if (
    escape(userNameValue.value).length > 36 ||
    userNameValue.value.length > 8
  ) {
    toast("Carácter demasiado longo");
    return;
  }
  loadingUserName.value = true;
  const res = await https.modifyNickName({ nickname: userNameValue.value });
  loadingUserName.value = false;
  if (res.code != 0) return toast(res.txt);
  await userStore.getUserInfo();
  showUerName.value = false;
  toast("success");
};
onMounted(async () => {
  await checkNewMail();
});
const selectedHeader = async (propId: any, index: number) => {
  if (index === activeHeader.value) {
    activeHeader.value = -1;
    headerShowBtn.value = true;
    _id.value = "";
    return;
  }
  activeHeader.value = index;
  headerShowBtn.value = false;
  _id.value = propId;
};
const submitHeader = async () => {
  loadingBtn.value = true;
  const res = await https.modifyHead({ propId: _id.value });
  console.log(res);
  loadingBtn.value = false;
  activeHeader.value = -1;
  headerShowBtn.value = true;
  _id.value = "";
  if (res.code !== 0) {
    toast(res.txt);
    return;
  }
  showAvatar.value = false;
  showLoading();
  await userStore.getUserInfo();
  closeLoading();
  toast("success");
};
const openHeader = async () => {
  showLoading();
  if (headList.value.length > 0) {
    closeLoading();
    showAvatar.value = true;
    return;
  }
  const res = await https.getHeadList();
  console.log(res);
  if (res.code !== 0) return closeLoading();
  headList.value = [...res.data.rows];
  closeLoading();
  showAvatar.value = true;
};

const moveErrorImg = (event: any) => {
  event.currentTarget.src = getAssets("base/loading.png");
  return true;
};

const checkNewMail = async () => {
  const res = await https.checkNewMail();
  if (res.code == 0) {
    emailShow.value = res.data.newMail;
  }
};
const goPage = (path: string) => {
  router.push(path);
};

// 钻石兑换金币提交
const submit = () => {
  showLoading();
  https.diamondConvert().then((res: any) => {
    if (res.code !== 0) {
      toast(res.txt);
      closeLoading();
      return;
    }
    closeLoading();
    userStore.getUserInfo();
    showSpecies.value = false;
  });
};
const openExchangeSpecies = () => {
  coins.value = userStore.userInfo.balance || 0;
  diamond.value = userStore.userInfo.diamond / 10000 || 0;
  showSpecies.value = true;
};

const openShowSpeciesWay = () => {
  showSpeciesWay.value = true;
};

const amount = computed(() => {
  return coins.value && diamond.value;
});
</script>

<style lang="scss" scoped>
.personal {
  width: 100%;
  background: url("https://cdn.18n.com/perfil/vip_dk.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  height: 3.8rem;
  width: 100%;
  display: flex;
  flex-direction: column;

  .top {
    flex: 1;
    display: flex;
    padding: 0 0.2rem;
    .left {
      width: 1.7rem;
      position: relative;
      .container {
        font-size: 0.4rem;
        position: absolute;
        display: flex;
        flex-direction: column;
        top: 0.15rem;
        left: 0;
        text-align: center;
        .change-box {
          position: absolute;
          right: -5%;
          bottom: 30%;
        }
        .avatar {
          width: 1.5rem;
          height: 1.5rem;
          border-radius: 50%;
        }
        .vip {
          border-radius: 1rem;
          background: #095a48;
          width: 95%;
          margin: 0 auto;
          font-size: 0.3rem;
          font-weight: bold;
          color: #fffd2c;
          line-height: 0.39rem;
        }
      }
    }
    .right {
      flex: 1;
      display: flex;
      justify-content: space-between;
      .info {
        font-size: 0.4rem;
        color: #EDF5D4;
        font-weight: bold;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        padding: .2rem 0;
        .nickname {
          font-size: 0.4rem;
          text-align: left;
        }
        .id {
          display: flex;
          align-items: center;
        }
        .mobile {
          display: flex;
          align-items: center;

          .van-button {
            width: 1.3rem;
            margin-left: 0.1rem;
            :deep(.van-button__text:first-child) {
              color: #f3e615;
              font-weight: bold;
            }
          }
        }
      }
      .icons {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        position: relative;
        padding: 0.27rem 0;
        .red-box {
          width: 0.18rem;
          height: 0.18rem;
          background-color: red;
          border-radius: 50%;
          position: absolute;
          right: 0;
          top: 0.26rem;
        }
      }
    }
  }
  .bottom {
    display: flex;
    justify-content: space-between;
    height: 1.4rem;
    padding: 0 0.2rem;
    &-left {
      display: flex;
      justify-content: space-around;
      flex-direction: column;
      align-items: flex-start;
    }
    .block {
      justify-content: left;
      span {
        font-size: 0.4rem;
        margin-left: 0.2rem;
        color: #fffd2c;
        font-weight: bold;
      }
    }
  }
  .speciesWay {
    &-content {
      padding: 0.3rem;
      font-size: 0.4rem;
      color: $font-text4;
      text-align: left;
      line-height: 0.8rem;
    }
  }
  .species {
    &-box {
      padding: 0.2rem;
      background-color: #002e2c;
      h2 {
        font-size: 0.4rem;
        color: $font-text3;
        text-align: center;
      }

      .reset {
        font-size: 0.5rem;
        color: #949393;
      }
      &-input {
        background-color: #007163;
        padding: 0.5rem 0.2rem;
        width: 96%;
        position: relative;
        border-radius: $border-radius;
        margin: 0.4rem 0 0.8rem 0;
        .flex-cl {
          justify-content: space-between;
          height: 100%;
          p {
            font-size: 0.3rem;
            color: $font-text4;
            font-weight: 600;
            text-align: center;
            width: 2.5rem;
          }
        }
        .flex-ct {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
        .icon {
          margin: 0.1rem 0;
        }
        .num {
          color: $font-text1;
          font-size: 0.4rem;
          background: #10231d;
          width: 100%;
          text-align: center;
          border-radius: 0.1rem;
          padding: 0.05rem 0;
          @extend .blod;
        }
      }
    }
  }
  .pro-box {
    display: flex;
    text-align: left;
    flex-direction: column;
    font-size: 0.4rem;
    padding: 0.3rem;
    color: #fff;
    .red {
      color: red;
    }
    .btn-box {
      display: flex;
      justify-content: space-around;
      margin: 0.3rem;
    }
  }
  .phonePsw-box {
    font-size: 0.4rem;
    color: #fff;
    padding: 0.2rem 0.5rem;
    > div {
      padding: 0.1rem 0;
    }
    &-code {
      display: flex;
      align-items: center;
      span {
        text-align: right;
        width: 2rem;
        margin-right: 0.3rem;
        font-size: 0.5rem;
        font-weight: 600;
      }
      .code-box {
        width: 4rem;
        margin-right: 0.3rem;
      }
    }
  }
  .teb-box {
    font-size: 0.4rem;
    color: #fff;
    padding: 0.2rem 0.5rem;
    > div {
      padding: 0.3rem 0;
    }
    &-phone {
      text-align: left;
      padding: 0.2rem 0;
      display: flex;
      align-items: center;
      span {
        text-align: right;
        width: 2rem;
        margin-right: 0.3rem;
        font-size: 0.5rem;
        font-weight: 600;
      }
    }
    &-code {
      display: flex;
      align-items: center;
      span {
        text-align: right;
        width: 2rem;
        margin-right: 0.3rem;
        font-size: 0.5rem;
        font-weight: 600;
      }
      .h-input {
        width: 3rem;
        margin-right: 0.3rem;
      }
    }
  }
}
.avatar {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 0.3rem;
  max-height: 10rem;
  overflow-y: auto;
  &::-webkit-scrollbar {
    width: 0;
  }
  &-box {
    border-radius: 50%;
    overflow: hidden;
    display: flex;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .active {
    border: 3px solid #57b286;
  }
}
.btn {
  color: #fff;
  margin-top: 0.2rem;
  .van-button {
    width: 100%;
    font-size: 0.4rem;
  }
}
</style>
