<template>
  <view class="page">
    <view class="showImgBox imgContenBox"
      ><image :src="styleData.coverImg"
    /></view>
    <text class="name">{{ styleData.title }}</text>
    <view class="imgBox">
      <!-- 图一 -->
      <view class="imgBoxItem">
        <image class="avatar" :src="avatarList[0].url" mode="aspectFill" />
        <view v-if="!avatarList[0].url" class="noUrlBox" @click="chooseImg(0)"
          >+</view
        >
        <!-- 遮罩层 -->
        <view v-if="avatarList[0].url" class="maskTips">{{
          avatarList[0].isMyAvatar ? "授权用户头像" : "已上传第1个头像"
        }}</view>
        <view
          v-if="avatarList[0].url && !avatarList[0].isMyAvatar"
          class="reUploadBtn"
          @click="chooseImg(0)"
          >更换头像</view
        >
        <view
          v-if="!avatarList[0].url && !avatarList[0].isMyAvatar"
          class="uploadBtn"
          @click="chooseImg(0)"
          >上传头像</view
        >
      </view>
      <image
        @click="swapItems"
        class="exchange"
        src="../../assets/icon/exchange.png"
        mode="scaleToFill"
      />
      <!-- 图二 -->
      <view class="imgBoxItem">
        <image class="avatar" :src="avatarList[1].url" mode="aspectFill" />
        <view v-if="!avatarList[1].url" class="noUrlBox" @click="chooseImg(1)"
          >+</view
        >
        <!-- 遮罩层 -->
        <view v-if="avatarList[1].url" class="maskTips">{{
          avatarList[1].isMyAvatar ? "授权用户头像" : "已上传第2个头像"
        }}</view>
        <view
          v-if="avatarList[1].url && !avatarList[1].isMyAvatar"
          class="reUploadBtn"
          @click="chooseImg(1)"
          >更换头像</view
        >
        <view
          v-if="!avatarList[1].url && !avatarList[1].isMyAvatar"
          class="uploadBtn"
          @click="chooseImg(1)"
          >上传头像</view
        >
      </view>
      <image
        v-if="styleData.mouldType == 3"
        @click="swapItems2"
        class="exchange"
        src="../../assets/icon/exchange.png"
        mode="scaleToFill"
      />
      <!-- 图三 -->
      <view v-if="styleData.mouldType == 3" class="imgBoxItem">
        <image class="avatar" :src="avatarList[2].url" mode="aspectFill" />
        <view v-if="!avatarList[2].url" class="noUrlBox" @click="chooseImg(2)"
          >+</view
        >
        <!-- 遮罩层 -->
        <view v-if="avatarList[2].url" class="maskTips">{{
          avatarList[2].isMyAvatar ? "授权用户头像" : "已上传第3个头像"
        }}</view>
        <view
          v-if="avatarList[2].url && !avatarList[2].isMyAvatar"
          class="reUploadBtn"
          @click="chooseImg(2)"
          >更换头像</view
        >
        <view
          v-if="!avatarList[2].url && !avatarList[2].isMyAvatar"
          class="uploadBtn"
          @click="chooseImg(2)"
          >上传头像</view
        >
      </view>
    </view>
    <text class="tips">人物头像对应模板人物位置，点击按钮可以调整顺序</text>
    <view class="orangeBtn" @click="createing(styleData.id)"
      >开始制作写真
      <view class="free">
        <text>耗金币{{ styleData.salePrice }}枚</text>
      </view>
    </view>
    <view class="balance"
      >金币余额:&nbsp;&nbsp;{{ userInfoModulesPinia.myGlod }}
      <image src="../../assets/icon/coin.png" mode="aspectFit" />
    </view>
  </view>
</template>

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

//#region 初始化
const styleId = ref(null);
const styleData = ref({});
onLoad((options) => {
  // styleId.value = options.id;
  // styleId.value = "857147862095679488";
  styleId.value = "2003";
  // styleId.value = "246";
  getInfo();
  // getMyCoin();
});

