import { Component, EventEmitter, Input, Output, OnInit, ChangeDetectorRef } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AssessmentModel } from 'src/app/shared/model/assessment.model';
import { MyCompetencyAssessmentModel } from 'src/app/shared/model/competency-assessment.model';
import { MyCompetencyCourseModel } from 'src/app/shared/model/competency-course.model';
import { MyCompetencyIndicatorsCourses1ListModel } from 'src/app/shared/model/competency-indicators-courses1-list.model';
import { MyCompetencyIndicatorsCourses2ListModel } from 'src/app/shared/model/competency-indicators-courses2-list.model';
import { CompetencytopicModel, MyCompetencytopicModel } from 'src/app/shared/model/competencytopic.model';
import { IndicatorsCoursesModel, MyIndicatorsCoursesModel } from 'src/app/shared/model/indicators-courses.model';
import { AssessmentService } from 'src/app/shared/services/assessment.service';
import { CompetencycourseService } from 'src/app/shared/services/competencycourse.service';
import { FileService } from 'src/app/shared/services/file.service';
import { IndicatorsCoursesService } from 'src/app/shared/services/indicators-courses.service';
export interface DataModel {
	code: string,
	behaviorIndicators: string[],
	assessmentTools: AssessmentToolsModal[][],
	curriculum: CurriculumModal[]
}
export interface AssessmentToolsModal {
	code: string,
	name: string,
	nameShow: string,
}
export interface CurriculumModal {
	code: string,
	name: string
}
@Component({
	selector: 'app-edit-group-indicators',
	templateUrl: './edit-group-indicators.component.html',
	styleUrls: ['./edit-group-indicators.component.scss']
})
export class EditGroupIndicators implements OnInit {
	@Input() competencytopic: CompetencytopicModel = new MyCompetencytopicModel({})
	@Input() seeTab = false
	indicatorsCourses: IndicatorsCoursesModel = new MyIndicatorsCoursesModel({})
	@Output() sendEdit: EventEmitter<boolean> = new EventEmitter<boolean>();
	search = ""
	currentPage = 1
	pageSize = 10
	page = Array.from({ length: 1 }, (_, i) => i + 1);
	dataList: DataModel[] = []
	dataSelect: DataModel = {
		code: "",
		behaviorIndicators: [],
		assessmentTools: [],
		curriculum: []
	}
	dataSelectIndex: number = -1
	behaviorIndicatorsSelectIndex: number = -1
	dataSelectAssessmentToolsIndex: number = -1
	searchModal = ""
	currentPageModal = 1
	pageSizeModal = 10
	pageModal = Array.from({ length: 1 }, (_, i) => i + 1);
	assessmentToolsLoading = false
	assessmentToolsList: AssessmentToolsModal[] = []
	assessmentToolsSelectIndex: number[] = [0, 0]
	curriculumList: CurriculumModal[] = []
	curriculumLoading = false
	curriculumSelectIndex: number = -1
	dataLoading = false

	constructor(private assessmentService: AssessmentService,
		private cdr: ChangeDetectorRef,
		private toastr: ToastrService,
		private competencycourseService: CompetencycourseService,
		private indicatorsCoursesService: IndicatorsCoursesService,
	) {

	}

	ngOnInit() {
		this.getIndicatorsCoursesById()
		this.getAssessmentList()
		this.getCompetencycourseList()
	}


