import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import { Sheepfold, Sheep, Course } from './Course';



@Component({
	selector: 'app-form',
	templateUrl: './form.component.html',
	styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {

	// 储存数据用
	saveKey = "ET26";
	// 储存对象
	item;


	constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef) {

	}


	ngOnInit() {
		this.item = new Course();

		// 获取存储的数据
		(<any>window).courseware.getData((data) => {
			if (data) {
				this.item = data;
			}
			console.log(data);
			this.init();
			this.changeDetectorRef.markForCheck();
			this.changeDetectorRef.detectChanges();
			this.refresh();

		}, this.saveKey);
		console.log(this.item);
	}


	ngOnChanges() {
	}

	ngOnDestroy() {
	}

	init() {
		if (!this.item) {
			this.item = new Course();
		}
		if (this.item && (this.item.sheepfoldArr.length < 1)) {
			for (var i = 0; i < 3; i++) {
				this.addSheepfold();
			}
		}
	}

	/**
	* 储存图片数据
	* @param e
	*/
	onImageUploadSuccess(e, item, key) {

		item[key] = e.url;
		this.save();
	}

	/**
	 * 储存音频数据
	 * @param e
	 */
	onAudioUploadSuccess(e, item, key) {

		item[key] = e.url;
		this.save();
	}

	/**
	 * 储存数据
	 */
	save() {
		(<any>window).courseware.setData(this.item, null, this.saveKey);
		this.refresh();
		console.log(this.item);

		console.log(JSON.stringify(this.item));
	}

	/**
	 * 刷新 渲染页面
	 */
	refresh() {
		setTimeout(() => {
			this.appRef.tick();
		}, 1);
	}

	randomChar() {
		var x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
		var tmp = "";
		var timestamp = new Date().getTime();
		for (var i = 0; i < 6; i++) {
			tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
		}

		return timestamp + tmp;
	}

	addSheepfold() {
		if (this.item.sheepfoldArr.length >= 6) {
			return
		}

		let sheepfold = new Sheepfold();

		sheepfold.id = this.randomChar();

		this.item.sheepfoldArr.push(sheepfold);

		this.save();
	}

	delSheepfold(index) {
		if (index < 3) return
		if (index !== -1) {
			this.item.sheepfoldArr.splice(index, 1);
			this.save();
		}
	}

	addSheep() {
		if (this.item.sheepArr.length >= 30) {
			return
		}
		let sheep = new Sheep();

		this.item.sheepArr.push(sheep);

		this.save();
	}

	delSheep(index) {
		if (index !== -1) {
			this.item.sheepArr.splice(index, 1);
			this.save();
		}
	}

	setSheepfoldId(event, item) {
		item.sheepfoldId = event;
		this.save();
	}

	setContentType(e, item) {
		item['contentType'] = e;

		if ("T" == e) {
			item['picUrl'] = "";
		}
		else if ("P" == e) {
			item['word'] = "";
		}

		this.save();
	}
}

