class Element {
	constructor() {
        this.oldProps = null;
		this.note = ""; // 备注
	}

    setProps(newProps, isCloneProps = false) {
		if(isCloneProps) {
			this.oldProps = this.cloneProps(this);
		}
		
		if((newProps['font'] || newProps['paragraph']) && !newProps['mode']) {
			if(newProps['font']) {
				Object.assign(this.font, newProps['font']);	
			} else if(newProps['paragraph']) {
				Object.assign(this.paragraph, newProps['paragraph']);	
			}
		} else {
			//注意！此方法对一层树结构合并没问题，但若是对象里的属性还是一个对象，则进行合并时，该属性里的对象会被覆盖而非合并操作
			Object.assign(this, newProps);
		}
		
		//在属性合并完成后单独对相对于画布左上角的y(this.y)和打印时输出的y(this.printedY)进行调整
		if(typeof newProps.printedY === 'undefined') {
			this.printedY = this.y - this.prevChunkBaseline;	
		} else  {
			this.y = this.prevChunkBaseline + this.printedY;
		}
    }

    getProp(prop) {
		if(this[prop] !== null && this[prop] !== undefined) {
		  return this[prop];	
		} else if(this.font && this.font[prop] !== null && this.font[prop] !== undefined) {
		  return this.font[prop];
		} else if(this.paragraph && this.paragraph[prop] !== null && this.paragraph[prop] !== undefined) {
			return this.paragraph[prop];
		}
		
		return (undefined);
    }
	
	cloneProps(props) {
		let clonedProps = Array.isArray(props) ? [] : {};
		
		if(props && typeof props == 'object') {
			for(let key in props) {
				if(props.hasOwnProperty(key) && key != 'oldProps') {
					if(props[key] && typeof props[key] == 'object') {
						clonedProps[key] = this.cloneProps(props[key]);
					} else {
						clonedProps[key] = props[key];
					}
				}
			}
		}
		
		return clonedProps;
	}
	
	// 替换特殊字符
	replaceCharacter(str) {
		if (str != null) {
			while (str.indexOf('&') != -1 || str.indexOf('"') != -1 || str.indexOf('<') != -1 || str.indexOf('>') != -1) {
				str = str.replace(/&/g, '@amp;');
				str = str.replace(/\"/g, '@quot;');
				str = str.replace(/</g, '@lt;');
				str = str.replace(/>/g, '@gt;');
			}
			return str;
		}
		return '';
	}

	replaceXML(str) {
		if (str != null) {
			while (str.indexOf('"') != -1) {
				str = str.replace(/\"/g, '@quot;');
			}
			return str;
		}
		return '';
	}

	replaceText(text) {
		if(text != null) {
			text += '';
			text = text.replace(/\!/, '');
			text = text.replace(/\[/, '');
			text = text.replace(/\]/, '');
			text = text.replace(/\</, '');
			text = text.replace(/\>/, '');
			text = text.replace(/(CDATA)/, '');

			return text;
		} else {
			return '';
		}
	}
}

export default Element;