import axios from 'axios';
import { MessagePlugin } from 'tdesign-vue-next';
import i18n from '../i18n';
const $t = i18n.global.t;

export async function upload(
  blob: Blob,
  shared = false,
  filename = 'thumb.png',
  directory = '/大屏/图片/默认',
  conflict?:string
) {
  const form = new FormData();
  let name = filename;
  if(!name.includes('.')) {
    name += '.png';
  }
  form.append('name', name);
  form.append('directory', directory);
  form.append('shared', shared + '');
  form.append('file', blob);
  // let ret;
  if(conflict) {
    // ret = await axios.post('/api/image/upload',{conflict}, form);
    form.append('conflict', conflict);
  } 
  const ret = await axios.post('/api/image/upload', form);
  if (!ret) {
    return;
  }

  return ret;
}

export async function delImage(image: string) {
  const ret: any = await axios.delete('/api' + image);
  if (ret.error) {
    return false;
  }

  return true;
}

export async function addImage(image: string) {
  const ret: any = await axios.post('/api/user/image', { image });
  if (ret.error) {
    return '';
  }

  return ret.id;
}

export function filename(str: string) {
  const i = str.lastIndexOf('.');
  return str.substring(0, i);
}

const units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
export function formatBytes(size: number) {
  let l = 0;
  let n = size / 1024;

  while (n >= 1024 && ++l) {
    n = n / 1024;
  }

  return Math.round(n * 100) / 100 + ' ' + units[l];
}

/**
 * 读取文件内容，返回字符串
 * @param file 文件
 */
export async function readFile(file: Blob) {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result as string);
    };
    reader.onerror = reject;
    // readAsText 使 result 一定是字符串
    reader.readAsText(file);
  });
}

export function dataURLtoBlob(base64: string) {
  let arr: any = base64.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

/**
 * 图片转 Blob
 * @param img 图片
 */
export function saveToBlob(img: HTMLImageElement): Blob {
  const canvas: HTMLCanvasElement = document.createElement('canvas');
  canvas.setAttribute('origin-clean', 'false');
  canvas.width = img.width;
  canvas.height = img.height;

  const context: any = canvas.getContext('2d');
  context.filter = window.getComputedStyle(img).filter;
  context.drawImage(img, 0, 0, canvas.width, canvas.height);
  return dataURLtoBlob(canvas.toDataURL());
}

export async function importCSV() {
  return new Promise((resolve, reject) => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept =
      '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/zip';
    input.onchange = (event) => {
      const elem: any = event.target;
      if (elem.files && elem.files[0].name.indexOf('.csv') > 0) {
        //papaparse.js
        globalThis.Papa.parse(elem.files[0], {
          complete: function(results) {
            resolve(results.data); // 输出二维数组
          }
        });
        MessagePlugin.success($t('导入成功!'));
      }
    };
    input.click();
  });
}
