<template>
  <view class="page">
    <!-- 毛玻璃 -->
    <view class="glass">
      <image src="../../assets/img/homeImg.jpg" mode="scaleToFill" />
    </view>
    <!-- 用户信息 -->
    <view class="userInfoBox" v-show="userInfoModulesPinia.token">
      <view class="phone">用户:{{ userInfoModulesPinia.phone }}</view>
      <view class="createTimes"
        >剩余次数:{{ userInfoModulesPinia.createTimes }}次</view
      >
      <view class="loginOut" @click="loginOut">退出登录</view>
    </view>
    <!-- 展示图 -->
    <view class="showImgBox imgContenBox"
      ><image :src="styleData.coverImg"
    /></view>
    <text class="name">{{ styleData.title }}</text>
    <view class="orangeBtn" @click="createing1" style="margin-top: -20rpx"
      >开始制作写真
    </view>
    <view class="grayBtn" @click="toChooseModel" style="margin-top: 30rpx"
      >重新选择模版
    </view>
    <!-- 登录二维码弹出层 -->
    <u-overlay
      class="overlay"
      :show="showQrCode"
      @click="showQrCode = false"
      opacity="0.9"
    >
      <view class="content">
        <view class="imageBox" :class="payMask ? 'glass' : ''">
          <view class="mask" v-show="payMask"></view>
          <image :src="qrCode" mode="scaleToFill" />
        </view>
        <text v-show="!userInfoModulesPinia.token">打开微信扫码登录小程序</text>
        <text
          v-show="
            userInfoModulesPinia.token && userInfoModulesPinia.createTimes == 0
          "
          >剩余生成次数不足,请扫码充值!</text
        >
        <text style="margin-top: 30rpx" v-show="payCount != 90"
          >{{ payCount }}秒后过期</text
        >
        <view class="orangeBtn" style="margin-top: 60rpx">取&nbsp;消</view>
      </view>
    </u-overlay>
  </view>
</template>

<script setup>
//#region 导入
import { ref, watch, onMounted } from "vue";
import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
import {
  findByIdApi,
  findImageApi,
  createPhotoApi,
} from "../../api/closeStyle";
import { getQRCodeApi, getUserApi } from "../../api/createing";
import { userInfoModules } from "@/store/modules/userInfo";
const userInfoModulesPinia = userInfoModules();
//#endregion

//#region 初始化
const styleId = ref(null);
const styleData = ref({});
const cameraImg = ref(null);
onLoad(async (options) => {
  styleId.value = options.id;
  // getInfo();
  cameraImg.value = options.imageUrl;
  if (options.imageUrl) {
    await getInfo();
    createing2();
  }
});
onShow(() => {
  getInfo();
});

async function getInfo() {
  try {
    const res = await findByIdApi(styleId.value);
    styleData.value = res.data;
  } catch (error) {
    uni.showToast({
      title: "获取数据失败，请重试",
      icon: "none",
    });
  }
}

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

//#region 生成写真照片
async function createing1() {
  // 没有token则扫码登录
  if (!uni.getStorageSync("token")) {
    showQrCode.value = true;
    return;
  } else if (uni.getStorageSync("createTimes") == 0) {
    showQrCode.value = true;
  } else {
    toCamera();
  }
}
async function createing2() {
  try {
    uni.showLoading({
      title: "生成中...",
      mask: true,
    });
    // const res = await findImageApi();
    // let myImg =
    //   "https://suimang.oss-accelerate.aliyuncs.com/capi/2023-09-18/bd50b0024ea4470cbd391bcb00382f72.jpg?x-oss-process=image/resize,w_10000/quality,q_60";
    let myImg = cameraImg.value;
    const data = {
      machineQrcodeId: uni.getStorageSync("UserId"),
      plat: uni.getStorageSync("plat"),
      digitalAvatarId: styleData.value.id,
      userImages: JSON.stringify([myImg]),
      title: styleData.value.title,
    };
    const res2 = await createPhotoApi(data);
    if (res2.data) {
      console.log(res2);
      // userInfoModulesPinia.createTimes = userInfoModulesPinia.createTimes - 1;
      uni.navigateTo({
        url: `/pages/created/index?id=${res2.data.id}&imgUrl=${styleData.value.coverImg}`,
      });
    } else {
      throw new Error();
    }
    uni.hideLoading();
  } catch (error) {
    console.log(error);
    uni.hideLoading();
    uni.showToast({
      title: "生成失败，请重试",
      icon: "none",
    });
  }
}
//#endregion ---------------------

