var angular = require('angular');
var _ = require('jsUtil');
require('../modules');
require('../../flow/services/ToBeReadremoteService');
require('../../../commons/services/CommonService');
require('../services/ToBeReadService');
require('../services/TobereadConfig');
require('../../linker/services/LinkerService');
require('../../../commons/services/AppConfig');

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

module.controller('ToBeReadDetailCtrl', ["$state", "CommonService", "$stateParams",
  "ToBeReadRemoteService", "$toast", "$q", "ToBeReadService",
  "$ionicPopup", "TobereadConfig", "$sinoGoBackDelegate", "$scope",
  "$ionicLoading", "LinkerService", "CoreAppConfig", function(
  $state, CommonService, $stateParams,
  ToBeReadRemoteService, $toast, $q,
  ToBeReadService, $ionicPopup, TobereadConfig,
  $sinoGoBackDelegate, $scope, $ionicLoading, LinkerService, CoreAppConfig) {
  var vm = this,
    sendId = $stateParams.id;
  vm.isUserNotion = false;

  activate();

  function activate() {
    initViewTime();
    ToBeReadService.getCurDaiyue(sendId)
    .then(function(daiyue) {
      vm.daiyue = daiyue;
      if(_.isEmpty(daiyue.userNotion)) {
        vm.daiyue.userNotion = '无';
        vm.isUserNotion = true;
      }
      if(_.isEmpty(daiyue.zfNotion)) {
        vm.isZfNotion = false;
      } else {
        vm.isZfNotion = true;
        var zfNotion = vm.daiyue.zfNotion;
        if(zfNotion.indexOf('<br>') >=0) {
          vm.daiyue.zfNotion = zfNotion.substring(0, zfNotion.length-4);
          if(!vm.daiyue.zfNotion) {
            vm.daiyue.zfNotion = '无';
          }
        }
      }
      var moduleConfig = TobereadConfig.get(daiyue) || {};
      vm.formTplHtml = moduleConfig.tobereadFormTplHtml;
      vm.hasRead = daiyue.seeFlag == '1';
      vm.title = daiyue.seeFlag == '1'? '阅毕信息' :'待阅信息';
      vm.showZfButton = TobereadConfig.hiddenZFButtons.indexOf(vm.daiyue.typeId) >= 0 ? false : true;
    });
  }

  function initViewTime() {
    return ToBeReadRemoteService.saveViewTime(sendId);
  }

  vm.onCommonnotionSelect = function(notion) {
    vm.daiyue.ybTempNotion = notion;
  };

  /**
   * 阅毕功能
   *
   * 阅毕完成后，跳转到待阅列表页
   */
  vm.yueBi = yuebi;

  vm.openNotionModal = function() {
    if (vm.dropdown) {
      vm.dropdown = !vm.dropdown;
    }
    vm.stashTempNotion = {};
    vm.stashTempNotion.content = vm.daiyue.ybTempNotion;

    var notionUrl = 'views/toberead/editYbNotion.tpl.html';
    vm.tempNotionContent = vm.daiyue.ybTempNotion;
    if (!vm.modal) {
      var modalPromise = CommonService.createModal(notionUrl,
        createModalScope());
      modalPromise.then(function(modal) {
        vm.modal = modal;
        return $q.all(vm.modal.show());
      });
    } else {
      vm.modal.show();
    }
  };

  function createModalScope() {
    var modalScope = $scope.$new();
    modalScope.saveNotion = function() {
      return yuebi().then(function() {
        return modalScope.closeNotionModal();
      });
    };
    modalScope.closeNotionModal = closeNotionModal;
    modalScope.vm = vm;
    return modalScope;
  }

  function yuebi(content) {
    if (content) {
      vm.daiyue.ybTempNotion = content;
    }

    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard.isVisible) {
      window.cordova.plugins.Keyboard.close();
    }

    return needSaveDaiyue().then(function() {
      return saveDaiyue();
    }).then(function() {
      $sinoGoBackDelegate.back();
    });
  }

  function needSaveDaiyue() {
    var deferred =  $q.defer();
    if(_.isEmpty(vm.daiyue.ybTempNotion)) {
      $ionicPopup.confirm({
        title: '阅毕',
        content: '确定不填写意见？',
        okText: '确定',
        cancelText: '取消'
      }).then(function(res) {
        if (res) {
          deferred.resolve();
        } else {
          deferred.reject();
        }
      });
    } else {
      deferred.resolve();
    }

    return deferred.promise;
  }

  function saveDaiyue() {
    $ionicLoading.show({
      template: '正在处理中，请等待...'
    });
    return ToBeReadRemoteService.saveYb(sendId, vm.daiyue.ybTempNotion)
      .then(function(status) {
        if(status) {
          $ionicLoading.hide();
          return $toast.showShortCenter('阅毕成功！');
        }
      });
  }

  function closeNotionModal() {
    return vm.modal.hide();
  }

  $scope.$on('$destroy', function() {
    if (vm.modal) {
      vm.modal.remove();
    }
  });

  vm.goGroup = function() {
    $sinoGoBackDelegate.back();
  };

  /**
   * 待阅的转发功能
   * @param  {[type]} daiyue
   */
  vm.transimt = function(userIds, userNames) {
    if(!userIds || !userNames) {
      $toast.showShortCenter('请选择人员！');
      return;
    }

    var zfNotion = vm.daiyue.ybTempNotion || '',
      curUserId = vm.daiyue.inUserId,
      curUserName = LinkerService.currentUser.loginName;

    var dispenseInfo = curUserName + '  分发给 ===〉 ' + userNames + ', <br> ';
    var dispenseField = TobereadConfig.getDispenseField(vm.daiyue.relationTable);

    return ToBeReadRemoteService.transimt(curUserId, sendId, zfNotion, userIds, dispenseInfo, dispenseField)
      .then(function(status) {
        if(status) {
          $toast.showShortCenter('转发成功！');
          return status;
        }
      }, function() {
        $toast.showShortCenter('转发失败！');
      });
  };

  /**
   * 待阅中屏蔽局领导
   */
  vm.filter = function(user, depts, superDepts) {
    var appId = CoreAppConfig.getAppId();

    if (appId === 'gjjoa' && user.deptId === '001') {
      return false;
    } else {
      return true;
    }
  }

}]);
