"use strict";

appCore.controller("AssessmentAdminCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter", '$uibModal',
	function ($state, $scope, $http, $timeout, vServices, filterFilter, $uibModal) {
		$scope.$root.page.title = "Create Assessment";
		$scope.createButton = {heading: "Add", text: "Submit", icon: "fa-save", today: new Date()};
		$scope.dummy = {
			dropdown: [{"value": "Select", "key": ""}, {"value": "", "key": ""}],
			dropdown_scale: [{"value": "Select", "key": ""}, {"value": "OUTSATANDING (5)", "key": "5"},
				{"value": "GOOD (4)", "key": "4"}, {"value": "AVERAGE (3)", "key": "3"},
				{"value": "SATISFACTORY (2)", "key": "2"}, {"value": "Low / Need Improvment (1)", "key": "1"}],
			multichoice: [{"value": "", "key": ""}, {"value": "", "key": ""}],
			tf: [{"value": "True", "key": "true"}, {"value": "False", "key": "false"}],
			num_range: {"min": 5, "max": 50, "step": 5}
		};
		$scope.data = {
			aqGroup: [],
			aqData: [],
			aqTypes: [
				{"working": true, "i": "caret-down", "key": "dropdown", "value": "Dropdown"},
				{"working": true, "i": "caret-down", "key": "dropdown_scale", "value": "Dropdown Scale"},
				{"working": false, "i": "tasks", "key": "multichoice", "value": "Multiple choice"},
				{"working": true, "i": "check-square", "key": "tf", "value": "True/False"},
				{"working": true, "i": "sort-numeric-down", "key": "number", "value": "Number"},
				{"working": true, "i": "sort-numeric-down", "key": "num_range", "value": "Number with Range"},
				{"working": true, "i": "text-width", "key": "shortanswer", "value": "Short answer 150 char"},
				{"working": true, "i": "text-width", "key": "longanswer", "value": "Long answer 300 char"},
				{"working": true, "i": "text-width", "key": "verylonganswer", "value": "Very long answer 500 char"},
				{"working": true, "i": "text-width", "key": "section", "value": "This is For Section"}
			]
		};
		$scope.getType = (k) => {
			const nK = $scope.data.aqTypes.filter(o => o.key === k);
			return nK && nK.length > 0 ? nK[nK.length - 1].value : '';
		};
		$scope.getGroup = (k) => {
			try {
				let nK = [];
				k = k ? k.toString() : "";
				if (k && k.indexOf(',') > -1) {
					let kArr = k.split(',');
					nK = $scope.data.aqGroup.filter(o => kArr.indexOf(o.ag_id + "") > -1 || kArr.indexOf(o.ag_id) > -1);
					// console.log('arr', kArr, nK);
				}
				else if (k && parseInt(k) > 0) {
					nK = $scope.data.aqGroup.filter(o => o.ag_id === parseInt(k));
					//console.log('11',nK);
				}
				return nK && nK.length > 0 ? nK.map(o => o.ag_name) : [];
			} catch (e) {
				console.error(e);
				return 'NA';
			}
		};
		
		$scope.cloneQuestion = (jsonQ, idx = null) => {
			let newJsonQ = JSON.parse(JSON.stringify(jsonQ));
			newJsonQ.aq_priority = $scope.data.aqData[$scope.data.aqData.length - 1].aq_priority + 1;
			newJsonQ.aq_ag_id = newJsonQ.aq_ag_id ? newJsonQ.aq_ag_id.toString() : '';
			newJsonQ.aq_status= newJsonQ.aq_status ? 'active' : 'inactive';
			if (!$scope.dummy[newJsonQ.aq_type]) {
				newJsonQ.aq_options = '';
			}
			else if (newJsonQ.aq_options) {
				newJsonQ.aq_options = JSON.stringify(newJsonQ.aq_options.map(o => ({
					"value": o.value,
					"key": o.key
				})));
			}
			else {
				newJsonQ.aq_options = '';
			}
			delete newJsonQ.aq_id;
			vServices.callApi("employee/getAssessmentQuestions", "POST", newJsonQ).then(res => {
				if (res) {
					toastr.success('Question has been cloned successfully!');
					newJsonQ.aq_id = res;
					$scope.data.aqData.push(newJsonQ);
				}
			});
		};
		
		$scope.deleteQuestion = (jsonQ, idx = null) => {
			vServices.callApi("employee/getAssessmentQuestions", "DELETE", {aq_id:jsonQ.aq_id}).then(isDeleted => {
				if (isDeleted) {
					$scope.data.aqData.splice(idx, 1);
					toastr.success('Question has been deleted successfully!');
				}
			});
		};
		
		$scope.addQuestion = (jsonQ, idx = null) => {
			console.log(idx);
			jsonQ = jsonQ ? jsonQ : {
				"aq_id": null, "aq_ag_id": [1, 2], "aq_name": "", "aq_type": "dropdown_scale",
				"aq_status": true, "aq_priority": 1, "aq_comment": true, "aq_manager_reply": false,
				"aq_options": JSON.parse(JSON.stringify($scope.dummy.dropdown_scale))
			};
			let modalInstance = $uibModal.open({
				animation: true,
				templateUrl: 'myModalContent.html',
				controller: 'ModalAssessmentAdminCtrl',
				size: window.outerWidth <= 1024 ? 'xl' : 'lg',//sm md,lg,xl
				controllerAs: "$scope",
				backdrop: "static",
				resolve: {
					data: () => {
						return {idx: idx, single: jsonQ, dummy: $scope.dummy, dataOriginal: $scope.data};
					}
				}
			});
			
			modalInstance.result.then(function (result) {
				console.log(result);
				result.data.aq_id = result.data.aq_id ? result.data.aq_id : result.aq_id;
				if (result.idx) {
					$scope.data.aqData[idx] = result.data;
				}
				else {
					$scope.data.aqData.push(result.data);
				}
			}, function () {
				//$log.info('Modal dismissed at: ' + new Date());
			});
		};
		
		const handler_aq_ag_id = (d) => {
			if (d.aq_ag_id && typeof d.aq_ag_id === 'string')
				d.aq_ag_id = d.aq_ag_id.replace('{', '').replace('}', '');
			if (d.aq_ag_id && typeof d.aq_ag_id === 'string' && d.aq_ag_id.indexOf(',') > -1)
				d.aq_ag_id = d.aq_ag_id.split(',').map(o => parseInt(o));
			else
				d.aq_ag_id = [parseInt(d.aq_ag_id)];
		};
		
		const init = () => {
			vServices.callApi("/employee/allAssessmentGroups", "GET", {}).then(function (aqGroup) {
				$scope.data.aqGroup = aqGroup;
				vServices.callApi("/employee/assessmentQuestionsAdmin", "GET", {}).then(function (aqData) {
					aqData.forEach((o, i) => {
						handler_aq_ag_id(aqData[i]);
						aqData[i].aq_options = aqData[i].aq_options ? JSON.parse(aqData[i].aq_options.replace(/\\\\"/g, '"')) : {};
						aqData[i].aq_status = aqData[i].aq_status === 'active';
						if (i === aqData.length - 1) {
							$scope.data.aqData = aqData;
							$scope.$root.callDataTable("#questionstbl");
							// vServices.callApi("allocation/listbyempid/" + $scope.$root.gUser.id, "GET", {}).then((res1) => createDiary(res1, aqData, () => {
							//     // vServices.callApi("project/manager/" + $scope.$root.gUser.id, "GET", {}).then((res2) => createDiary(res2));
							// }));
						}						
					});
				});
			});
			// vServices.callApi("mydiary/all_logtypes", "GET", {}).then((res) => {
			//     if (res) {
			//         $scope.logTypes = res;
			//         // $scope.logTypes.unshift({mydiarylogtypeid: "0", lt_name: "Select", lt_description: "", lt_status: "active"});
			//     }
			// });
		};
		init();
	}
])
	.controller('ModalAssessmentAdminCtrl', function ($scope, $uibModalInstance, data, vServices) {
		const getValue = (v) => JSON.parse(JSON.stringify(v));
		$scope.cancel = () => $uibModalInstance.dismiss('cancel');
		$scope.data = data;// single dummy dataOriginal
		console.log(JSON.stringify(data.single));
		$scope.$watch("data.single.aq_type", (n, o) => {
			if (n !== o) {
				console.log(n);
				$scope.data.single.aq_options = $scope.data.dummy[n];
			}			
		});
		
		$scope.save = () => {
			//$scope.data.dataOriginal.aqData.push($scope.data.single);
			
			if (!$scope.data.single.aq_name) {
				toastr.error('Please enter the Question');
				return false;
			}
			else {
				let data = {
					manager_only:$scope.data.single.manager_only?$scope.data.single.manager_only:false,
					rms_team_only:$scope.data.single.rms_team_only?$scope.data.single.rms_team_only:false,
					is_required:$scope.data.single.is_required?$scope.data.single.is_required:false,
					aq_id: getValue($scope.data.single.aq_id ? $scope.data.single.aq_id : ''),
					aq_ag_id: getValue($scope.data.single.aq_ag_id ? $scope.data.single.aq_ag_id : ''),
					aq_name: getValue($scope.data.single.aq_name ? $scope.data.single.aq_name : ''),
					aq_type: getValue($scope.data.single.aq_type ? $scope.data.single.aq_type : 'dropdown_scale'),
					aq_status: getValue($scope.data.single.aq_status ? 'active' : 'inactive'),
					aq_priority: getValue($scope.data.single.aq_priority ? $scope.data.single.aq_priority : 0),
					aq_comment: getValue($scope.data.single.aq_comment),
					aq_manager_reply: getValue($scope.data.single.aq_manager_reply)
				};
				if (!$scope.data.dummy[$scope.data.single.aq_type]) {
					data.aq_options = '';
				}
				else if ($scope.data.single.aq_options) {
					data.aq_options = JSON.stringify($scope.data.single.aq_options.map(o => ({
						"value": o.value,
						"key": o.key
					})));
				}
				else {
					data.aq_options = '';
				}
				console.log(JSON.stringify(data));
				vServices.callApi("/employee/getAssessmentQuestions", "POST", data).then(aqData => {
					//console.log(aqData);
					$uibModalInstance.close({idx: $scope.data.idx, isNew: !data.aq_id, data, aq_id: aqData});
				});
				
			}
//            $uibModalInstance.close({idx: $scope.data.idx, data: $scope.data.single});
		};
		
		const init = () => {
			console.log($scope.data);
			try {
				if (!$scope.data.idx && !$scope.data.single.aq_id && $scope.data.dataOriginal && $scope.data.dataOriginal.aqData && $scope.data.dataOriginal.aqData.length > 0) {
					$scope.data.single.aq_priority = $scope.data.dataOriginal.aqData[$scope.data.dataOriginal.aqData.length - 1].aq_priority + 1;
				}
			} catch (e) {
				console.error(e);
			}
		};
		init();
		
	});