//#region 获取二维码
const qrCode = ref(null); //二维码路径
const showQrCode = ref(false);
async function getQRCode() {
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  try {
    const data = {
      sn: "112233",
      // sn: window.android.getIMEI(),
      type: 1,
    };
    const res = await getQRCodeApi(data);
    uni.hideLoading();
    if (res.code == 1013) {
      uni.showToast({
        title: "操作频繁,请稍等....",
        icon: "none",
        mask: true,
        duration: 3000,
      });
      setTimeout(() => {
        getQRCode();
      }, 3000);
      return;
    }
    if (res.data && res.data.tmpUserId) {
      uni.setStorageSync("UserId", res.data.tmpUserId);
      qrCode.value = res.data.qrCodeUrl;
      getUser();
      payCountTimer.value = setInterval(() => {
        payCount.value--;
      }, 1000);
    } else if (res.code == 1013) {
      uni.showToast({
        title: "请勿重复操作",
        icon: "error",
        mask: true,
      });
    }
  } catch (err) {
    console.log(err);
    uni.hideLoading();
    uni.showToast({
      title: "获取登录失败,请刷新页面重试",
      icon: "error",
      mask: true,
    });
  }
}
// getQRCode();
//#endregion ---------------------

//#region 获取用户信息

const payMask = ref(false); //支付状态遮罩层
const payCount = ref(90); //支付倒计时数
const payCountTimer = ref(null); //支付倒计时
// 获取登录信息
async function getUser() {
  // 如果二维码框隐藏,不再执行
  if (showQrCode.value == false) {
    return;
  }
  try {
    const res = await getUserApi(uni.getStorageSync("UserId"));
    // 如果接口200就说明已登录
    if (res.code == 200 && res.data) {
      // 查询支付状态 0:待支付，2:支付中，3：已支付
      uni.setStorageSync("token", res.data.token);
      uni.setStorageSync("createTimes", res.data.createTimes);
      uni.setStorageSync("phone", res.data.phone);
      userInfoModulesPinia.token = res.data.token;
      userInfoModulesPinia.phone = res.data.phone;
      userInfoModulesPinia.createTimes = res.data.createTimes;
      if (res.data.payStatus == 3) {
        clearInterval(payCountTimer.value);
        payCountTimer.value = null;
        uni.hideLoading();
        payMask.value = false;
        showQrCode.value = false;
        uni.showToast({
          title: "支付成功!",
          icon: "success",
          mask: true,
        });
        // 成功直接照相
        // toCamera();
      } else if (res.data.payStatus == 0) {
        payMask.value = true;
        uni.showLoading({
          title: `待支付...`,
        });
        if (showQrCode.value == false) {
          payMask.value = false;
          uni.hideLoading();
          return;
        }
        getUser();
      } else if (res.data.payStatus == 2) {
        payMask.value = true;
        uni.showLoading({
          title: `支付中...`,
        });
        if (showQrCode.value == false) {
          payMask.value = false;
          uni.hideLoading();
          return;
        }
        getUser();
      }
    } else {
      getUser();
    }
  } catch (err) {
    console.log(err);
  }
}
// 监听二维码弹窗显示隐藏
watch(
  () => showQrCode.value,
  () => {
    if (showQrCode.value == true) {
      getQRCode();
    } else if (showQrCode.value == false) {
      uni.hideLoading();
      qrCode.value = null;
      payMask.value = false;
      clearInterval(payCountTimer.value);
      payCountTimer.value = null;
      payCount.value = 90;
    }
  }
);
// 监听支付倒计时
watch(
  () => payCount.value,
  () => {
    if (payCount.value <= 0) {
      uni.hideLoading();
      showQrCode.value = false;
    }
  }
);
onUnload(() => {
  uni.hideLoading();
  clearInterval(payCountTimer.value);
  payCountTimer.value = null;
  // uni.setStorageSync("UserId", null);
});
//#endregion ---------------------

