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


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

	// 储存数据用
	saveKey = "OP26";
	// 储存对象
	uploadUrl
	uploadData
	item;

	questionArr = [];

	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 = {
			question_arr: []
		};

		// 获取存储的数据
		(<any>window).courseware.getData((data) => {

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

			console.log('data: ', data);

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

		}, this.saveKey);
	}

	ngOnChanges() {
	}

	ngOnDestroy() {
	}

	init() {
		if (!this.item.question_arr) {
			this.item.question_arr = [];
		}
		this.questionArr = this.item.question_arr;
	}

	addQuestionBtnClick() {
		this.questionArr.push({
			question_audio_url: '',
			option_arr: [ //选项 （多选）

			]
		})
		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;
		}
	}

	addOptionBtnClick(question) {
		question.option_arr.push({
			text: '',
			pic_url: '', // 图片路径
			audio_url: '', //音频路径
			is_right: false, //是否正确
		})
		this.save();
	}

	deleteQuestionBtnClick(index) {
		this.questionArr.splice(index, 1);
		this.save();
	}

	deleteOptionBtnClick(option, index) {
		option.splice(index, 1)
		this.save();
	}

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

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

	/**
	 * 储存音频数据
	 * @param e
	 */
	onAudioUploadSuccess(e, key, item) {
		item[key] = e.url;
		this.save();
	}

	onWordAudioUploadSuccess(e, idx) {
		this.item.wordList[idx].audio = e.url;
		this.save();
	}

	onBackWordAudioUploadSuccess(e, idx) {
		this.item.wordList[idx].backWordAudio = e.url;
		this.save();
	}

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

		this.refresh();
		console.log('this.item = ' + JSON.stringify(this.item));
	}

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

}