async function getInfo() {
  try {
    const res = await findByIdApi(styleId.value);
    console.log(res);
    styleData.value = res.data;
  } catch (error) {
    uni.showToast({
      title: "获取数据失败，请重试",
      icon: "none",
    });
  }
}
// 查询我的金币
async function getMyCoin() {
  const res4 = await findGlodApi();
  if (!res4.data) {
    userInfoModulesPinia.myGlod = 0;
  } else {
    userInfoModulesPinia.myGlod = res4.data.digitalAvatarResidueGlod
      ? res4.data.digitalAvatarResidueGlod
      : 0;
  }
}
//#endregion ---------------------

//#region 上传图片
const avatarList = ref([
  {
    url: userInfoModulesPinia.myAvatar,
    // url: "https://suimang.oss-accelerate.aliyuncs.com/builtin/digital_avatar/girl/%E9%A3%8E%E9%87%87%E5%87%BA%E4%BC%97.jpg",
    isMyAvatar: true,
  },
  {
    url: "",
    // url: "https://suimang.oss-accelerate.aliyuncs.com/builtin/digital_avatar/girl/%E9%AA%8F%E9%A9%AC%E4%BD%B3%E4%BA%BA.jpg",
    isMyAvatar: false,
  },
  {
    url: "",
    // url: "https://suimang.oss-accelerate.aliyuncs.com/builtin/digital_avatar/girl/%E7%B4%AB%E8%96%87%E7%90%B4%E9%9F%B5.png",
    isMyAvatar: false,
  },
]);
// 切换位置
function swapItems() {
  const temp = avatarList.value[0];
  avatarList.value[0] = avatarList.value[1];
  avatarList.value[1] = temp;
}
function swapItems2() {
  const temp = avatarList.value[1];
  avatarList.value[1] = avatarList.value[2];
  avatarList.value[2] = temp;
}
// 打开图片选择,包含了百度检测人脸检测和上传图片
function chooseImg(index) {
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      console.log(res, "887");
      uni.showLoading({
        title: "上传中...",
        mask: true,
      });
      // 百度敏感信息检测
      uni.uploadFile({
        url: "https://test.metavatar.cc/C/api/baidu/checkPhoto", //上传图片api
        filePath: res.tempFilePaths[0],
        name: "file",
        formData: {
          user: "test",
        },
        header: {
          // Authorization: userInfoModulesPinia.token,
          token: userInfoModulesPinia.token,
        },
        success: async (res2) => {
          if (JSON.parse(res2.data).code != 200) {
            uni.hideLoading();
            uni.showToast({
              title: "图片不符合规范， 请重试",
              icon: "none",
            });
            return;
          } else {
            // 人脸识别接口
            uni.uploadFile({
              url: "https://test.metavatar.cc/C/api/userDigital/checkPhoto", //上传图片api
              filePath: res.tempFilePaths[0],
              name: "file",
              formData: {
                user: "test",
              },
              header: {
                // Authorization: userInfoModulesPinia.token,
                token: userInfoModulesPinia.token,
              },
              success: (res3) => {
                if (JSON.parse(res3.data).code != 200) {
                  uni.hideLoading();
                  uni.showToast({
                    title: "图片不符合规范， 请重试",
                    icon: "none",
                  });
                  return;
                } else {
                  // 上传接口
                  uni.uploadFile({
                    url: "https://test.metavatar.cc/C/api/upload/awsImgUpload", //上传图片api
                    filePath: res.tempFilePaths[0],
                    name: "file",
                    formData: {
                      user: "test",
                    },
                    header: {
                      "Content-Type": "multipart/form-data",
                      token: userInfoModulesPinia.token,
                    },
                    success: async (res4) => {
                      if (JSON.parse(res4.data).code != 200) {
                        uni.hideLoading();
                        uni.showToast({
                          title: "网络被数字人偷走了， 请稍后重试",
                          icon: "none",
                        });
                        return;
                      }
                      // 赋值
                      avatarList.value[index].url = JSON.parse(
                        res4.data
                      ).data.url;
                      uni.hideLoading();
                    },
                    fail: () => {
                      uni.hideLoading();
                      uni.showToast({
                        title: "网络被数字人偷走了， 请稍后重试",
                        icon: "none",
                      });
                    },
                  });
                }
              },
              fail: () => {
                uni.hideLoading();
                uni.showToast({
                  title: "网络被数字人偷走了， 请稍后重试",
                  icon: "none",
                });
              },
            });
          }
        },
        fail: (err) => {
          console.error("选择图片失败", err);
          uni.hideLoading();
          uni.showToast({
            title: "选择图片失败， 请稍后重试",
            icon: "none",
          });
        },
      });
    },
    fail: (err) => {
      console.error("选择图片失败", err);
      uni.showToast({
        title: "选择图片失败， 请稍后重试",
        icon: "none",
      });
    },
  });
}

