<script setup>
import { ref, computed, watch, onMounted } from "vue"
import { useRouter, useRoute } from 'vue-router'
import positionMaps from '../static/positionMaps.js'
import imagePositionMaps from '../static/imagePositionMaps.js'
import { RequestImg, Storage } from "../libs/utils"

defineProps({
  show: true
})

onMounted(() => {
})

import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const imageUrl1 = ref('');
// 上传前的校验
// const beforeUpload = (file) => {
//   const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
//   if (!isJpgOrPng) {
//     ElMessage.error('只能上传JPG或PNG格式的图片!');
//     return false; // 返回false阻止上传
//   }
//   const isLt2M = file.size / 1024 / 1024 < 2;
//   if (!isLt2M) {
//     ElMessage.error('图片大小不能超过2MB!');
//     return false;
//   }
//   return true; // 返回true继续上传
// };

// 上传成功回调
// const handleSuccess = (response, index) => {
//   console.log(index)
//   imageUrl1.value = response.url;
//   ElMessage.success('上传成功！');
// };

// 上传失败回调
// const handleError = (error) => {
//   // console.error('上传失败:', error);
//   // ElMessage.error('上传失败，请重试！');
//   uploadItems.value[0].imageUrl = "src/assets/images/demo.png";
//   uploadItems.value[1].imageUrl = "src/assets/images/demo.png";
//   uploadItems.value[2].imageUrl = "src/assets/images/demo.png";
//   uploadItems.value[3].imageUrl = "src/assets/images/demo.png";
//   uploadItems.value[4].imageUrl = "src/assets/images/demo.png";
//   ElMessage.success('上传成功！');
// };

// 根据imageUrl的结尾编号确定需要多少个上传项
const getUploadItemsCount = () => {
  if (!imageUrl.value) return 2 // 默认值

  const url = imageUrl.value.toString()

  if (url.includes('xianxia') && url.endsWith('_3.png')) {
    return 3
  }

  if (url.includes('paidui') && url.endsWith('_5.png')) {
    return 3
  }

  if (url.endsWith('_1.png') || url.endsWith('_2.png') || url.endsWith('_3.png')) {
    return 2
  } else if (url.endsWith('_4.png')) {
    return 3
  } else if (url.endsWith('_5.png')) {
    return 4
  } else if (url.endsWith('_6.png')) {
    return 5
  }

  return 2 // fallback
}
const uploadItems = ref([])

const initializeUploadItems = () => {
  const count = getUploadItemsCount()
  
  const items = Array(count).fill(null).map(() => ({
    imageUrl: '',
    uploadData: {}
  }))

  uploadItems.value = items
}

const route = useRoute()
const imageUrl = computed(() => route.query.imageUrl)

watch(imageUrl, () => {
  initializeUploadItems()
}, { immediate: true })

const uploadRefs = ref([]);

const clearUploadFile = (index) => {
  if (uploadRefs.value[index]) {
    uploadRefs.value[index].clearFiles();
    uploadItems.value[index].imageUrl = '';
  }
};

const generateImage = () => {
  
}

const router = useRouter();
const goBack = () => {
  router.back();
};

const currentVersion = computed(() => {
  const url = imageUrl.value;
  const match = url.match(/(shenxian|xianxia|fugu|xinzhongshi|luying|paidui)_(\d)/);
  
  if (!match) return positionMaps.shenxian[1];
  const [_, category, version] = match;
  
  return positionMaps[category]?.[version] || positionMaps.shenxian[1];
});

const buttonPosition = (index) => {
  const versionData = currentVersion.value;
  if (!versionData || !versionData.positions[index - 1]) {
    return {};
  }
  const pos = versionData.positions[index - 1];
  return {
    top : pos.top,
    left : pos.left,
    "--item-width": pos.width
  };
};

