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

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

module.controller('TaskListCtrl', function($scope, $timeout, $state, TaskRemoteService,
	CommonService, taskMessages, CurrentTaskService, $ionicScrollDelegate, $rootScope) {
	$scope.taskMessages = taskMessages;
	$scope.barTheme = $scope.tabTheme = 'dark';
	$scope.loading = false;
	$scope.delegate = $ionicScrollDelegate.$getByHandle('messageScroll');

	$scope.goBack = function() {
		$state.go('core-notice');
	};

	$rootScope.totalNoticeNum = function() {
		var result = 0;
		jsUtil.each($scope.taskMessages.items, function(item) {
			result += item.noticeNum;
		});
		return result;
	};

	$timeout(function() {
		$scope.delegate.scrollTo(taskMessages.scrollPosition.left, taskMessages.scrollPosition.top);
	});

	$scope.clearSearch = function() {
		$scope.search = '';
	};
	/**
	 * 生成用户头像链接。
	 * @param  {String} userId 用户id
	 */
	$scope.parseImageSrc = function(userId) {
		return CommonService.getPersonImageUrl(userId, 55, 55);
	};
	/**
	 * 查看消息详情。
	 * @param  {String} taskId 任务id
	 */
	$scope.toMessageDetail = function(task) {
		if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard.isVisible) {
			window.cordova.plugins.Keyboard.close();
		}
		CurrentTaskService.changeCurrentTask(task).then(function() {
			if (task.status === '0' || task.status === '3') {
				CommonService.setCookie('mission.taskDetail.parent', $state.current);
				$state.get('mission.taskDetail').parent = $state.current;
				$state.go('mission.taskDetail', {
					taskId: task.id
				});
			} else {
				$state.go('mission.taskDiscuss', {
					taskId: task.id
				});
			}
		});

	};
	/**
	 * 创建任务。
	 */
	$scope.createTask = function() {
		CommonService.setCookie('mission.taskCreate.parent', $state.current);
		$state.get('mission.taskCreate').parent = $state.current;
		$state.go('mission.taskCreate');
	};
	/**
	 * 刷新页面。
	 */
	$scope.onRefresh = function() {
		$scope.loading = true;
		$scope.taskMessages.refresh().
		finally(function() {
			$scope.loading = false;
			$rootScope.$broadcast('messages.refreshComplete');
			$scope.$broadcast('scroll.refreshComplete');
		});
	};
	/**
	 * 解析任务类型。
	 * @param  {String} typeId 任务类型id
	 */
	$scope.parseType = function(typeId) {
		return TaskRemoteService.getTypeById(typeId);
	};
	/**
	 * 解析日期格式。
	 * @param  {String} dateStr 日期字符串
	 */
	$scope.parseDateStr = function(dateStr) {
		return CommonService.smartListDateParser(dateStr);
	};
	/**
	 * 加载更多。
	 */
	$scope.loadMore = function() {
		$scope.taskMessages.loadMore($scope.taskMessages.number).
		finally(function() {
			$scope.$broadcast('scroll.infiniteScrollComplete');
			$scope.$broadcast('scroll.resize');
		});
	};
	/**
	 * 获取任务的子标题。
	 * 如果当前任务为草稿任务，即task.status = '0'，则显示 草稿 ；
	 * 否则，如果最新消息为系统生成的消息，则显示title；
	 * 否则，如果最新消息为任务接收人或者发送人发送来的消息，则显示消息内容，若消息内容为语音或者图片，显示'[语音]'或者'[图片]'。
	 * @param  {Object} task 任务
	 */
	$scope.getMessageSubTitle = function(task) {
		if (task.status === '0') {
			return '草稿';
		} else {
			var latestMessage = task.latestMessage ? task.latestMessage :
				task.discussions ? task.discussions[task.discussions.length - 1] : {};
			if (!latestMessage) {
				return '';
			} else if (latestMessage.type === '0') {
				return latestMessage.title;
			} else {
				if (latestMessage.content && latestMessage.content.indexOf && latestMessage.content.indexOf('audio-player') !== -1) {
					return '[语音]';
				} else if (latestMessage.content && latestMessage.content.indexOf && latestMessage.content.indexOf('image-view') !== -1) {
					return '[图片]';
				} else {
					return latestMessage.content;
				}
			}
		}
	};

	/**
	 * 搜索。
	 * @param  {String} searchText 搜索词
	 */
	$scope.$watch('search.text', function(searchText) {
		if (!searchText) {
			$scope.searchItems = [];
		} else {
			$scope.searchItems = jsUtil.filter($scope.taskMessages.items, function(task) {
				return (task.title && task.title.indexOf(searchText) !== -1) || (task.content && task.content.indexOf && task.content.indexOf(searchText) !== -1);
			});
			$ionicScrollDelegate.$getByHandle('searchTaskScroll').scrollTop();
		}
	});

	$scope.$on('$destroy', function() {
		var position = $scope.delegate.getScrollPosition();
		taskMessages.scrollPosition = position;
	});

});