<template>
  <div class="page flex">
    <!-- 左侧内容 -->
    <div class="left">
      <!-- 头像 -->
      <div class="left-one border flex justify-between flex-wrap">
        <div class="avatar">
          <img
            :src="
              localStorageAccountInfo.avatarUrl
                ? localStorageAccountInfo.avatarUrl
                : defaultAvater
            "
            alt=""
          />
        </div>
        <div class="info">
          <div class="name" v-if="localStorageAccountInfo.name">
            {{ localStorageAccountInfo.name }}
          </div>
          <span>{{ localStorageAccountInfo.email }}</span>
          <div>
            <span class="password pointer" @click="showEditInfoDialog = true">{{
              $t("account.editInfo")
            }}</span>
            <span
              class="password pointer"
              style="margin-right: 10px"
              @click.stop="resetPassWord"
              >{{ $t("account.reSetPwd") }}</span
            >
          </div>
        </div>
      </div>
      <!-- 剩余次数 -->
      <div class="left-two border">
        <div v-if="lanChange == 'en'" class="number">
          Free for a limited time
        </div>
        <div v-if="lanChange == 'zh-cn'" class="number">限时免费</div>

        <div class="time">{{ $t("account.until") }} 2023/7/31</div>
        <div class="getMore pointer" @click="routerTo('/myStore')">
          {{ $t("account.getMore") }}
        </div>
      </div>
      <!-- 我的邀请码 -->
      <div class="left-three border flex justify-between">
        <!-- <div class="codeImg">
          <img ref="codeImgRef" :src="defaultAvater" alt="" />
        </div> -->
        <div class="mask">
          <div class="title">
            <el-icon><i-ep-Lock /></el-icon>
            {{ $t("createVideo.comingSoon") }}
          </div>
        </div>
        <div class="other">
          <div v-if="lanChange == 'en'">
            <span>Invite friends to get</span>
            <span class="bigWord">free</span>
            <span>video</span>
            <span class="bigWord">Generation!</span>
            <p class="myInviteCode">
              your Invitation code:
              <span id="InviteCodeId">{{ myInviteCode }}</span>
            </p>
          </div>

          <div v-if="lanChange == 'zh-cn'">
            <span>邀请更多好友</span>
            <span class="bigWord">免费</span>
            <span>生成视频！</span>
            <p class="myInviteCode">
              邀请码:
              <span id="InviteCodeId">{{ myInviteCode }}</span>
            </p>
          </div>

          <div class="btns">
            <span class="myBtn" @click="copyInviteCode">{{
              $t("account.copyCode")
            }}</span>
            <!-- <span class="myBtn" @click="DownloadCodeImg">{{
              $t("account.saveCode")
            }}</span> -->
          </div>
        </div>
      </div>
      <!-- 输入邀请码 !isUseState-->
      <div class="left-four border" v-if="false">
        <el-input
          class="w-50 m-2"
          v-model="inputCode"
          :placeholder="$t('account.inputCode')"
        />
        <span class="submitCodeBtn" @click="submitUseCode">{{
          $t("account.submit")
        }}</span>
      </div>
    </div>
    <!-- 右侧内容 -->
    <div class="right">
      <el-tabs type="border-card" class="tabs">
        <!-- ----------------------------- 1 -->
        <el-tab-pane :label="$t('account.buyHistory')">
          <div class="card scrolly">
            <div class="orderItem" v-for="item in 0" :key="item">
              <p>{{ $t("account.orderID") }}:123456</p>
              <div class="orderItem-content">
                <div class="orderCode"><img :src="defaultAvater" alt="" /></div>
                <div class="info">
                  <h5>疯狂星期{{ item }}</h5>
                  <p>{{ $t("account.price") }}：88$</p>
                  <p>{{ $t("account.date") }}：2023/5/2</p>
                </div>
                <div class="state">{{ $t("account.successed") }}</div>
              </div>
            </div>
            <!-- 无数据时 -->
            <div v-if="InviteList.length == 0" class="noList">
              <div class="title">
                {{ $t("account.noListOrder") }}
              </div>
            </div>
          </div>
        </el-tab-pane>
        <!-- ------------------------ 2 -->
        <el-tab-pane :label="$t('account.inviteHistory')">
          <div class="card scrolly card2">
            <div v-if="InviteList.length != 0">
              <div class="orderItem" v-for="item in InviteList" :key="item">
                <div class="orderItem-content">
                  <div class="orderCode">
                    <img
                      :src="item.avatarUrl ? item.avatarUrl : defaultAvater"
                      alt=""
                    />
                  </div>
                  <div class="info">
                    <h5 v-if="item.name">{{ item.name }}</h5>
                    <p>E-mail:{{ item.email }}</p>
                    <p>
                      {{ $t("account.date") }}：{{
                        dayjs(item.createDate).format("YYYY-MM-DD HH:mm:ss")
                      }}
                    </p>
                  </div>
                  <div class="state">{{ $t("account.msg1") }}</div>
                </div>
              </div>
            </div>
            <!-- 无数据时 -->
            <div v-if="InviteList.length == 0" class="noList">
              <div class="title">
                {{ $t("account.noListInvite") }}
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 修改个人信息弹窗 -->
    <el-dialog
      width="30%"
      class="editInfoDialog"
      v-model="showEditInfoDialog"
      :title="$t('account.editInfo')"
      destroy-on-close
      @close="closeInfoDialog"
    >
      <div class="LoadingBox" v-if="submitUserInfoLoading">
        <my-Loading-Icon v-if="submitUserInfoLoading"></my-Loading-Icon>
      </div>
      <el-row>
        <el-col :span="4"> {{ $t("public.avatar") }}: </el-col>
        <el-col :span="20">
          <div class="flex">
            <div class="dialogAvatar">
              <input accept="image/*" type="file" @change="chooseImg" />
              <div class="add">+</div>
              <img v-if="dialogAvatarUrl" :src="dialogAvatarUrl" alt="" />
            </div>
            <div class="compressLoadBox" v-if="compressImgLoadIng">
              <el-icon class="is-loading">
                <i-ep-Loading />
              </el-icon>
              <div class="tips">{{ $t("account.compressLoad") }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4"> {{ $t("public.username") }}: </el-col>
        <el-col :span="20">
          <el-input v-model="userNameinput" />
        </el-col>
      </el-row>
      <el-row>
        <div class="customBtn" @click="showEditInfoDialog = false">
          {{ $t("public.cancel") }}
        </div>
        <div class="customBtn" @click="submitUserInfo">
          {{ $t("public.confirm") }}
        </div>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
//#region 导入文件
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { userInfoModules } from "@/store/modules/userInfo";
import dayjs from "dayjs";
import imageCompression from "browser-image-compression"; //压缩图片插件
import {
  inviteCodeApi,
  useCodeApi,
  isUseApi,
  useCodeUserApi,
  updUserInfoApi,
} from "../../apis/myAccount";
import { awsImgUpload } from "@/apis/createVideo";
import defaultAvater from "../../assets/img/left-top-logo.png";

//#endregion ---------------------------

const { locale } = useI18n();
const lanChange = ref(locale); //国际化

const userInfoPinia = userInfoModules(); //pinia
// const userInfoPinia = localStorage.getItem("AccountInfo");//pinia
const localStorageAccountInfo = ref(
  JSON.parse(localStorage.getItem("AccountInfo"))
);

//#region 编辑个人信息
const showEditInfoDialog = ref(false); //控制弹窗显隐
const userNameinput = ref(null); //用户名输入框绑定
const dialogAvatarUrl = ref(null); //图片回显地址
const dialogAvatarData = ref(null); //图片上传数据
const infoDialogLoad = ref(false); //load效果
// 去重置密码
function resetPassWord() {
  router.push({ name: "login", query: { type: 4 } });
}
// 选择图片

const compressImgLoadIng = ref(false);
async function chooseImg(e) {
  try {
    if (e.target.files[0]) {
      dialogAvatarUrl.value = null;
      dialogAvatarData.value = null;
      compressImgLoadIng.value = true;
      // 压缩配置
      const options = {
        maxSizeMB: 2, // 最大压缩大小为 2MB
        useWebWorker: false, // 使用 Web Worker 进行压缩，提高性能
      };
      const compressedFile = await imageCompression(e.target.files[0], options);
      dialogAvatarUrl.value = URL.createObjectURL(compressedFile);
      dialogAvatarData.value = compressedFile;
      compressImgLoadIng.value = false;
      // 不压缩图片
      // dialogAvatarUrl.value = URL.createObjectURL(e.target.files[0]);
      // dialogAvatarData.value = e.target.files[0];
    } else {
      return;
    }
  } catch (error) {
    ElMessage.error(
      lanChange.value == "zh-cn"
        ? `上传失败,请稍后重试`
        : `Upload failure. Please try again later`
    );
    compressImgLoadIng.value = false;
  }
}
const submitUserInfoLoading = ref(false);
// 上传编辑信息
async function submitUserInfo() {
  submitUserInfoLoading.value = true;
  if (dialogAvatarData.value) {
    let formData = new FormData();
    const timestamp = Date.now();
    formData.append("file", dialogAvatarData.value, timestamp + ".png");
    const res1 = await awsImgUpload(formData);
    const data = {
      name: userNameinput.value,
      avatarUrl: res1.data.url,
    };

    try {
      const res2 = await updUserInfoApi(data);
      ElMessage.success(
        lanChange.value == "zh-cn" ? `修改成功` : `Modified successfully`
      );
      await userInfoPinia.getUserInfo();
      showEditInfoDialog.value = false;
      submitUserInfoLoading.value = false;
      router.go(0);
    } catch (error) {
      ElMessage.error(
        lanChange.value == "zh-cn"
          ? `修改失败,请稍后重试`
          : `The modification failed. Please try again later`
      );
      submitUserInfoLoading.value = false;
    }
  } else {
    const data = {
      name: userNameinput.value,
    };
    try {
      const res2 = await updUserInfoApi(data);
      ElMessage.success(
        lanChange.value == "zh-cn" ? `修改成功` : `Modified successfully`
      );
      await userInfoPinia.getUserInfo();
      showEditInfoDialog.value = false;
      submitUserInfoLoading.value = false;
      router.go(0);
    } catch (error) {
      ElMessage.error(
        lanChange.value == "zh-cn"
          ? `修改失败,请稍后重试`
          : `The modification failed. Please try again later`
      );
      submitUserInfoLoading.value = false;
    }
  }
}
// 关闭弹窗清空
function closeInfoDialog() {
  userNameinput.value = localStorageAccountInfo.value.name;
  dialogAvatarUrl.value = localStorageAccountInfo.value.avatarUrl;
  dialogAvatarData.value = null;
}
//#endregion ---------------------------

//#region 二维码邀请码区域
const myInviteCode = ref(null); //我的邀请码
async function getMyInviteCode() {
  const res = await inviteCodeApi();
  myInviteCode.value = res.data;
}
// 点击复制邀请码
function copyInviteCode() {
  const inviteCode = document.getElementById("InviteCodeId").innerText;
  navigator.clipboard
    .writeText(inviteCode)
    .then(() => {
      ElMessage.success(
        lanChange.value == "zh-cn"
          ? "邀请码已复制到剪贴板"
          : `The invitation code has been copied to the clipboard`
      );
    })
    .catch((error) => {
      ElMessage.error(
        lanChange.value == "zh-cn"
          ? "无法复制邀请码:"
          : `Unable to copy invitation code`
      );
    });
}
// 下载二维码图片
const codeImgRef = ref();
function DownloadCodeImg() {
  const link = document.createElement("a");
  link.href = codeImgRef.value.src;
  link.download = "image.jpg";
  link.click();
}
//#endregion

//#region 输入邀请码区
const inputCode = ref(""); // 邀请码输入框内容
const isUseState = ref(false); //用户是否填写过过邀请码
// 提交邀请码
async function submitUseCode() {
  try {
    const res = await useCodeApi(inputCode.value);
    console.log(res.code);
    if (res.code == 200) {
      ElMessage.success(
        lanChange.value == "zh-cn"
          ? `提交邀请码成功`
          : `The invitation code was submitted successfully`
      );
    }
    if (res.code == 1001) {
      ElMessage.error(
        lanChange.value == "zh-cn"
          ? `不能使用自己的邀请码`
          : `You cannot use your own invitation code`
      );
    } else {
      ElMessage.error(
        lanChange.value == "zh-cn"
          ? `提交邀请码成失败`
          : `Failed to submit the invitation code`
      );
    }
    await getIsUseState();
  } catch (error) {
    console.log(error);
  }
}
// 查询是否使用过邀请码
async function getIsUseState() {
  const res = await isUseApi();
  isUseState.value = res.data;
}
//#endregion ---------------------------

//#region 右侧列表
const InviteList = ref([]); //邀请列表

async function getInviteList() {
  const res = await useCodeUserApi();
  InviteList.value = res.data;
}

//#endregion ---------------------------

//#region 页面初始化
onMounted(() => {
  getMyInviteCode(); // 查询用户的邀请码
  getIsUseState(); //查询是否使用过邀请码
  getInviteList();

  userNameinput.value = localStorageAccountInfo.value.name;
  dialogAvatarUrl.value = localStorageAccountInfo.value.avatarUrl;
});
//#endregion ---------------------------

//#region
watch(localStorageAccountInfo.value, (newValue) => {
  console.log("LocalStorage 的值发生了变化:", newValue);
});
//#endregion ---------------------------

//#region

//#endregion ---------------------------
const router = useRouter();
function routerTo(url) {
  router.push(url);
}
</script>

<style lang="scss" scoped>
.page {
  height: calc(100vh - 80px);
  // height: calc(100vh - 84px);
  background-color: #fff;
  border-radius: 25px 0 0;
}

.left {
  width: 39%;
  height: 100%;

  padding: 30px;
  .border {
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #000;
    border-radius: 15px;
  }

  &-one {
    .avatar {
      position: relative;
      width: 80px;
      height: 80px;
      margin-right: 10px;
      border-radius: 50%;
      border: 1px solid #ccc;
      overflow: hidden;
      img {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .info {
      flex: 1;

      .name {
        height: 30px;
        margin-top: 10px;
        font-size: 20px;
      }

      .password {
        display: inline-block;
        float: right;
        padding: 2px 8px;
        border: 1px solid #000;
        border-radius: 5px;
        cursor: pointer;
        transition: all 0.3s;
        &:hover {
          color: #fff;
          background-color: #000;
        }
      }
    }
  }

  &-two {
    position: relative;
    // height: 80px;
    text-align: center;
    overflow: hidden;

    .number {
      font-size: 30px;
      font-weight: 700;
    }

    .time {
      // position: absolute;
      // right: 90px;
    }

    .getMore {
      position: absolute;
      display: flex;
      align-items: center;
      justify-content: space-around;
      top: 0px;
      right: 0px;
      padding: 5px;
      width: 80px;
      // height: 80px;
      height: 100%;
      // line-height: 70px;
      text-align: center;
      background-color: #000;
      color: #fff;
      font-size: 14px;
      transition: all 0.3s;
      &:hover {
        background-color: #15d1b8;
        color: #fff;
      }
    }
  }

  &-three {
    position: relative;
    height: 200px;
    overflow: hidden;
    // &:hover {
    //   .mask {
    //     display: block;
    //   }
    // }
    .mask {
      position: absolute;
      top: 0;
      left: 0;
      // display: none;
      width: 100%;
      height: 100%;
      line-height: 780px;
      font-size: 120px;
      font-weight: 900;
      text-align: center;
      background-color: rgba(0, 0, 0, 0.3);
      z-index: 9;
      .title {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 30px;
        text-align: center;
        line-height: 80px;
        background-image: -webkit-linear-gradient(
          left,
          #4b61dc,
          #15d1b8 25%,
          #4b61dc 50%,
          #15d1b8 75%,
          #4b61dc
        ) !important;
        -webkit-text-fill-color: transparent !important;
        -webkit-background-clip: text !important;
        background-clip: text !important;
        -webkit-background-size: 200% 100% !important;
        background-size: 200% 100% !important;
        .el-icon {
          padding-top: -3px;
          color: #15d1b8;
          vertical-align: middle;
          font-size: 25px;
        }
      }
    }
    .codeImg {
      position: relative;
      padding: 10px;
      width: 120px;
      height: 120px;
      margin-right: 10px;
      border: 1px solid #ccc;
      border-radius: 10px;
      // background-color: red;
      img {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        width: 100px;
        max-height: 100px;
      }
    }

    .other {
      position: relative;
      flex: 1;

      .btns {
        position: absolute;
        bottom: 10px;
        // padding: 0 80px;
        display: flex;
        justify-content: space-evenly;
        width: 100%;
        .myBtn {
          margin-right: 10px;
          cursor: pointer;
          transition: all 0.3s;
          &:hover {
            color: #fff;
            background-color: #000;
          }
        }
      }
      .myInviteCode {
        margin-top: 20px;
      }
    }
  }
  &-four {
    .el-input {
      width: 80%;
    }
    :deep(.el-input__wrapper.is-focus) {
      box-shadow: 0 0 0 1px #000 !important;
    }

    // padding: 30px 50px !important;
    div {
      margin-top: 5px;
      height: 40px;
    }
    .submitCodeBtn {
      display: inline-block;

      width: 15%;
      padding: 10px 15px;
      color: #000;
      border-radius: 10px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s;
      &:hover {
        color: #fff;
        background-color: #000;
      }
    }
  }
}

.right {
  background-color: #f1f2f6;
  padding: 30px;
  width: 61%;
  height: 100%;
  // height: 95%;
  border-radius: 30px 0 0 0;
  overflow: hidden;
  // element组件样式
  :deep(.el-tabs--border-card) {
    font-size: 20px;
    border: none;
  }

  .tabs {
    // height: 760px;
    height: 100%;
    padding: 20px;
    border-radius: 20px;
    overflow: hidden;
    .noList {
      .title {
        font-size: 30px;
        text-align: center;
        margin-top: 100px;
        background-image: -webkit-linear-gradient(
          left,
          #4b61dc,
          #15d1b8 25%,
          #4b61dc 50%,
          #15d1b8 75%,
          #4b61dc
        ) !important;
        -webkit-text-fill-color: transparent !important;
        -webkit-background-clip: text !important;
        background-clip: text !important;
        -webkit-background-size: 200% 100% !important;
        background-size: 200% 100% !important;
      }
    }
    .card {
      // height: 100%;
      height: 740px;
      padding: 10px;
      // height: 79vh;
      .orderItem {
        width: 100%;
        height: 110px;
        padding: 8px;
        margin-bottom: 10px;
        border: 1px solid #000;
        border-radius: 5px;

        p {
          font-size: 12px;
        }

        &-content {
          display: flex;
          width: 100%;
          // justify-content: space-between;
          .orderCode {
            position: relative;
            width: 70px;
            height: 70px;
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 5px;
            overflow: hidden;

            img {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              max-width: 60px;
              max-height: 60px;
            }
          }

          .info {
            // width: 50%;
            flex: 1;
            margin-left: 10px;

            h5 {
              margin: 0;
            }

            p {
              margin-top: 5px;
            }
          }

          .state {
            margin-right: 30px;
          }
        }
      }
    }

    .card2 {
      .orderItem {
        padding: 20px;

        &-content {
          .orderCode {
            position: relative;
            border: 1px solid #ccc;
            border-radius: 50%;
            overflow: hidden;
            img {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              max-width: 100%;
              max-height: 100%;
            }
          }

          .state {
            font-size: 14px;
            line-height: 60px;
          }
        }
      }
    }

    :deep(.el-tabs__item.is-active) {
      color: #fff;
      background-color: #000;
    }

    :deep(.el-tabs__nav) {
      width: 100%;
    }

    :deep(.el-tabs__item) {
      width: 34%;
    }

    :deep(.el-tabs__item:hover) {
      color: #909393;
    }

    :deep(.el-tabs__content) {
      height: 760px;
      // height: calc(100% - 60px);
      padding: 0;
    }
  }
}

.editInfoDialog {
  position: relative;
  overflow: hidden;
  .LoadingBox {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
    opacity: 0.8;
    border-radius: 30px;
    padding-top: 150px;
    background-color: #ccc;
  }
  .el-row {
    display: flex;
    justify-content: space-evenly;
  }
  .el-col {
    margin-bottom: 10px;
    text-align: right;
    line-height: 32px;
    padding-right: 20px;
  }
  .dialogAvatar {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: rgba(204, 204, 204, 0.2);
    border-radius: 30px;
    overflow: hidden;
    &:hover {
      img {
        z-index: 0;
      }
      .add {
        background-color: rgba(0, 0, 0, 0.2);
      }
    }
    input {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
      z-index: 3;
      cursor: pointer;
    }
    .add {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 1;
      text-align: center;
      line-height: 200px;
      font-size: 50px;
      font-weight: 700;
      color: #000;
      transition: all 0.3s;
    }
    img {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 10px;
      max-width: 100%;
      max-height: 100%;
      z-index: 2;
      transition: all 0.3s;
    }
  }
  .compressLoadBox {
    // align-items: center;
    padding-top: 40px;
    text-align: center;
    flex: 1;
    .el-icon {
      font-size: 20px;
      color: #909393;
    }
    .tips {
      // display: inline-block;
      flex: 1;
      line-height: 50px;
    }
  }
}
// 公共类名
.bigWord {
  font-size: 30px;
  font-weight: 700;
  margin: 0 10px;
}
</style>
