import React, { useState } from 'react';


/***
 * 处理铜川学生头像颠倒的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);
			};
		}
	});
}