	clearDataList() {
		this.dataList = this.dataList.map(x => ({
			code: x.code,
			behaviorIndicators: [],
			assessmentTools: [],
			curriculum: []
		}))
	}
	getIndicatorsCoursesById() {
		this.dataLoading = true
		this.indicatorsCoursesService.getById(this.competencytopic.competencyTopicId).subscribe({
			next: response => {
				this.indicatorsCourses = new MyIndicatorsCoursesModel(response)
				this.dataList = this.indicatorsCourses.competencyIndicatorsCourses1List.map(x => {
					const behaviorIndicators = x.competencyIndicatorsCourses2List.map(x => x.behavioralIndicators).concat([""]);
					let assessmentTools = x.competencyIndicatorsCourses2List.map(x =>
						x.competencyAssessment.map(y => ({ code: y.assessmentId, nameShow: y.shortName, name: y.tdesc }))
					);
					while (assessmentTools.length < behaviorIndicators.length - 1) {
						assessmentTools.push([]);
					}
					return {
						code: x.lineNo + '' || '0',
						behaviorIndicators,
						assessmentTools,
						curriculum: x.competencyCourse.map(x => ({ code: x.competencyCourseId, name: x.tdesc }))
					};
				});
				this.dataList.sort((a, b) => +a.code - +b.code)
				let maxCode = Math.max(0, ...this.dataList.map(x => +x.code))
				while (this.dataList.length < +this.indicatorsCourses.competencyTopic.expectationLevel) {
					this.dataList.push({
						code: (++maxCode) + "",
						behaviorIndicators: [""],
						assessmentTools: [],
						curriculum: []
					})
				}
				this.dataLoading = false
				this.searchChange()
				this.cdr.detectChanges()
			}, error: error => {
				this.dataLoading = false
				this.cdr.detectChanges()
			}
		})
	}
	deleteBehaviorIndicators() {
		if (this.dataSelectIndex > -1) {
			this.dataList[this.dataSelectIndex].assessmentTools = this.dataList[this.dataSelectIndex].assessmentTools.filter((_, i) => i != this.behaviorIndicatorsSelectIndex)
			this.dataList[this.dataSelectIndex].behaviorIndicators = this.dataList[this.dataSelectIndex].behaviorIndicators.filter((_, i) => i != this.behaviorIndicatorsSelectIndex)
		}
	}
	addBehaviorIndicators() {
		if (this.dataSelectIndex > -1) {
			this.dataList[this.dataSelectIndex].assessmentTools.push([])
			this.dataList[this.dataSelectIndex].behaviorIndicators.push("")
		}
	}
	getAssessmentList() {
		this.assessmentToolsLoading = true
		this.assessmentService.getList().subscribe({
			next: response => {
				this.assessmentToolsList = response.map(x => (
					{ code: x.assessmentId, nameShow: x.shortName, name: x.tdesc }
				))
				this.assessmentToolsLoading = false
				this.cdr.detectChanges()
			}, error: error => {
				this.assessmentToolsLoading = false
				this.cdr.detectChanges()
			}
		}
		)
	}
	deleteAssessmentTools() {
		if (this.dataSelectIndex > -1) {
			this.dataList[this.dataSelectIndex].assessmentTools[this.assessmentToolsSelectIndex[0]] = this.dataList[this.dataSelectIndex].assessmentTools[this.assessmentToolsSelectIndex[0]].filter((_, i) => i != this.assessmentToolsSelectIndex[1])
		}
	}
	addAssessmentTools(data: AssessmentToolsModal) {
		if (this.dataSelectIndex > -1) this.dataList[this.dataSelectIndex].assessmentTools[this.assessmentToolsSelectIndex[0]].push(data)
	}
	deleteCompetencycourse() {
		if (this.dataSelectIndex > -1) {
			this.dataList[this.dataSelectIndex].curriculum = this.dataList[this.dataSelectIndex].curriculum.filter((_, i) => i != this.curriculumSelectIndex)
		}
	}
	addCompetencycourse(data: CurriculumModal) {
		if (this.dataSelectIndex > -1) this.dataList[this.dataSelectIndex].curriculum.push(data)
	}
	getCompetencycourseList() {
		this.curriculumLoading = true
		this.competencycourseService.getList().subscribe({
			next: response => {
				this.curriculumList = response.map(x => ({ code: x.competencyCourseId, name: x.tdesc }))
				this.curriculumLoading = false
				this.cdr.detectChanges()
			}, error: error => {
				this.curriculumLoading = false
				this.cdr.detectChanges()
			}
		})
	}
	onEdit() {
		this.sendEdit.emit(false);
	}
	searchChange() {
		this.currentPage = 1;
		const filteredData = this.dataListFilter();
		this.page = Array.from({ length: Math.ceil(filteredData.length / 10) }, (_, i) => i + 1);
	}
	dataListFilter() {
		return this.dataList.filter(x => {
			const match = x.code.includes(this.search);
			return match;
		});
	}

