var angular = require('angular');
require('../modules');
require('../../../commons/directives/sinoListTabs');
require('../services/ToBeReadService');
require('../services/TobereadConfig');
require('../../linker/services/LinkerService');

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

module.controller('ToBeReadGroupCtrl',
      function($scope, $state, ToBeReadService, TobereadConfig,
        LinkerService, $ionicPopup, $toast, $ionicLoading) {
      $scope.title = '待阅事宜';
      $scope.todos = ToBeReadService.todos;
      $scope.relatedList = ToBeReadService.relatedList;

      $scope.allYueBi = function() {
        $ionicPopup.confirm({
          title: '全部阅毕',
          content: '您确定要全部阅毕【待阅】吗？',
          okText: '确定',
          cancelText: '取消'
        }).then(function(res) {
          if (res) {
            $ionicLoading.show({
              template: '正在处理中，请等待...'
            });
            ToBeReadService.allYueBi(LinkerService.currentUserId).then(function(status) {
              if(status) {
                ToBeReadService.initArrayCache();
                $scope.todos.items = [];
                $toast.showShortCenter('全部阅毕成功！');
              }
            }, function() {
              $toast.showShortCenter('全部阅毕失败！');
            }).finally(function() {
              $ionicLoading.hide();
            });
          }
        });
      };

      $scope.toDetail = function(item) {
        if(item.relationId === item.typeId) {
          if(item.viewUrl) {
            item.relationId = item.viewUrl.match(/evectionId=([^&]+)/)[1];
          }
        }
        var config = TobereadConfig.get(item) || {},
          stateParams = {
            id: item.sendId,
            seeFlag: item.seeFlag,
            relationId: item.relationId,
            relationTable: item.relationTable,
            flowType: item.typeId
          };
        ToBeReadService.setCurDaiyue(item);
        $state.go(config.tobereadUrl || 'tobereadDetail', stateParams);
      };
});
