import React from 'react';
import { queryApiActionPath, queryFileUrl } from '@/webPublic/one_stop_public/utils/queryConfig';
import { getToken } from '@/webPublic/one_stop_public/utils/token';
import { isFromIframe } from '@/webPublic/one_stop_public/utils/utils';
import getOneStopUploadUrl from '@/webPublic/one_stop_public/Base16/getOneStopUploadUrl';
import {
  getSassApiHeader,
  getSysCode
} from '@/webPublic/one_stop_public/2023yunshangguizhou/utils';


const oneSetItemP = {
  marginBottom: 0,
  userSelect: 'none',
};
let startX = 0;
let startY = 0;

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',
            ...oneSetItemP,
            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;
  let documentThis = isFromIframe() ? window?.parent?.document : document;
  documentThis.onmousedown = function (evt) {
    startX = evt.offsetX;
    startY = evt.offsetY;
  };

  documentThis.addEventListener(
    'dragstart',
    function (event) {
      // 保存拖动元素的引用(ref.)
      draggedRef = event.target;
      event.target.style.opacity = 0.2;
    },
    false,
  );
  documentThis.addEventListener(
    'dragend',
    (event) => {
      // 重置透明度
      event.target.style.opacity = '';
    },
    false,
  );

  /* 放下目标节点时触发事件 */
  documentThis.addEventListener(
    'dragover',
    (event) => {
      // 阻止默认动作
      event.preventDefault();
    },
    false,
  );
  documentThis.addEventListener(
    'drop',
    (event) => {
      // 阻止默认动作（如打开一些元素的链接）
      event.preventDefault();
      // 将拖动的元素到所选择的放置目标节点中
      let infoClientRect = documentThis.getElementById('dropZone')
        .getBoundingClientRect();
      // console.log(startX, typeof startX, startY);
      // return ;
      let leftNew = Math.ceil(event.clientX - infoClientRect.left) - startX;
      let topNew = Math.ceil(event.clientY - infoClientRect.top) - startY;
      // console.log(leftNew, topNew);
      if (leftNew < 0 || leftNew > infoClientRect.width || topNew < 0 || topNew > infoClientRect.height) {
        console.log('拖拽到了图片区域外部,不能进行拖拽');
        return false;
      }

      let key = draggedRef?.dataset?.mes || draggedRef?.parentNode?.dataset?.mes;
      let item = otherProps.signConfig.find((g) => {
        return g.key === key;
      });
      if (!item) {
        return false;
      }
      item.x = leftNew;
      item.y = topNew;
      setOtherProps({
        ...otherProps,
        signConfig: otherProps.signConfig,
      });
      draggedRef.style.left = leftNew; // `${left}px`;
      draggedRef.style.top = topNew; // `${top}px`;
      return true;
    },
    false,
  );
};

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

export const uploadWordToHtml = (file) => {
  let url = queryApiActionPath() + '/ImageLibApi/convert';
  const formData = new FormData();
  formData.append('file', file);
  formData.append('base', window.specialImportantSystemConfig.dfs);
  formData.append('token', getToken());
  return fetch(url, {
    method: 'POST',
    headers: {
      Accept: '*/*',
      ...getSassApiHeader(),
    },
    body: formData,
  })
    .then((res) => {
      return res.json();
    })
    .then((res) => {
      return res;
    });
};


// 将图片宽度确定 高度按比例调整后返回一张新的图片
export const zipImage = (path, fileName, limitWidth = 1200) => {
  return new Promise((resolve, reject) => {
    let image = new Image(); //新建一个img标签（还没嵌入DOM节点)
    let imageUrl = queryFileUrl(path);
    image.setAttribute('crossOrigin', 'Anonymous');
    image.src = imageUrl;
    image.onload = () => {
      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;