const buttonUploadedPosition = (index) => {
  const versionData = currentVersion.value;
  if (!versionData?.positions?.[index - 1]) {
    return {};
  }

  const pos = versionData.positions[index - 1];
  const url = imageUrl.value;
  
  const match = url.match(/(shenxian|xianxia|fugu|xinzhongshi|luying|paidui)_(\d)/);
  if (!match) {
    return {
      top: pos.top,
      left: pos.left,
      "--item-width": pos.width
    };
  }

  const [_, category, versionStr] = match;
  const version = parseInt(versionStr);
  
  const originalTop = parseFloat(pos.top);
  if (isNaN(originalTop)) {
    return {
      top: pos.top,
      left: pos.left,
      "--item-width": pos.width
    };
  }

  const ADJUSTMENT_CONFIG = {
    shenxian: { 
      1:8, 2:6, 3:6, 4:5, 5:5, 6:4 
    },
    xianxia: { 
      1:8, 2:6, 3:6, 4:5, 5:5, 6:4 
    },
    fugu: { 
      1:6, 2:7, 3:7, 4:5, 5:5, 6:4 
    },
    xinzhongshi: { 
      1:6, 2:7, 3:4, 4:5, 5:3, 6:4 
    },
    luying: { 
      1:6, 2:7, 3:4, 4:5, 5:3, 6:4 
    },
    paidui:{ 
      1:6, 2:7, 3:6, 4:5, 5:6, 6:4 
    }
  };

  let adjustedTop = originalTop;
  if (ADJUSTMENT_CONFIG[category]?.[version] !== undefined) {
      adjustedTop -= ADJUSTMENT_CONFIG[category][version];
  }

  return {
    top:`${adjustedTop}%`,
    left :pos.left ,
    "--item-width" :pos.width  
  };
};

const currentImgVersion = computed(() => {
  const url = imageUrl.value;
  const match = url.match(/(shenxian|xianxia|fugu|xinzhongshi|luying|paidui)_(\d)/);
  
  if (!match) return imagePositionMaps.shenxian[1];
  const [_, category, version] = match;
  
  return imagePositionMaps[category]?.[version] || imagePositionMaps.shenxian[1];
});

const imagePosition = (index) => {
  const versionData = currentImgVersion.value;
  if (!versionData || !versionData.positions[index - 1]) {
    return {};
  }
  const pos = versionData.positions[index - 1];
  return {
    top : pos.top,
    left : pos.left,
    width: pos.width
  };
};



// 自定义上传方法
const customUpload = async (options) => {
  const { file, data, onProgress, onSuccess, onError } = options
  
  try {
    // FormData对象用于构建表单数据
    const formData = new FormData()
    formData.append('type', 'ali-face')
    formData.append('image', file)
    
    const config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.lengthComputable) {
          const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100)
          onProgress({ percent }) // 更新上传进度
        }
      }
    }
    
    // 使用你封装的Request方法调用API
    const result = await RequestImg('upload/image', formData)
    
    // API调用成功处理
    if (result.code === 'success') { // code字段需要根据你的API实际返回调整
      onSuccess(result.data) // result.data包含服务器返回的数据
    } else {
      onError(new Error(result.message || '上传失败'))
    }
    
    return result
    
  } catch (error) {
    onError(error)
    throw error
  }
}
</script>

