var angular = require('angular');
require('../modules');
require('jsUtil');
require('../services/TaskRemoteService');
require('../services/TaskRepository');
require('../services/delaySaveTasks');
'use strict';

var module = angular.module('task');
/**
 * 创建/编辑任务控制器。
 */
module.controller('TaskCreateCtrl', function($scope, $state, $ionicModal,
	TaskRemoteService, TaskRepository, $ionicActionSheet, CommonService, $stateParams,
	DiscussService, fileService, $ionicScrollDelegate,
	$window, $ionicPopup, $rootScope, $timeout, delaySaveTasks, AudioPlayerService, $toast) {

	$scope.loading = false;
	$scope.titleEditing = false;
	$scope.fromState = CommonService.getParentState();
	$scope.delegate = $ionicScrollDelegate.$getByHandle('taskFormScroll');

	$scope.actionName = '发送';
	if($state.params.userId) {
		$scope.actionName = '发送';
	} else {
		$scope.actionName = '选择办理人';
	}

	function keyboardShowHandler() {
		$scope.keyboardshow = true;
		$scope.$apply();
		// $scope.delegate.scrollTo(0, window.screen.availHeight - e.keyboardHeight - document.querySelector('.bar.bar-header').clientHeight);
	}

	function keyboardHideHandler() {
		$scope.keyboardshow = false;
		$scope.titleEditing = false;
		$scope.$apply();
	}

	window.addEventListener('native.keyboardshow', keyboardShowHandler);
	window.addEventListener('native.keyboardhide', keyboardHideHandler);

	$scope.titleInputFocus = function() {
		if ($window.device && ($window.device.platform === 'Android' || $window.device.platform === 'iOS')) {
			$scope.titleEditing = true;
		}
	};

	$scope.titleInputBlur = function() {
		$scope.titleEditing = false;
	};

	$scope.showKeyboard = function() {
		if ($scope.keyboardshow) {
			document.querySelector('.footerinput input').blur();
		} else {
			document.querySelector('.footerinput input').focus();
		}
	};

	$scope.initTask = function() {
		if ($stateParams.taskId) {
			$scope.loading = true;
			$scope.loadTask();
		} else {
			$scope.task = {
				type: '日常事务'
			};
		}
	};

	$scope.loadTask = function() {
		TaskRepository.getTaskById($stateParams.taskId).then(function(task) {
			$scope.task = task;
			$scope.loading = false;
		});
	};

	$scope.items = [{
		value: '日常事务',
		label: '日常事务'
	}, {
		value: '局发文',
		label: '局发文'
	}, {
		value: '处发文',
		label: '处发文'
	}, {
		value: '局收文',
		label: '局收文'
	}, {
		value: '处收文',
		label: '处收文'
	}, {
		value: '出差',
		label: '出差'
	}, {
		value: '信息发布',
		label: '信息发布'
	}, {
		value: '文件归档',
		label: '文件归档'
	}];
	/**
	 * 加载任务办理人选择modal。
	 */
	$scope.initModal = function() {
		$ionicModal.fromTemplateUrl('views/linker/modal/chooselinker.modal.tpl.html', function(modal) {
			$scope.searchModal = modal;
		}, {
			scope: $scope,
			animation: 'slide-in-up'
		});
	};
	/**
	 * 返回。
	 */
	$scope.goBack = function() {
		if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard.isVisible) {
			window.cordova.plugins.Keyboard.close();
		}
		if ($scope.taskForm.$dirty) {
			$scope.openTips();
		} else {
			$state.go($scope.fromState.name, $scope.fromState.params);
		}
	};
	/**
	 * 当任务被修改后操作人想要返回，显示是否保存草稿的提示。
	 */
	$scope.openTips = function() {
		$ionicActionSheet.show({
			buttons: [{
				text: '保存草稿'
			}, {
				text: '不保存'
			}],
			cancelText: '取消',
			cancel: function() {
				return true;
			},
			buttonClicked: function(index) {
				if (index === 1) {
					$scope.taskForm.$dirty = false;
					$scope.goBack();
				} else if (index === 0) {
					$scope.saveDraft();
				}
				return true;
			}
		});
	};
	/**
	 * 保存草稿任务。
	 */
	$scope.saveDraft = function() {
		if ($scope.validateTask($scope.task)) {
			$scope.save(0);
		}
	};
	/**
	 * 保存任务.
	 * @param  {Number} ifSend
	 */
	$scope.save = function(ifSend) {
		var cacheTaskId = $scope.task.id ? $scope.task.id : delaySaveTasks.generateId();
		$rootScope.$broadcast('task.saving', $scope.task, cacheTaskId);

		var cloneTask = jsUtil.clone($scope.task);
		delete cloneTask.id;
		delete cloneTask.latestMessage;
		TaskRemoteService.saveTask(cloneTask, ifSend).then(function(task) {
			$scope.task = task;
			$rootScope.$broadcast('task.saved', $scope.task, cacheTaskId);
		}, function() {
			$rootScope.$broadcast('task.savefail', $scope.task, cacheTaskId);
		});
		$state.go('mission.task');
	};
	/**
	 * 发送任务。
	 */
	$scope.send = function() {
		if (jsUtil.isEmpty($scope.task.handlePersons)) {
			$toast.showLongCenter('友情提示，请选择任务办理人！');
		} else {
			$scope.searchModal.hide();
			$scope.save(1);
		}
	};
	/**
	 * 发送任务，如果当前任务是先指定联系人，给该联系人发送的话，则直接发送；否则，进行任务验证，通过则弹出选择任务接收人页面。
	 */
	$scope.sendTask = function() {

		if ($state.current.name === 'mission.tasktouser') {
			if ($scope.validateTask($scope.task, 1)) {
				$scope.task.handlePersons = $state.params ? $state.params.userId : '';
				$scope.save(1);
			}
		} else if ($scope.validateTask($scope.task, 1)) {
			$scope.searchModal.show();
			$timeout(function() {
				$scope.showModal = true;
			});
		}
	};
	/**
	 * 对任务的数据进行验证，任务类型和名称不能为空，任务发送人由后端进行验证，在保存方法中的错误消息内可以获知。
	 * @param  {Task} task 需要保存的任务
	 */
	$scope.validateTask = function(task, ifSend) {
		if (!ifSend) {
			return true;
		} else if (jsUtil.isEmpty(task.type)) {
			$toast.showLongCenter('友情提示，任务类型不能为空！');
			return false;
		} else if (jsUtil.isEmpty(task.title)) {
			$toast.showLongCenter('友情提示，任务标题不能为空！');
			return false;
		} else {
			return true;
		}
	};
	/**
	 * 关闭任务办理人搜索弹层。
	 */
	$scope.closeSearchModal = function() {
		$scope.searchModal.hide();
	};
	/**
	 * scope作用域销毁时将搜索弹层移除。
	 */
	$scope.$on('$destroy', function() {
		if ($scope.searchModal) {
			$scope.searchModal.remove();
		}
		window.removeEventListener('native.keyboardshow');
		window.removeEventListener('native.keyboardhide');
	});

	$scope.onCheckedUsersChange = function(users) {
		if ($scope.task) {
			$scope.task.handlePersons = jsUtil.map(users, function(user) {
				return user.userId;
			}).join(',');
			$scope.taskForm.$dirty = true;
		}
	};

	$scope.chooseLinkerOptions = {
		onCheckedUsersChange: $scope.onCheckedUsersChange
	};

	$scope.parseImageSrc = function(src) {
		return DiscussService.parseImageSrc(src);
	};
	/**
	 * 图片上传成功。
	 */
	var uploadImageSuccess = function(r) {
		var file = JSON.parse(r.response)[0];
		$scope.task.content = $scope.task.content ? $scope.task.content : '';
		$scope.task.content += '<img class="image-view" image-id="' + file.id + '" size="270x270">';
		$scope.taskForm.$dirty = true;
		$scope.loading = false;
		$timeout(function() {
			$scope.delegate.scrollBottom();
		});
	};
	/**
	 * 图片/语音上传失败。
	 */
	var uploadFileFail = function() {
		$scope.loading = false;
		$toast.showLongCenter('上传失败，请检查网络连接。');
	};
	/**
	 * 获取图片成功，上传。
	 * @param  {String} fileURL 图片文件的url
	 */
	$scope.onGetPictureSuccess = function(fileURL) {
		$scope.loading = true;
		var options = {
			mimeType: 'image/jpeg',
			fileName: fileURL && fileURL.substr(fileURL.lastIndexOf('/') + 1) + '.jpg',
			params: {
				category: 'mission-images'
			}
		};
		fileService.upload(fileURL, options).then(uploadImageSuccess, uploadFileFail);
	};
	/**
	 * 录音成功，上传。
	 * @param  {String} audioURL 录音的url
	 */
	$scope.onCaptureAudioSuccess = function(media) {
		$scope.loading = true;
		DiscussService.uploadAudio(media).then(uploadAudioSuccess, uploadFileFail);
	};

	/**
	 * 录音失败。
	 */
	$scope.onCaptureAudioFail = function() {
		$toast.showShortCenter('语音录取失败。');
	};
	/**
	 * 上传语音成功。
	 */
	var uploadAudioSuccess = function(playAudioHtml) {
		$scope.loading = false;
		$scope.task.content = $scope.task.content ? $scope.task.content : '';
		$scope.task.content += playAudioHtml;
		$scope.taskForm.$dirty = true;
	};
	/**
	 * 发送文字内容
	 * @param  {String} text
	 */
	$scope.onSendText = function(text) {
		text = CommonService.escapeHtml(text);
		$scope.task.content = $scope.task.content ? $scope.task.content : '';
		$scope.task.content += '<p>' + text + '</p>';
		$scope.taskForm.$dirty = true;
		$scope.$digest();
	};

	$scope.onLongPress = function() {
		$ionicPopup.confirm({
			title: '删除',
			content: '确定要删除任务内容吗？',
			okText: '确定',
			cancelText: '取消'
		}).then(function(res) {
			if (res) {
				$scope.task.content = '';
				$scope.taskForm.$dirty = true;
			}
		});
	};
	/**
	 * 监听语音播放完成事件，播放下一个语音。
	 * @param  {Event} event   事件对象
	 * @param  {String} audioId 语音id
	 */
	$scope.$on('audio.release', function(event, audioId) {
		var node = document.querySelector('[audio-player="' + audioId + '"]');
		AudioPlayerService.playNext(node, function(node) {
			return node.nextElementSibling;
		});
	});
	/**
	 * 底部输入框、录音、上传图片组件的配置。
	 */
	$scope.footerInputOptions = {
		onGetPictureSuccess: $scope.onGetPictureSuccess,
		onCaptureAudioSuccess: $scope.onCaptureAudioSuccess,
		onCaptureAudioFail: $scope.onCaptureAudioFail,
		onSendText: $scope.onSendText,
		confirmText: '确定'
	};

	$scope.initTask();
	$scope.initModal();
});