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 &&
      fileJsonStr.indexOf('http') <= -1 &&
      fileJsonStr.length > 10
    ) {
      // 拼一站式的 图片路径 可能需要修改
      const prefix = window.specialImportantSystemConfig && window.specialImportantSystemConfig.dfs;
      return {
        downloadUrl: '',
        url: prefix + fileJsonStr,
        fileName: '',
      };
    } else {
      if (fileJsonStr && 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: '',
      };
    }
  }
}
