import React, { useState } from 'react';
import { isJSON } from '@/webPublic/one_stop_public/copy';

/***
 * 处理铜川学生头像颠倒的bug
 * */
export default function HandlePhoto({ urlObj, style, ...props }) {
  let url = '';
  try {
    url = JSON.parse(urlObj).url;
  } catch (e) {
    url = urlObj;
  }
  const [needTransForm, setTransform] = useState(false);
  if (url) {
    getIsNeedTransform(url).then(res => {
      if (res) {
        setTransform(true);
      }
    });
  } else {
    return null;
  }
  let styleThis = {
    ...style,
    transform: needTransForm ? 'rotate(-90deg)' : 'none',
  };
  return <img src={url} {...props} style={styleThis} />;
}

export function getIsNeedTransform(url) {
  return new Promise((resolve, reject) => {
    if (url) {
      const img = new Image();
      img.src = url;
      // 判断是否有缓存
      if (img.complete) {
        // 打印
        if (img.width > img.height) {
          resolve(true);
        } else {
          resolve(false);
        }
      } else {
        // 加载完成执行
        img.onload = () => {
          if (img.width > img.height) {
            resolve(true);
          } else {
            resolve(false);
          }
        };
      }

      img.onerror = () => {
        resolve(false);
      };
    }
  });
}

/**
 * [
 * {
 * "downloadUrl":"http://192.168.1.122:8101/dsf/download?filePath=/u/upload/202009/08151011zzxg.png",
 * "fileExt":"png",
 * "fileName":"首页-系统导览.png",
 * "filePath":"/u/upload/202009/08151011zzxg.png",
 * "id":492,
 * "previewType":"picture",
 * "url":"http://192.168.1.122:8101/dsf/u/upload/202009/08151011zzxg.png",
 * }]
 *
 * */
export function getFileInfo(fileJsonStr) {
  if (!fileJsonStr || !isJSON(fileJsonStr)) {
    if (fileJsonStr && typeof fileJsonStr === 'string' && fileJsonStr.indexOf('http') <= -1 && fileJsonStr.length > 10) {
      // 拼一站式的 图片路径 可能需要修改
      // /u/asda/1.png
      let prefix = window.specialImportantSystemConfig && window.specialImportantSystemConfig.dfs;
      if (fileJsonStr.startsWith('/u/')) { // 一站式的图片
        // console.log('一站式图片地址拼接');
        prefix = window.specialImportantSystemConfig && window.specialImportantSystemConfig.sqlFormsServer;
      }
      let r = {
        downloadUrl: '',
        url: prefix + fileJsonStr,
        fileName: '',
      }
      r.url = r.url ? r.url.replace('/dsf/dsf/', '/dsf/') : '';
      return r;
    } else {
      if (fileJsonStr && typeof fileJsonStr === 'string' && fileJsonStr.indexOf('http') > -1 && fileJsonStr.length > 10) {
        return {
          downloadUrl: '',
          url: fileJsonStr,
          fileName: '',
        };
      } else {
        return {
          downloadUrl: '',
          url: '',
          fileName: '',
        };
      }
    }
  } else {
    if (isJSON(fileJsonStr)) {
      fileJsonStr = JSON.parse(fileJsonStr);
      if (fileJsonStr.url) {
        return fileJsonStr;
      } else {
        return {
          downloadUrl: '',
          url: '',
          fileName: '',
        };
      }
    } else {
      return {
        downloadUrl: '',
        url: '',
        fileName: '',
      };
    }
  }
}

/**
 * 图片压缩函数
 * 返回一个promise  resolve 新的文件
 * */
export const zipImage = (file, fileSizeLimitMb = 3) => {
  let fileSizeMb = file.size / 1024 / 1024;
  console.log(fileSizeMb);

  let fileName = file.name;
  if (fileSizeMb < fileSizeLimitMb) {
    // 1MB 以下的图片不需要压缩。
    return new Promise((resolve, reject) => {
      resolve(file);
    });
  }
  let reader = new FileReader();
  reader.readAsDataURL(file);
  return new Promise((resolve, reject) => {
    reader.onload = e => {
      //这里的e.target.result就是转换后base64格式的图片文件
      let image = new Image(); //新建一个img标签（还没嵌入DOM节点)
      image.src = e.target.result;
      return (image.onload = () => {
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');
        let imageWidth = image.width * 0.3; //压缩后图片的大小
        let imageHeight = image.height * 0.3;
        let data = '';
        canvas.width = imageWidth;
        canvas.height = imageHeight;

        context.drawImage(image, 0, 0, imageWidth, imageHeight);
        data = canvas.toDataURL('image/jpeg');
        let zipFile = dataURLtoFile(data, fileName);
        console.log(zipFile);
        resolve(zipFile);
        //压缩完成
      });
    };
  });
};

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 });
};

export function formatFileJson(fileString) {
  if (isJSON(fileString)) {
    let fileAll = JSON.parse(fileString);
    if (fileAll && Array.isArray(fileAll.files)) {
      let files = fileAll.files;
      for (let item of fileAll.files) {
        item.path = getFileInfo(item.path).url;
      }
      return files;
    }
  }
  return [];
}
