import { Graph, Shape, Addon, DataUri } from '@antv/x6';
import QRCode from 'qrcode';


// 字符串转base64
const textQrcodeToBase64 = text => {
  return new Promise((res, rej) => {
    QRCode.toDataURL(
      text, // 二维码字符串
      {
        type: 'image/png', // 生成dataurl图片格式
        width: 200, // 二维码宽度
        quality: 0.8, // 质量
        margin: 1, // 白边大小
        color: {
          dark: '#000', // 暗色颜色
          light: '#fff', // 亮色颜色
        },
      },
      (err, dataUrl) => {
        if (err) rej(err);
        res(dataUrl);
      },
    );
  });
};
export default function CreateJPEG(dom) {
  let graph = new Graph(
    {
      container: dom,
      width: 1,
      height: 1,
      background: {
        color: '#ddd',
      },
      grid: {
        size: 10,
        visible: true,
      },
      history: true,
      resizing: {
        enabled: true,
        restricted: true,
      },
    },
  );
  return async function (json, tempStr,assetNo) {
    let test = JSON.parse(tempStr);
    let tempObj = JSON.parse(test);
    for (const key in json) {
      for (let index = 0; index < tempObj.cells.length; index++) {

        if (tempObj.cells[index].data.type == key) {
          if (tempObj.cells[index].shape == 'image') {
            tempObj.cells[index].attrs.image['xlink:href'] = await textQrcodeToBase64(json[key]);
          }
          if (tempObj.cells[index].shape == 'rect') {
            tempObj.cells[index].attrs.label.text = tempObj.cells[index].attrs.label.text + json[key];
          }
        }
      }
    }
    graph.fromJSON(tempObj);
    return new Promise(res => {
      setTimeout(() => {
        graph.toJPEG(dataUri => {
          // dataUri就是base64的图片地址
          res(dataUri);
          // DataUri.downloadDataUri(dataUri, assetNo);
        }, {
          serializeImages: true,
          quality: 1,
        });
      }, 500);
    });
  };
}
export const base64toFile = (url, imageName) => {
  const arr = url.split(',');
  const mime = arr[0].match(/.*?:(.*?);/)[1];
  const suffix = mime.split('/')[1];
  const bstr = window.atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], `${imageName}.${suffix}`, {
    type: 'image/jpeg',
  });
};