"use strict";

appCore.controller("AssessmentScheduleCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter", '$uibModal', function ($state, $scope, $http, $timeout, vServices, filterFilter, $uibModal) {
	$scope.$root.page.title = "Create/Schedule Assessment";
	$scope.createButton = { heading: "Add", text: "Submit", icon: "fa-save", today: new Date() };
	$scope.data = [];
	$scope.sequencesave = [];
	$scope.questionIds = '';
	$scope.sortArray = [];

	const initDate = (d) => {
		if (d && d.length === 10) d = moment(d, 'DD-MM-YYYY').format();
		else if (d && moment(d).isValid()) d = moment(d).format();
		else d = moment().format();
		return d;
	};

	$scope.createSchedule = (jsonQ, idx = null, opts = 'create') => {
		if (!jsonQ) {
			const date1 = ($scope.data.length == 0) ? initDate($scope.data[$scope.data.length - 1]) : initDate($scope.data[$scope.data.length - 1].ae_to);
			// console.log(date1)
			const date = date1,
				firstDate = moment(date).add(1, 'days'),
				lastDate = moment(firstDate).add(3, 'months');
			jsonQ = {
				"ae_id": null,
				"ae_name": `ASSESSMENT_${moment(firstDate).format('YYYYMM')}_${moment(lastDate).add(3, 'months').format('YYYYMM')}`,
				"ae_sys_name": `ASSESSMENT_${moment(firstDate).format('YYYYMM')}_${moment(lastDate).add(3, 'months').format('YYYYMM')}`,
				"ae_from": moment(firstDate).format('YYYY-MM-DD'),
				"ae_to": moment(lastDate).subtract(1, 'days').format('YYYY-MM-DD'),
				"ae_active_from": moment(lastDate).format('YYYY-MM-DD'),
				"ae_hero_lock": 5,
				"ae_manager_lock": 7,
				"ae_status": "draft",
				"ae_cby": 1,
				"ae_mby": 1,
				"is_overall": false,
				"description": '',
				"is_show_score": false,
				"total_score": 100
			};
		}

		let modalInstance = $uibModal.open({
			animation: true,
			templateUrl: 'modelAssessmentSchedule.html',
			controller: 'modelAssessmentScheduleCtrl',
			size: 'xl',//sm md,lg,xl
			controllerAs: "$scope",
			backdrop: "static",
			keyboard: false,
			resolve: {
				data: () => {
					return { idx, opts, single: JSON.parse(JSON.stringify(jsonQ)) };
				}
			}
		});

		modalInstance.result.then(function (result) {
			//console.log(JSON.stringify(result, null, 2));
			if (result && (result.idx || (typeof result.idx === 'number' && result.idx > -1))) {
				// console.log(result.data);
				vServices.callApi("/employee/getAssessmentSchedule", "POST", result.data).then(as => {
					result.data.ae_id = parseInt(as);
					$scope.data[idx] = result.data;
					toastr.success('Edited successfully');
				});
			}
			else if (result && !result.idx) {
				// console.log(result.data);
				vServices.callApi("/employee/getAssessmentSchedule", "POST", result.data).then(as => {
					result.data.ae_id = parseInt(as);
					$scope.data.push(result.data);
					toastr.success('Saved successfully');
				});
			}
		}, () => {
			//$log.info('Modal dismissed at: ' + new Date());
		});
	};



	$scope.addQuestions = (jsonQ, idx = null) => {
		$scope.createSchedule(jsonQ, idx, 'question');
	};
	$scope.cloneSchdule = (jsonQ, idx = null) => {
		const _html = `Do you real want to clone the "<strong>${jsonQ.ae_name}</strong>" Assessment?`;
		$scope.$root.prompt(_html, 'Clone operation has been canceled!').then(result => {
			if (result) {
				let newJsonQ = JSON.parse(JSON.stringify(jsonQ));
				newJsonQ.ae_heroes = '';
				newJsonQ.ae_id = 'null';
				vServices.callApi("/employee/getAssessmentSchedule", "POST", newJsonQ).then(as => {
					newJsonQ.ae_id = parseInt(as);
					$scope.data.push(newJsonQ);
					toastr.success(`"${jsonQ.ae_name}" assessment has been cloned successfully!`);
				});
			}
		});
	};
	$scope.deleteSchedule = (jsonQ, idx = null) => {
		// console.log(jsonQ);
		const _html = `Do you real want to delete the "<strong>${jsonQ.ae_name}</strong>" Assessment?`;
		$scope.$root.prompt(_html, 'Delete operation has been canceled!').then(result => {
			if (result) vServices.callApi("/employee/getAssessmentSchedule", "DELETE", { ae_id: jsonQ.ae_id }).then(isDeleted => {
				if (isDeleted) $scope.data.splice(idx, 1);
			});
		});
	};

	// $scope.sendMail = (jsonQ, idx = null) => {
	// 	console.log(jsonQ);
	// };

	// To send mail
	// Created By Syed Mohd Bilal Rais
	// 08 August 2021

	$scope.sendMail = (jsonQ, idx = null) => {

		// console.log(jsonQ);
		let modalInstance = $uibModal.open({
			animation: true,
			templateUrl: 'modelAssessmentScheduleMails.html',
			controller: 'modelAssessmentScheduleMailsCtrl',
			size: 'xl',//sm md,lg,xl
			controllerAs: "$scope",
			backdrop: "static",
			keyboard: false,
			resolve: {
				data: () => {
					return { idx, single: JSON.parse(JSON.stringify(jsonQ)) };
				}
			}
		});

		modalInstance.result.then(function (result) {
			// console.log('bhbj' + result.data);
			toastr.success('Mails Send successfully');
		}, () => {
			//$log.info('Modal dismissed at: ' + new Date());
		});
	};

	const init = () => {
		vServices.callApi("/employee/getAssessmentSchedule", "GET", {}).then(as => {
			$scope.data = as;
			$scope.$root.callDataTable("#assessmentSchedule", 400, (t) => {
			});
		});
	};
	init();

}])

	// // Created By Syed Mohd Bilal Rais
	.controller('modelAssessmentScheduleMailsCtrl', function ($scope, $uibModalInstance, data, vServices) {
		$scope.cancel = () => $uibModalInstance.dismiss(false);
		$scope.data = data;// single idx
		$scope.data.sendmail = [];
		$scope.mInfo = {
			head_icon: "fas fa-plus-circle",
			head_title: "Assessment Mails Status",
			btn_icon: "fas fa-save",
			btn_title: "Send Mail",
			today: new Date()
		};

		$scope.toggleAll = function () {
			var toggleStatus = !$scope.isAllSelected;
			angular.forEach($scope.data.sendmail, function (itm) { itm.check = toggleStatus; });
		}
		// console.log($scope.data.single.ae_id);
		vServices.callApi("/employee/getAssessmentMailDetails?id=" + $scope.data.single.ae_id, "GET", {}).then(data => {
			$scope.data.sendmail = JSON.parse(JSON.stringify(data));
			$scope.data.sendmail.heroes.forEach(h => {
				h.emp_id = h.emp_id;
				h.ae_id = $scope.data.single.ae_id;
				h.check = false;
				h.id = data.mails_data.filter(x => x.hero_id == h.emp_id);
				h.last_mail_sent = data.last_update.filter(x => x.hero_id == h.emp_id);
				if (h.id.length > 0) {
					data.mails_data.forEach(i => {
						if (h.emp_id == i.hero_id) {
							h.timestamp = moment(i.timestamp).format('DD-MMM-YYYY');
						}
					});
				} else {
					h.timestamp = 'Not Send';
				}
				data.last_update.forEach(i => {
					if (h.emp_id == i.hero_id) {
						h.mail2 = moment(i.mail2).format('DD-MMM-YYYY');
					}
				});
			});
			let filteretedArray = $scope.data.sendmail.heroes;
			$scope.data.sendmail = filteretedArray;
			console.log($scope.data.sendmail);
		});


		$scope.send = () => {
			data.sendmail = data.sendmail.filter(o => o.check);
			vServices.callApi("/employee/postAssessmentMailDetails", "POST", { myval: JSON.stringify(data) }).then(data => {
				$uibModalInstance.close({
					result: data
				});
			});
		}
	})

	.controller('modelAssessmentScheduleCtrl', function ($scope, $uibModalInstance, data, vServices) {
		$scope.cancel = () => $uibModalInstance.dismiss(false);
		$scope.data = data;// single idx
		$scope.data.questions = [];
		//$scope.data.sequence = [];

		$scope.mInfo = {
			head_icon: "fas fa-plus-circle",
			head_title: "Create Assessment's Schedule",
			btn_icon: "fas fa-save",
			btn_title: "Submit",
			today: new Date()
		};
		$scope.addQues = () => {
			$scope.data.quesList.filter(o => {
				if (o.aq_id === $scope.data.activeQue.aq_id) o.show = !o.show;
			});
			$scope.data.questions.push($scope.data.activeQue);
			$scope.data.activeQue = null;
		};

		const sysName = () => {
			$scope.data.single.users = $scope.data.single.ae_heroes && $scope.data.single.ae_heroes.indexOf(',') > -1 ? $scope.data.single.ae_heroes.split(',').filter(o => !!o.trim()).map(o => parseInt(o)) : [];
			const f = $scope.data.single.ae_from.length === 10 ? moment($scope.data.single.ae_from, 'DD-MM-YYYY').format('YYYYMM') : moment($scope.data.single.ae_from).format('YYYYMM');
			const t = $scope.data.single.ae_to.length === 10 ? moment($scope.data.single.ae_to, 'DD-MM-YYYY').format('YYYYMM') : moment($scope.data.single.ae_to).format('YYYYMM');
			$scope.data.single.ae_sys_name = `ASSESSMENT_${f}_${t}`;
		};

		$scope.$watch("data.single.ae_from", (n, o) => {
			if (n !== o) sysName();
		});

		$scope.$watch("data.single.ae_to", (n, o) => {
			if (n !== o) sysName();
		});

		$scope.removeQues = (q, idx) => {
			$scope.data.questions.splice(idx, 1);
			$scope.data.quesList.filter(o => {
				if (o.aq_id === q.aq_id) o.show = true;
			});
		};
		$scope.save = () => {

			let newarrsq = [];
			let newString = '';
			var newArr = [];
			if ($scope.data.opts == 'question') {
				$scope.data.questions.forEach((o, i) => {
					let itr = 'sequencesave' + i;
					let ids = document.getElementById(itr).value;
					newarrsq.push(ids);
				});
				$scope.data.questions.forEach((o, i) => {
					o.sequencesave = parseInt(newarrsq[i]);
				});


				$scope.data.questions.forEach((o, i) => {
					let sq = parseInt(o.sequencesave);
					var arr = { 'seq': sq, 'quesId': o.aq_id };
					newArr.push(arr);
				});
				newArr.sort(function (a, b) {
					return a.seq - b.seq;
				});
				newArr.forEach(i => {
					newString += ',' + i.quesId;
				});
			}
			if ($scope.data.single.users && $scope.data.single.users.length > 0) $scope.data.single.users.sort((a, b) => a - b);
			$scope.data.single.ae_questions = $scope.data.questions ? "," + $scope.data.questions.map(o => o.aq_id).toString() + "," : ',';
			if ($scope.data.opts == 'question') {
				$scope.data.single.ae_questions = newString;
			}
			$scope.data.single.ae_heroes = $scope.data.single.users ? "," + $scope.data.single.users.toString() + "," : $scope.data.ae_heroes;
			$uibModalInstance.close({
				idx: $scope.data.idx,
				data: $scope.data.single
			});
		};
		const init = () => {
			try {
				sysName();
				vServices.callApi("/employee/assessmentQuestionsDefault", "GET", {}).then(_question => {
					const selectedQues = $scope.data.single.ae_questions ? $scope.data.single.ae_questions.split(',').filter(o => o).map(o => parseInt(o)) : [];
					_question.map(o => {
						if (selectedQues.indexOf(parseInt(o.aq_id)) > -1) {
							o.show = false;
						}
						else {
							o.show = true;
						}
						return o;
					});

					// To create questions should be in sequence.
					let trimQuestions = $scope.data.single.ae_questions.replace(/(^,)|(,$)/g, "").split(",");
					trimQuestions.forEach(item => {
						let tempArr = _question.filter(o => o.aq_id == item);
						if (tempArr.length > 0) {
							$scope.data.questions.push(tempArr[0]);
						}
					});

					$scope.data.questions.forEach(item => {
						item.sequence = trimQuestions.indexOf('' + item.aq_id + '');
						item.sequence = item.sequence + 1;

					});
					$scope.data.quesList = _question;
				});
			} catch (e) {
				console.error(e);
			}
		};
		init();
	}).filter('question_show', () => items => items ? items.filter(o => o.show) : []);



