import {
	Component,
	EventEmitter,
	Input,
	OnDestroy,
	OnChanges,
	OnInit,
	Output,
	ApplicationRef,
	ChangeDetectorRef
} from '@angular/core';
import { NzMessageService, UploadXHRArgs, UploadFile } from 'ng-zorro-antd';



@Component({
	selector: 'app-form',
	templateUrl: './form.component.html',
	styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
	pageArr = [];//页数据
	fileList
	uploadUrl
	uploadData
	_item: any;

	KEY = 'hw_004';

	answerType = 'A';

	showGuideAudio;



	// @Input()
	set item(item) {
		this._item = item;
		// this.init();

	}
	get item() {
		return this._item;
	}

	@Output()
	update = new EventEmitter();


	constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef) {
		this.uploadUrl = (<any>window).courseware.uploadUrl();
		this.uploadData = (<any>window).courseware.uploadData();
		window['air'].getUploadCallback = (url, data) => {
			this.uploadUrl = url;
			this.uploadData = data;
		};
	}


	ngOnInit() {

		this.item = {};
		this.item.contentObj = {};


		const getData = (<any>window).courseware.getData;
		getData((data) => {

			if (data) {
				this.item = data;
			} else {
				this.item = {};
			}

			if (!this.item.contentObj) {
				this.item.contentObj = {};
			}

			console.log('~data:', data);
			if (data) {
				console.log('~data JSON:', JSON.stringify(data));
			}
			this.init();

			this.changeDetectorRef.markForCheck();
			this.changeDetectorRef.detectChanges();

			this.refresh();

		}, this.KEY);

		// this.initData();
	}
	ngOnChanges() {

	}

	ngOnDestroy() {
	}


	init() {
		if (this.item.contentObj.pageArr) {
			this.pageArr = this.item.contentObj.pageArr;
		} else {
			this.pageArr = this.getDefaultPicArr();
			this.item.contentObj.pageArr = this.pageArr;
		}
		this.save();
		console.log('item:', this.item);
	}


	getDefaultPicArr() {
		const arr = [];
		// for (let i = 0; i < 4; i ++) {
		//   const data = {};
		//   data['pic_url'] = '';
		//
		//   const soundArr = [];
		//   for (let i = 0; i < 3; i++) {
		//     const tmpData = {};
		//     tmpData['answer'] = false;
		//     tmpData['audio_url'] = '';
		//     soundArr.push(tmpData);
		//   }
		//   data['soundArr'] = soundArr;
		//
		//   arr.push(data);
		// }
		return arr;
	}



	initData() {

	}

	deletePage(data) {
		const index = this.pageArr.indexOf(data);
		if (index !== -1) {
			this.pageArr.splice(index, 1);
		}

		// this.update.emit(this.item);
		this.save();
	}


	deleteItem(data, j) {
		const index = this.pageArr[j].pageInfo.indexOf(data);
		if (index !== -1) {
			this.pageArr[j].pageInfo.splice(index, 1);
		}

		// this.update.emit(this.item);
		this.save();
	}

	onImageUploadSuccessByItem(e, item, id = null) {

		if (id != null) {
			item[id + '_pic_url'] = e.url;
		} else {
			item['groupPic'] = e.url;
		}

		this.save();
		// this.update.emit(this.item);

		// console.log('this.item: ', this.item);
	}

	onAudioUploadSuccessByItem(e, item, id = null) {
		if (id != null) {
			item[id + '_audio_url'] = e.url;
		} else {
			item.audio_url = e.url;
		}
		// this.update.emit(this.item);
		this.save();
	}

	uploadSuccess(file, item, key) {
		console.log(item);
		item[key] = file.response.url;
		item[key + '_name'] = file.name;
		this.save();
	}
	handleChange(info: { type: string, file: UploadFile, event: any }, item, key) {
		console.log('info:', info);
		switch (info.type) {
			case 'success':
				this.uploadSuccess(info.file, item, key);
				break;
		}
	}
	handleQuestionTypeChange(key) {
		if (key == 'Spine') {
			this.fileList = [
				{
					uid: '-1',
					name: this.item['ske_json'],
					status: 'done',
					url: this.item['ske_json']
				}
			]
		} else if (key == 'Image') {

		}
		this.saveItem()
		this.changeDetectorRef.detectChanges();
		this.changeDetectorRef.markForCheck();
	}

	//添加页面
	addPage() {
		const data = {
			pageInfo: []
		};
		this.pageArr.push(data);
		console.log(this.pageArr);
		this.saveItem();
	}

	//添加项进页面
	addPic(i) {
		const data = {
			a_pic_url: '',
			b_pic_url: '',
			a_audio_url: '',
			b_audio_url: '',
			groupLabel: '',
			groupPic: '',
			group_audio_url: '',

			type: '',
			ske_json: '',
			tex_json: '',
			tex_png: '',
			// uploadData: '',
			// uploadUrl: '',
		};
		this.pageArr[i].pageInfo.push(data);
		console.log(this.pageArr);
		this.saveItem();
	}

	radioClick(it, radioValue) {
		it.radioValue = radioValue;

		this.saveItem();
	}

	clickCheckBox() {
		console.log(' in clickCheckBox');
		this.saveItem();
	}


	saveItem() {
		console.log(' in saveItem');
		// this.update.emit(this.item);
		this.save();

	}

	onCopyData(index) {
		this.item.contentObj.pageArr.push(JSON.parse(JSON.stringify(this.item.contentObj.pageArr[index])));
		this.save();
		setTimeout(() => {
			window.scrollTo(0, document.body.scrollHeight);
		}, 1)
	}


	save() {
		(<any>window).courseware.setData(this.item, null, this.KEY);
		this.refresh();
		// 获取数据
		const getData = (<any>window).courseware.getData;
		getData((data) => {
			console.log('data:', data);
			// console.log('string:', JSON.stringify(data));
		}, this.KEY);
	}

	refresh() {
		setTimeout(() => {
			this.appRef.tick();
		}, 1);
	}

	guideBtnClick(value) {
		this.showGuideAudio = value;
	}

}

