<template>
  <div class="change-img">
    <a id="link"></a>
    <div class="course-container" id="download-image">
      <template v-if="backimg">
        <img class="course" id="course-img" :src="backimg" />
      </template>
      <template v-else>
        <div class="empty-background"></div>
      </template>
      <template v-if="list.length">
        <div class="drag-img-parent">
          <template v-for="item in list" :key="item.id">
            <ImageDarg
              :id="item.id"
              :img="item.img"
              @delete="DeleteImg"
            ></ImageDarg>
          </template>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import html2canvas from 'html2canvas';
import { ref, watch } from 'vue';
import ImageDarg from '@/components/custom/ImageDrag.vue';
import { show_message } from '@/utils/tdesign_tool';
import { base642File } from '@/utils/file';
import { UploadImageToAly } from '@/utils/http/http';
import { ModelStatus } from '@/utils/api/Task';
const props = withDefaults(
  defineProps<{
    list: any[];
    edit_image?: string;
    module_status: number;
    config?: any;
  }>(),
  {
    edit_image: '',
    config: {},
  }
);
const emit = defineEmits(['moduleChange', 'delete', 'submit']);
// 添加可以拖拽功能,放大缩小功能
const backimg = ref(props.edit_image);

watch(
  () => props.edit_image,
  (v) => {
    if (v) {
      backimg.value = v;
    }
  }
);
// menu事件
const DeleteImg = (item: any, id: string) => {
  emit('delete', item, id);
};
/**
 * 将oss图片做一次请求，转换下，网络路径图片都可以
 * url: 网络图片得路径
 * imgId: 网络图片img标签得id
 */
const getImage = (url, imgId) => {
  console.log(url, imgId);
  var xhr = new XMLHttpRequest();
  xhr.open('get', url, true);
  // 设置请求头（这一步得设置不然oss图片还是跨域）
  xhr.setRequestHeader('Cache-Control', 'no-cache');
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (this.status == 200) {
      const img_id = document.getElementById(imgId);
      if (img_id) {
        console.log('存在img_id');
        img_id.src = URL.createObjectURL(this.response);
      } else {
        console.log('不存在img_id');
      }
    }
  };
  xhr.send();
};
// 将元素转换为base64格式
const ConversionBase64 = async () => {
  const canvas = await html2canvas(document.querySelector('#download-image'), {
    // 跨域处理
    useCORS: true,
    logging: false,
  });
  const base64 = canvas
    .toDataURL('image/png')
    .replace('image/png', 'image/octet-stream');
  return base64;
};
// 保存到本地
// const save = () => {
//   html2canvas(document.querySelector('#download-image')).then((canvas) => {
//     // var image = canvas
//     //   .toDataURL('image/png')
//     //   .replace('image/png', 'image/octet-stream');

//     //save as download without name and extension
//     //window.location.href = image;
//     var link = document.getElementById('link');
//     link.setAttribute('download', 'my.png');
//     link.setAttribute(
//       'href',
//       canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
//     );
//     link.click();
//   });
// };
// 转换图片
const ConversionImage = async () => {
  try {
    const { config } = props;
    // 转换图片格式
    const ImageBase64 = await ConversionBase64();
    if (ImageBase64) {
      // 转二进制
      const file = await base642File(ImageBase64);
      if (file) {
        // 准备上传图片
        const res = await UploadImageToAly(config, file);
        if (res.status == 'fail') {
          show_message('图片上传失败,请再次点击生成按钮');
          return;
        }
        const url = res.response.url;
        // 通知父组件提交任务
        console.log(url);
        emit('submit', url);
      }
    }
  } catch (e) {
    console.log(e);
  }
};
/**
 * 转换为二进制，上传阿里云,提交任务
 */
watch(
  () => props.module_status,
  (v) => {
    console.log('监听到了');
    if (v == ModelStatus.upload) {
      // 上传并提交任务
      getImage(props.edit_image, '#course-img');
      ConversionImage();
    }
  }
);
</script>

<style scoped lang="less">
@import '@/style/variables.less';
.change-img {
  display: flex;
  flex-direction: column;
  padding: 20px;
  .course-container {
    width: 100%;
    position: relative;
    flex: 1;
    .course {
      width: 100%;
      height: 100%;
      // object-fit: contain;
      // cover 效果更好
      // object-fit: cover;
    }
  }
}

.empty-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 1px dashed #00f9f9;
}
.code {
  z-index: 2;
  position: absolute;
  width: 150px;
  height: 150px;
  img {
    width: 100%;
    height: 100%;
    cursor: move;
  }
}
.drag-img-parent {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 3;
}
</style>
