import React from "react";
import {queryApiActionPath} from "@/webPublic/one_stop_public/utils/queryConfig";
import {apiRequest} from "@/webPublic/one_stop_public/utils/request";
import {getToken} from "@/webPublic/one_stop_public/utils/token";

const ShowItem = ({ basicUrl, type, x, y, ...otherInfo }) => {
  switch (type) {
    case 'image':
      return (
        <img
          draggable={false}
          key={otherInfo.key}
          src={basicUrl + otherInfo.path}
          style={{
            // border: '1px solid red',
            cursor: 'pointer',
            width: otherInfo.w,
            height: otherInfo.h,
            zIndex: otherInfo.index || 1,
          }}
        />
      );
    case 'text':
      return (
        <p
          draggable={false}
          key={otherInfo.key}
          style={{
            // border: '1px solid red',
            cursor: 'pointer',
            fontSize: otherInfo?.fontSize ? otherInfo.fontSize + 'px' : undefined,
            fontFamily: otherInfo?.fontFamily ? otherInfo.fontFamily : undefined,
            fontWeight: otherInfo?.fontStyle ? otherInfo.fontStyle : undefined,
            color: otherInfo?.color ? otherInfo.color : undefined,
            zIndex: otherInfo.index || 1,
          }}
        >
          {otherInfo.word}
        </p>
      );
  }
};


export const dragEventList = (setOtherProps, otherProps) => {
  let draggedRef = null;
  document.addEventListener(
    'dragstart',
    function(event) {
      // 保存拖动元素的引用(ref.)
      draggedRef = event.target;
      // 使其半透明
      event.target.style.opacity = 0.5;
    },
    false,
  );
  document.addEventListener(
    'dragend',
    (event) => {
      // 重置透明度
      event.target.style.opacity = '';
    },
    false,
  );

  /* 放下目标节点时触发事件 */
  document.addEventListener(
    'dragover',
    (event) => {
      // 阻止默认动作
      event.preventDefault();
    },
    false,
  );
  document.addEventListener(
    'drop',
    (event) => {
      // 阻止默认动作（如打开一些元素的链接）
      event.preventDefault();
      // 将拖动的元素到所选择的放置目标节点中
      // console.log('drop');
      if (event.target.id === 'dropZone') {
        let left = event.offsetX;
        if (left > event.target.offsetWidth - draggedRef.offsetWidth - 10) {
          console.log('拖拽到了图片区域外部,不能进行拖拽');
          return false;
        }
        let top = event.offsetY;
        let key = draggedRef?.dataset?.mes || draggedRef?.parentNode?.dataset?.mes;
        let item = otherProps.signConfig.find((g) => {
          return g.key === key;
        });
        if(!item){
          return false;
        }
        // left = left - (item.x /2 );
        // top = top - (item.y / 2);
        item.x = left;
        item.y = top;
        // console.log(left, top);
        setOtherProps({
          ...otherProps,
          signConfig: otherProps.signConfig,
        })
        draggedRef.style.left = left; // `${left}px`;
        draggedRef.style.top = top; // `${top}px`;
      }
      return true;
    },
    false,
  );
}

const uploadFile = (file) => {
  let url = queryApiActionPath() + '/upload?token=' + getToken();
  const formData = new FormData();
  formData.append('file', file);
 return fetch(url, {
    method: 'POST',
    headers: {
      Accept: '*/*',
    },
    body: formData,
  })
    .then((res) => {
      return res.text();
    })
    .then((res) => {
      return res;
    })
}


// 将图片宽度确定 高度按比例调整后返回一张新的图片
export const zipImage = (path, fileName, limitWidth = 1200) => {
  return new Promise((resolve, reject) => {
    let image = new Image(); //新建一个img标签（还没嵌入DOM节点)
    let imageUrl = queryApiActionPath()  + path;
    image.setAttribute("crossOrigin",'Anonymous');
    image.src = imageUrl;
    image.onload = () => {
      // console.log('123');
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      const imageWidth = limitWidth;
      const ratio = image.width / limitWidth;  // 按宽度固定 压缩图片
      if(ratio === 1 || isNaN(ratio)){
        resolve(path);
        return true;
      }
      const imageHeight = parseInt(image.height / ratio, 10);
      let data = '';
      canvas.width = imageWidth;
      canvas.height = imageHeight;
      // console.log(imageWidth, imageHeight);
      context.drawImage(image, 0, 0, imageWidth, imageHeight);
      data = canvas.toDataURL('image/jpeg');
      const dataURLtoFile = (dataurl, filename) => {  // 将base64转换为文件
        let arr = dataurl.split(',');
        let mime = arr[0].match(/:(.*?);/)[1];

        let bstr = atob(arr[1]);
        let n = bstr.length;
        let u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
      };
      let file = dataURLtoFile(data, fileName);
      uploadFile(file).then((res) => {
        if(res){
          resolve(res);
        }else{
          resolve(path);
        }
      });
      //压缩完成
    };
  });


};


export default ShowItem
