<template>
  <div>
    <el-dialog v-model="upLoadDialog" append-to-body :close-on-click-modal="false" :before-close="dialogClose" destroy-on-close>
      <el-upload
        class="upload-demo"
        drag
        :headers="{ Authorization: 'Bearer' + getZHToken() }"
        :on-error="handleUploadError"
        :on-success="handleUploadSuccess"
        :before-upload="handleBeforeUpload"
        :on-progress="handleUploadProgress"
        action="https://api.zhihui.qq.com/atom-parser/psd/upload-parse-only"
        :http-request="templateUpload"
        :accept="'.psd'"
        ref="uploader"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖拽到此处，或者
          <em>选择文件</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">支持上传psd文件,大小限制100M以内。</div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script setup>
import { getZHToken } from '@/utils/auth';
import { ElLoading } from 'element-plus';
import editorRender from 'psyche-editor-render';
import OSS from 'ali-oss';
import dayjs from 'dayjs';
// const jsonData = parse.parsePSD(bufferData);
const emits = defineEmits(['update:upLoadDialog', 'updateEnd']);
const props = defineProps({
  upLoadDialog: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: 'template',
  },
});
const { upLoadDialog, type } = toRefs(props);
const { proxy } = getCurrentInstance();

const update_list = ref([]); //待推送的文件
const uploader = ref(null);
const accept_list = ref({ template: '.psd', b: 'image' });
const uploader_url = ref({
  template: 'https://api.zhihui.qq.com/atom-parser/psd/upload-parse-only',
  mraw: 'https://zhihui.qq.com/bll-apollo/common/upload',
});
let loading = null;

function dialogClose() {
  uploader && uploader?.clearFiles?.();
  emits('update:upLoadDialog', false);
}
async function handleBeforeUpload(file) {
  console.log('🚀 ~ file: index.vue:59 ~ handleBeforeUpload ~ file:', file);
}

function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}
function base64ToBlob(data) {
  const arr = data.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
function uploaderOss(file) {
  return new Promise(async (resolve, reject) => {
    let fileDir = dayjs().format('YYYYMMDD');
    const client = new OSS({
      // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
      region: 'oss-cn-fuzhou',
      // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
      accessKeyId: import.meta.env.VITE_APP_OSS_ACCESS_KEY_ID,
      accessKeySecret: import.meta.env.VITE_APP_OSS_ACCESS_KEY_SECRET,
      // 填写存储空间名称。
      bucket: 'dfdiyfile',
      endpoint: 'https://oss-cn-fuzhou.aliyuncs.com',
    });
    let name = 'desgn/' + fileDir + '/' + guid() + '.png';
    // storeAs表示上传的object name , file表示上传的文件
    let data = await client.put(name, base64ToBlob(file));
    resolve(data.url);
  });
}
//文件转buffer
function fileToBuffer(file) {
  return new Promise((resolve, reject) => {
    const fr = new FileReader();
    fr.onload = e => {
      resolve(e.target.result);
    };
    fr.readAsArrayBuffer(file);
    fr.onerror = () => {
      reject(new Error('转换文件格式发生错误'));
    };
  });
}
//解析加上传
async function templateUpload(options) {
  loading = ElLoading.service({
    lock: true,
    text: '解析中...',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  const parse = new editorRender.ParsePSDHandler();
  let bufferData;
  try {
    bufferData = await fileToBuffer(options.file);
  } catch (error) {
    loading && loading.close();
    return options.onError(error);
  }
  let jsonData;
  try {
    jsonData = parse.parsePSD(bufferData, false);
  } catch (error) {
    loading && loading.close();
    return options.onError(error);
  }
  //tumb上传至oss
  jsonData.thumb = await uploaderOss(jsonData.thumb);
  jsonData.objects?.map(async item => {
    if (item.src) {
      item.src = await uploaderOss(item.src);
    }
  });
  options.onSuccess({ data: jsonData, statusCode: 201 });
}
function getSuff(name) {
  return name.substring(name.lastIndexOf('.'));
}
function handleUploadError(error, uploadFile, uploadFiles) {
  proxy.$modal.msgError('解析失败-' + error);
}
function handleUploadProgress(evt, uploadFile, uploadFiles) {
  console.log('🚀 ~ file: index.vue:96 ~ handleUploadProgress ~ evt, uploadFile, uploadFiles:', evt, uploadFile, uploadFiles);
}
async function handleUploadSuccess(res, file, uploadFiles) {
  if (!res) {
    return;
  }
  if (res.statusCode == 201) {
    let data = res.data;
    if (type.value == 'template') {
      update_list.value.push({ ...data, file_name: file.name });
    }
    let uploading_list = uploadFiles.filter(item => item.status !== 'success');
    if (uploading_list.length == 0) {
      loading && loading.close();
      emits('updateEnd', update_list.value);
    }
  }
}
</script>