<template>
  <div :show="show">
    <div class="home-wrapper" style="z-index: 9;">
      <div class="scene-item item-1">
        <img src="../assets/images/back-btn.png" @click="goBack" alt="后退">
      </div>

      <div class="scene-item img-from-template scene-item-img" style="transition: none !important;">
        <img :src="imageUrl" alt="模板图片">
      </div>

      <div class="scene-item item-2" @click="generateImage">
        <img src="../assets/images/generate-btn.png" alt="开始合成">
      </div>

      <div class="upload-container">
        <div v-for="(item, index) in uploadItems" :key="index" class="upload-item-wrapper">
          <el-upload
            :ref="(el) => (uploadRefs[index] = el)"
            :http-request="customUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="(res) => handleSuccess(res, index)"
            :on-error="handleError"
            :data="item.uploadData"
            accept="image/*"
          >
            <el-button class="upload-img-wrapper upload-btn" :style="buttonPosition(index + 1)">
              <div class="scene-item item scene-item-img" :class="{ uploaded: item.imageUrl }"
              :style="{ width: buttonPosition(index + 1)['--item-width'] }">
                <img 
                  v-if="!item.imageUrl"
                  src="../assets/images/upload-img.png" 
                  alt="上传图片"
                >
                <div v-if="!item.imageUrl"></div>
              </div>
            </el-button>
          </el-upload>

          <!-- 图片预览 -->
          <div v-if="item.imageUrl" class="preview-container">
            <img 
              :src="item.imageUrl" 
              alt="预览图" 
              class="preview-image upload-btn"
              :style="imagePosition(index + 1)"
            />
            <button @click.stop.prevent="clearUploadFile(index)" :style="buttonUploadedPosition(index + 1)" style="position: absolute;">
              <div :style="{ width: buttonUploadedPosition(index + 1)['--item-width'] }" >
                <img src="../assets/images/img-uploaded.png" class="delete-btn upload-img-wrapper" alt="删除图片">
              </div>
            </button>
          </div>
          <template v-else>
            <Plus />
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.scene-item-img {
  transition: none !important;
}
.preview-image {
  z-index: 999;
}
.delete-btn {
  position: relative;
  width: 100%;
  z-index: 999;
}
.uploaded {
  margin-top: -18px;
}
.upload-btn {
  position: absolute;
}
.remove-img-1 {
  top: 31.6%;
  left: 24%;
  position: absolute;
}
.remove-img-2 {
  top: 30.4%;
  left: 44.2%;
  position: absolute;
}
.remove-img-3 {
  top: 39.4%;
  left: 57.2%;
  position: absolute;
}
.remove-img-4 {
  top: 34.4%;
  left: 72.2%;
  position: absolute;
}
.remove-img-5 {
  top: 48.4%;
  left: 37.2%;
  position: absolute;
}
.upload-img-wrapper.el-button {
  background: transparent !important;
  background-color: transparent !important;
  border: none !important;
  border-color: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
  color: inherit !important;
  box-shadow: none !important;
  text-shadow: none !important;
  cursor: pointer;
  outline: none !important;
  
  border-radius: 0 !important;
  height: auto !important;
  line-height: inherit !important;
  width: auto !important;
  min-width: auto !important;
  display: inline-block !important;
  justify-content: inherit !important;
  align-items: inherit !important;
  transition: none !important;
}

.upload-img-wrapper.el-button:hover,
.upload-img-wrapper.el-button:focus,
.upload-img-wrapper.el-button:active {
  background: transparent !important;
  background-color: transparent !important;
  border: none !important;
  border-color: transparent !important;
  box-shadow: none !important;
  color: inherit !important;
  outline: none !important;
}
.home-wrapper {
  width: 100%;
  height: 92vh;
  background-image: url('src/assets/images/generate-img-bg.png');
  background-size: cover;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  min-height: -webkit-fill-available;
}
.img-from-template {
  width: 322px;
  height: 436px;
  margin-top: -28px;
  border-radius: 16px !important;
  margin-left: 2px;
}
.scene-item {
  position: absolute;
  z-index: 2;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.4s ease;
  overflow: hidden;
  border: 3px solid transparent;
  animation: float 4s ease-in-out infinite;
}

.scene-item:hover {
  transform: scale(1.05);
  z-index: 10;
}

.scene-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.item-1 {
  width: 20px;
  top: 6.7%;
  left: 5%;
  animation-delay: 0s;
}

.item-2 {
  width: 240px;
  bottom: 28px;
  animation-delay: 0s;
}

.item {
  width: 48px;
}
.item-4 {
  width: 48px;
  top: 30.6%;
  left: 44.5%;
}
.item-5 {
  width: 48px;
  top: 34%;
  left: 72%;
}
.item-6 {
  width: 48px;
  top: 49.4%;
  left: 36.6%;
}
.item-7 {
  width: 48px;
  top: 40%;
  left: 57.5%;
}
</style>