// 上传图片
function uploadImg(index) {}
//#endregion ---------------------

//#region 生成写真照片
async function createing(id) {
  try {
    uni.showLoading({
      title: "加载中...",
      mask: true,
    });
    // const res = await findImageApi();
    // console.log(res);
    // let myImg = res.data.image;
    let myImgList = [];
    avatarList.value.forEach((item) => {
      myImgList.push(item.url);
    });
    const data = {
      digitalAvatarId: id,
      userImages:
        styleData.value.mouldType == 2
          ? JSON.stringify(myImgList.slice(0, 2))
          : JSON.stringify(myImgList),
    };
    const res2 = await createPhotoApi(data);
    console.log(res2);
    uni.hideLoading();
    uni.navigateTo({
      url: `/pages/createing/index?id=${res2.data.id}`,
    });
  } catch (error) {
    console.log(error);
    uni.hideLoading();
    uni.showToast({
      title: "生成失败，请重试",
      icon: "none",
    });
  }
}
//#endregion ---------------------

//#region

//#endregion ---------------------
</script>

<style lang="scss">
.page {
  background-color: rgba(24, 25, 26, 1);
}

.showImgBox {
  margin-top: 30rpx;
  width: 360rpx;
  height: 480rpx;
  // background-color: #ccc;
  border-radius: 30rpx;
  image {
    width: 100%;
    height: 100%;
    border-radius: 30rpx;
  }
}
.name {
  margin-top: 70rpx;
  margin-bottom: 47rpx;
  font-size: 44rpx;
  font-weight: 800;
}
.imgBox {
  margin-bottom: 40rpx;
  width: 100%;
  // height: 180rpx;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .exchange {
    width: 60rpx;
    height: 60rpx;
    margin-top: 67rpx;
  }
  .imgBoxItem {
    position: relative;
    width: 180rpx;
    height: 250rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    .avatar {
      position: absolute;
      width: 180rpx;
      height: 180rpx;
      border-radius: 24rpx;
    }
    .noUrlBox {
      position: absolute;
      width: 180rpx;
      height: 180rpx;
      line-height: 180rpx;
      color: #ff4f00;
      font-size: 50rpx;
      font-weight: 900;
      text-align: center;
      border-radius: 24rpx;
      background-color: #393a3d;
    }
    .maskTips {
      position: absolute;
      width: 180rpx;
      height: 180rpx;
      line-height: 180rpx;
      color: #fff;
      font-size: 20rpx;
      font-weight: 900;
      text-align: center;
      border-radius: 24rpx;
      background-color: rgba(0, 0, 0, 0.3);
    }
    .reUploadBtn,
    .uploadBtn {
      margin-top: 200rpx;
      width: 150rpx;
      height: 50rpx;
      text-align: center;
      line-height: 50rpx;
      border-radius: 50rpx;
      background-color: #383a3c;
    }
  }
}

.tips {
  font-size: 22rpx;
}
.orangeBtn {
  position: relative;
  margin-top: 60rpx;
  .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;
  }
}
.balance {
  display: inline-block;
  margin-top: 70rpx;
  font-size: 30rpx;
  font-weight: bold;
  line-height: 33rpx;
  image {
    display: inline-block;
    width: 33rpx;
    height: 33rpx;
    vertical-align: middle;
  }
}
</style>