	assessmentToolsModalSearchChange() {
		this.currentPageModal = 1;
		const filteredData = this.assessmentToolsListFilter();
		this.pageModal = Array.from({ length: Math.ceil(filteredData.length / 10) }, (_, i) => i + 1);
	}
	assessmentToolsListFilter() {
		if (this.dataSelectIndex > -1) {
			const assessmentTools = this.dataList[this.dataSelectIndex].assessmentTools.length ? this.dataList[this.dataSelectIndex].assessmentTools[this.assessmentToolsSelectIndex[0]] : []
			const dataList = (this.assessmentToolsSelectIndex[1] == this.dataSelect.assessmentTools.length) ?
				this.assessmentToolsList.filter(x => !assessmentTools.some(y => y.code == x.code)) :
				this.dataList[this.dataSelectIndex].assessmentTools[this.assessmentToolsSelectIndex[0]]
			return dataList?.filter(x => {
				const match = x.code.includes(this.searchModal) || x.name.includes(this.searchModal);
				return match;
			}) || []
		}
		return []
	}

	curriculumModalSearchChange() {
		this.currentPageModal = 1;
		const filteredData = this.curriculumListFilter();
		this.pageModal = Array.from({ length: Math.ceil(filteredData.length / 10) }, (_, i) => i + 1);
	}
	curriculumListFilter() {
		if (this.dataSelectIndex > -1) {
			const dataList = this.curriculumList.filter(x => !this.dataList[this.dataSelectIndex].curriculum.some(y => y.code == x.code))
			return dataList.filter(x => {
				const match = x.code.includes(this.searchModal) || x.name.includes(this.searchModal);
				return match;
			});
		}
		return []
	}
	addCurriculumList(data: CurriculumModal) {
		if (this.dataSelectIndex > -1) {
			this.dataList[this.dataSelectIndex].curriculum.push(data)
		}
	}
	deleteCurriculumList() {
		if (this.dataSelectIndex > -1) {
			this.dataList[this.dataSelectIndex].curriculum = this.dataList[this.dataSelectIndex].curriculum.filter((_, i) => i != this.curriculumSelectIndex)
		}
	}

	saveIndicatorsCourses() {
		const body = new MyIndicatorsCoursesModel({
			...this.indicatorsCourses,
			competencyIndicatorsCourses1List: this.dataList.map(x =>
				new MyCompetencyIndicatorsCourses1ListModel({
					competencyCourse: x.curriculum.map(y => new MyCompetencyCourseModel({
						competencyCourseId: y.code,
						tdesc: y.name
					})),
					competencyCourseId: x.curriculum.map(y => y.code).join(","),
					competencyIndicatorsCourses2List: x.assessmentTools.map((y, i) => new MyCompetencyIndicatorsCourses2ListModel({
						assessmentId: y.map(z => z.code).join(','),
						behavioralIndicators: x.behaviorIndicators[i],
						competencyAssessment: y.map(z => new MyCompetencyAssessmentModel({
							assessmentId: z.code,
							tdesc: z.name,
							shortName: z.nameShow
						}))
					}))

				}))
		})
		this.indicatorsCoursesService.post(body).subscribe({
			next: response => {
				if (response.success) {
					this.showAlert(response.message, 'success')
				} else {
					this.showAlert(response.message, 'error')
				}
			}, error: error => {
				this.showAlert(error.message, 'error')
			}
		})
	}
	showAlert(text: string, type: 'success' | 'error') {
		this.toastr[type](text, 'แจ้งเตือน', {
			timeOut: 3000,
			positionClass: 'toast-top-right',
		})
	}
}