//#region 路由跳转
function toChooseModel() {
  uni.navigateTo({
    url: `/pages/chooseStyle/index`,
  });
}
function toCamera() {
  const url = styleData.value.coverImg;
  const id = styleData.value.id;
  const mouldType = styleData.value.mouldType;
  uni.navigateTo({
    url: `/pages/camera/index?modelUrl=${url}&id=${id}&mouldType=${mouldType}`,
  });
}
//#endregion ---------------------

//#region 退出登录
function loginOut() {
  uni.showModal({
    title: "提示",
    content: "是否退出登录?",
    confirmColor: "#ff4f00",
    success: function (res) {
      if (res.confirm) {
        console.log("用户点击确定");
        userInfoModulesPinia.clearStorage();
        uni.navigateTo({ url: "/pages/login/index" });
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
}
//#endregion ---------------------

//#region

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

//#region 页面初始化和卸载
const resetTimer = ref(null);
onMounted(() => {
  window.document.addEventListener("touchstart", () => {
    // 用户点击时，清除之前的定时器
    clearTimeout(resetTimer.value);
    // 重新设定120秒后触发的定时器
    resetTimer.value = setTimeout(() => {
      userInfoModulesPinia.clearStorage();
      uni.redirectTo({ url: "/pages/login/index" });
    }, 180000);
  });
  resetTimer.value = setTimeout(() => {
    userInfoModulesPinia.clearStorage();
    uni.redirectTo({ url: "/pages/login/index" });
  }, 180000);
});
onUnload(() => {
  clearTimeout(resetTimer.value);
});
//#endregion -----------------------
</script>

<style lang="scss">
.userInfoBox {
  padding: 0 20rpx;
  width: 100%;
  display: flex;
  height: 50rpx;
  line-height: 50rpx;
  justify-content: space-between;
  border-radius: 20rpx;
  background-color: rgba($color: #ccc, $alpha: 0.4);
  .loginOut {
    color: #ff4f00;
    text-decoration: underline;
  }
}
.showImgBox {
  margin-top: 30rpx;
  width: 540rpx;
  height: 720rpx;
  // background-color: #ccc;
  border-radius: 30rpx;
  image {
    width: 100%;
    height: 100%;
    border-radius: 30rpx;
  }
}
.name {
  margin-top: 80rpx;
  margin-bottom: 80rpx;
  font-size: 44rpx;
  font-weight: 800;
}
.orangeBtn {
  position: relative;
  .free {
    position: absolute;
    top: -18rpx;
    right: -70rpx;
    width: 142rpx;
    height: 50rpx;
    background-color: #000;
    border-radius: 25rpx 25rpx 25rpx 0;
    font-size: 22rpx;
    font-weight: 900;
    line-height: 50rpx;
    text-align: center;
  }
}
.overlay {
  .content {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    .imageBox {
      position: relative;
      margin-top: 200rpx;
      width: 500rpx;
      height: 500rpx;
      border-radius: 30rpx;
      background-color: #fff;
      .mask {
        position: absolute;
        width: 500rpx;
        height: 500rpx;
        border-radius: 30rpx;
        background-color: rgba($color: #000000, $alpha: 0.7);
        z-index: 2;
      }
      image {
        width: 500rpx;
        height: 500rpx;
        border-radius: 30rpx;
        background-color: #fff;
      }
    }
    text {
      margin-top: 20rpx;
      font-weight: 900;
      font-size: 32rpx;
    }
    // .orangeBtn {
    //   margin-top: 100rpx;
    // }
  }
}
</style>
