var angular = require('angular');
require('../modules');
require('jsUtil');
require('../services/CurrentTaskService');
require('../services/TaskRemoteService');
require('../services/delaySaveTasks');

'use strict';

var module = angular.module('task');

module.controller('TaskDetailCtrl', function(
	$scope, $ionicActionSheet, $state,
	TaskRemoteService, CommonService, $stateParams,
	userList, CurrentTaskService, CoreAppConfig, delaySaveTasks, AudioPlayerService, $toast) {

	$scope.fromState = CommonService.getParentState();

	/**
	 * 从缓存中获取当前任务。
	 */
	$scope.init = function() {
		CurrentTaskService.getCurrentTask().then(function(task) {
			$scope.task = task;
			if (!jsUtil.isEmpty($scope.task.handlePersons)) {
				getUserInfoByIds();
			}
			if ($scope.task.status !== '3') {
				taskFinishOrNot();
			}
		});
	};

	function getUserInfoByIds() {
		var userIds = $scope.task.handlePersons.split(',').concat($scope.task.sendPerson);
		userList.get(userIds).then(function(users) {
			$scope.sendPersonName = users.pop().userName;
			$scope.handlePersonsNames = _.map(users, function(user) {
				return user ? (user.deptName + '/' + user.userName) : '';
			}).join('，');
		});
	}

	function taskFinishOrNot() {
		TaskRemoteService.taskFinishOrNot($scope.task.id).then(function(result) {
			$scope.taskFinish = result.finish;
		});
	}

	$scope.goBack = function() {
		$state.go($scope.fromState.name, $scope.fromState.params);
	};
	/**
	 * 解析日期格式。
	 * @param  {String} dateStr 日期字符串
	 */
	$scope.parseDateStr = function(dateStr) {
		return CommonService.smartInfoDateParser(dateStr);
	};

	$scope.parseImageSrc = function(src) {
		return CoreAppConfig.serverUrl + src;
	};

	/**
	 * 解析任务类型。
	 * @param  {String} typeId 任务类型id
	 */
	$scope.parseType = function(typeId) {
		return TaskRemoteService.getTypeById(typeId);
	};
	/**
	 * 完成任务。
	 */
	$scope.completeTask = function() {
		$ionicActionSheet.show({
			buttons: [{
				text: '完成'
			}],
			cancelText: '取消',
			cancel: function() {
				return true;
			},
			buttonClicked: function() {
				TaskRemoteService.completeTask($scope.task.id).then(function(result) {
					if (result.success) {
						$toast.showShortCenter('祝贺你，任务完成！已完成的任务可以到任务列表查看。');
					} else {
						$toast.showShortCenter('任务无法完成，请检查网络连接。');
					}
					$state.go('mission.task');
				}, function() {
					$toast.showShortCenter('任务无法完成，请检查网络连接。');
				});
				return true;
			}
		});
	};
	/**
	 * 删除任务。
	 */
	$scope.deleteTask = function() {
		$ionicActionSheet.show({
			destructiveText: '删除',
			cancelText: '取消',
			cancel: function() {
				return true;
			},
			destructiveButtonClicked: function() {
				if ($scope.task.status === '3') {
					delaySaveTasks.remove($scope.task).then(function() {
						$toast.showShortCenter('友情提示，草稿已删除。');
						$state.go('mission.task');
					}, function() {
						$toast.showShortCenter('删除草稿失败，请检查网络连接。');
					});
				} else {
					TaskRemoteService.deleteDraftTask($scope.task.id).then(function(result) {
						if (result.success) {
							$toast.showShortCenter('友情提示，草稿已删除。');
							$state.go('mission.task');
						} else {
							$toast.showShortCenter('删除草稿失败，请检查网络连接。');
						}
					}, function() {
						$toast.showShortCenter('删除草稿失败，请检查网络连接。');
					});
				}

				return true;
			}
		});
	};
	/**
	 * 编辑任务。
	 */
	$scope.editTask = function() {
		$state.current.params = $state.params;
		CommonService.setCookie('mission.taskEdit.parent', $state.current);
		$state.get('mission.taskEdit').parent = $state.current;
		$state.go('mission.taskEdit', {
			taskId: $scope.task.id
		});
	};

	$scope.toDetail = function() {
		if($scope.task.status === '0' || $scope.task.status === '3') {
			$scope.editTask();
		} else {
			$scope.toTaskDiscuss();
		}
	};

	$scope.toTaskDiscuss = function() {
		$state.go('mission.taskDiscuss', {
			taskId: $scope.task.id
		});
	};

	$scope.isBlankContent = function(content) {
		return !jsUtil.isEmpty(content);
	};

	/**
	 * 监听语音播放完成事件，播放下一个语音。
	 * @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.init();
});