'use strict';

angular.module('APP_MBO').controller('ObjectiveSetting', function($scope, $http, MBOutil, MBOrest, $filter, $state, $stateParams, $q, $mdDialog) {

	$scope.employeeid = $stateParams.employeeid;
	$scope.apsyear = $stateParams.apsyear;
	$scope.state = 0;
	$scope.user_data = {};
	$scope.isAppraisee = false;
	$scope.isAppraiser = false;
	$scope.aprraisee_data = {};
	$scope.isApsyear2016 = false;
	if($scope.apsyear=='2016'){
		$scope.isApsyear2016 = true;
	}
	$scope.kpi_category_name = [];
	$scope.global_basic_condition = '';
	$scope.ObjectiveSetting = [];
	$scope.sum = MBOutil.sum;
	$scope.dateNow = new Date().toISOString().slice(0,10);
	$scope.TapsstateList = MBOutil.TapsstateList;
	$scope.alertSaveComplete = MBOutil.alertSaveComplete;
	$scope.loading = MBOutil.loading;
	

	if( MBOutil.TapsstateList.length == 0 ){
		MBOrest.TapsstateList.query({ apsid: 'MBO' })
			.$promise.then(function(data) {
				MBOutil.TapsstateList = data.TapsstateList;
				$scope.TapsstateList = MBOutil.TapsstateList;
			});
	}

	$scope.addRow = function(category, bu, obj, weight, commitment, isfix){
		$scope.ObjectiveSetting.push(
			{
				'kpi_idx': $scope.getKpi_idx(category),
				'bu': bu || '',
				'obj': obj || '',
				'isfix': isfix || 0,
				'weight': weight || 0,
				'commitment': commitment || '',
				'target': '',
				'action': '',
				'kpi_category': category,
				'isChecked': false,
				'isNew': true,
				'isDelete': false
			}
		);
	};

	$scope.delRow = function( kpi_category ){
		MBOutil.deleteCheckedlistWithCat($scope.ObjectiveSetting, kpi_category);
	};

	MBOrest.ObjectiveSetting.query( { apsyear: $scope.apsyear, employeeid: $scope.employeeid } )
		.$promise.then(function(data) {
			if(data.kpi_category_name[0].kpiweight){
				$scope.kpi_category_name = data.kpi_category_name;
				$scope.ObjectiveSetting = data.ObjectiveSetting;
				$scope.aprraisee_data = data.aprraisee_data;
				$scope.aprraisee_data = data.aprraisee_data;
				$scope.user_data = data.userdata;
				$scope.state = data.state;
				if( $scope.user_data.employeeid == data.aprraisee_data.employeeid ){
					$scope.isAppraisee = true;
				}else{
					$scope.isAppraiser = true;
				}

				if($scope.isApsyear2016){
					$scope.fixBu1 = [];
					$scope.fixBu2 = [];
					$scope.fixBu3 = ['','','',''];
					$scope.fixBu4 = [];
					$scope.fixObj1 = [];
					$scope.fixObj2 = ['CK WAY', 'Compliance', 'Developing People', 'V-up / CKPS'];
					$scope.fixObj3 = [];
					$scope.fixWeight1 = [];
					$scope.fixWeight2 = [5,5,5,5];
					$scope.fixWeight3 = [];
					$scope.fixCommitment1 = [];
					$scope.fixCommitment2 = [];
					$scope.fixCommitment3 = [];
				}else{
					$scope.fixBu1 = [];
					$scope.fixBu2 = [];
					$scope.fixBu3 = ['Fixed Individual','Fixed Individual','Common HR'];
					$scope.fixObj1 = ['Profit','Quality','Function KPI'];
					$scope.fixObj2 = [];
					$scope.fixObj3 = ['Turnover Rate & Employee SatisfactionScore','Best','CK WAY & Compliance'];
					$scope.fixWeight1 = [0,0,0];
					if(data.aprraisee_data.jobgroup=="015"){
						$scope.fixWeight1 = [20,10,0];
					}else if(data.aprraisee_data.jobgroup=="016"){
						$scope.fixWeight1 = [30,10,0];
					}else if(data.aprraisee_data.jobgroup=="017"){
						$scope.fixWeight1 = [30,10,0];
					}else if(data.aprraisee_data.jobgroup=="020"){
						$scope.fixWeight1 = [40,10,0];
					}
					$scope.fixWeight2 = [];
					$scope.fixWeight3 = [5,5,10];
					$scope.fixCommitment1 = [];
					$scope.fixCommitment2 = [];
					$scope.fixCommitment3 = ['• TO ≤ 7.4% (reduce 1% from FY16 8.4%)\n• ESS ≥ 75%','• Total project paticipate : 70 PJ/Y\n\• Project pass thru final round : ≥ 50% of commit # (≥ 35 PJ)','• CK WAY survey score above 3.0 (exclusive VMV portion)\n• NO Significant compliance issue occurrence'];
				}

				$scope.checkFixData($scope.fixBu1, $scope.fixObj1, $scope.fixWeight1,$scope.fixCommitment1, 0);
				$scope.checkFixData($scope.fixBu2, $scope.fixObj2, $scope.fixWeight2,$scope.fixCommitment2, 1);
				$scope.checkFixData($scope.fixBu3, $scope.fixObj3, $scope.fixWeight3,$scope.fixCommitment3, 2);
			/*	if(!$scope.isApsyear2016){
					$scope.checkFixData($scope.fixBu4, $scope.fixObj4, $scope.fixWeight4, 3);
				}	*/
			}else{
				alert('Invalid setup data');
				$state.go('mbo.profile', { apsyear: $scope.apsyear, employeeid: $scope.employeeid });
			}
		}).catch(function(response){
			
		});
	
	MBOrest.GlobalCondition.query( { apsyear: $scope.apsyear, employeeid: $scope.employeeid } )
		.$promise.then(function(data) {
			$scope.global_basic_condition = data.global_basic_condition;
		});

	$scope.$on('$stateChangeStart', function(event) {
		if($scope.myForm.$dirty){
			var answer = confirm("Data has not been save. Are you sure to leave this tab?")
			if(!answer) {
				event.preventDefault();
			}
		}
	});
	
	$scope.checkKpiSetting = function(){
		for(let i in $scope.kpi_category_name){
			let min = $scope.kpi_category_name[i].itemmin;
			let max = $scope.kpi_category_name[i].itemmax;

			if( $scope.sumWeight(i) != $scope.kpi_category_name[i].kpiweight ){
				alert(
						'The Weight of '+$scope.kpi_category_name[i].edesc+' not equals '+$scope.kpi_category_name[i].kpiweight+'% \n'+
						'Now you have '+$scope.sumWeight(i)+'%'
					);
				return false;
			}

			if( $scope.getCat(i).length > max || $scope.getCat(i).length < min ){
				alert(
						'The Item of '+$scope.kpi_category_name[i].edesc+' not in range of '+min+' - '+max+' items \n'+
						'Now you have '+$scope.getCat(i).length+' items'
					);
				return false;			
			}

		}
		return true;
	}

	$scope.save = function(isAlert){
		/*$scope.loading();*/
		let saveObjSet = $q.defer();
		let saveGloCon = $q.defer();

		$q.all(
			[saveObjSet.promise, saveGloCon.promise]
		).then(function() {
			if(isAlert != false){
				/*$scope.alertSaveComplete();*/
			}
			if($scope.myForm != undefined){
				$scope.myForm.$setPristine();
			}
			return true;
		});

		MBOrest.ObjectiveSetting.save( { apsyear: $scope.apsyear, employeeid: $scope.employeeid }, $scope.ObjectiveSetting )
			.$promise.then(function(data) {
				saveObjSet.resolve(data);
				alert("Save Complete");
			});
		
		if( !$scope.myForm.global_basic_condition.$pristine ){
			MBOrest.GlobalCondition.save( { apsyear: $scope.apsyear, employeeid: $scope.employeeid }, $scope.global_basic_condition )
				.$promise.then(function(data) {
					saveGloCon.resolve(data);
				});
		}else{
			saveGloCon.resolve(true);
		}	

	};

	$scope.getFloat = function(value){
		return parseFloat(value)
	}

	$scope.sum2Weight = function( cat_no, cat_no2 ){
		return (parseFloat($scope.sumWeight(cat_no)) + parseFloat($scope.sumWeight(cat_no2))).toFixed(2)
	}

	$scope.sumWeight = function( cat_no ){
		if( $scope.kpi_category_name && $scope.kpi_category_name.length > 0 && $scope.kpi_category_name[ cat_no ]!=undefined){
			return $scope.sum( $scope.getCat(cat_no), 'weight' )
		}
	}

	$scope.getCat = function( cat_no ){
		if( $scope.kpi_category_name && $scope.kpi_category_name.length > 0 && $scope.kpi_category_name[ cat_no ]!=undefined){
			return $filter('filter')($scope.ObjectiveSetting, {kpi_category:$scope.kpi_category_name[ cat_no ].kcatid, isDelete:false});
		}
	}

	$scope.checkFixData = function(fixBu, fixObj, fixWeight,fixCommitment, group){
		let kcatid = $scope.kpi_category_name[group].kcatid;
		let common = $filter('filter')($scope.ObjectiveSetting, {kpi_category:kcatid});

		if(common.length == 0){
			for(let i in fixObj){
				$scope.addRow(kcatid, fixBu[i], fixObj[i], fixWeight[i],fixCommitment[i], 1);
			}
		}else{
			let tmpForAdd = fixObj;
			for(let i in common){
				let minion = common[i];
				if( fixObj.indexOf(minion.obj) == -1 ){
					$scope.delRow(kcatid, minion.kpi_idx);
				}else{
					tmpForAdd.splice( fixObj.indexOf(minion.obj), 1 );
				}
			}
			if(tmpForAdd.length>0){
				for(let i in tmpForAdd){
					$scope.addRow(kcatid, fixBu[i], fixObj[i], fixWeight[i],fixCommitment[i], 1);
				}
			}
		}
		
		for(let i in $scope.ObjectiveSetting){//sort idx
			let minion = $scope.ObjectiveSetting[i];
			for(let x in fixObj){
				if(minion.obj == fixObj[x]){
					minion.kpi_idx = parseInt(kcatid+(parseInt(x)+1));
				}
			}
		}
		$scope.ObjectiveSetting = $filter('orderBy')($scope.ObjectiveSetting, 'kpi_idx');
		return common;
	}

	$scope.getKpi_idx = function(category){
		let arr = $filter('filter')($scope.ObjectiveSetting, {kpi_category:category});
		let sort = $filter('orderBy')(arr, 'kpi_idx');
		if(sort == ''){
			return parseInt(category+''+1);
		}
		return parseInt(sort[ sort.length-1 ].kpi_idx)+1;
	}

	$scope.Next = function(){
		if($scope.checkKpiSetting() && confirm("Are you sure to confirm data?") == true ){
			/*$scope.loading();*/
			let isAlert = false;
			let Q1 = $q.defer();
			let Q2 = $q.defer();

			$q.all(
				[ Q1.promise, Q2.promise ]
			).then(function() {
			//	$scope.myForm.$setPristine();
				$state.reload();
			});

			Q1.resolve( $scope.save(isAlert) );

			MBOrest.ObjectiveSetting.transfer( { apsyear: $scope.apsyear, employeeid: $scope.employeeid } )
				.$promise.then(function(data) {
					/*$scope.alertSaveComplete(data.Message);*/
					Q2.resolve(data);
				});
		}
    };

});