var angular = require('angular');
var _ = require('jsUtil');
require('../modules');
require('../../../commons/services/CommonService');
require('../services/CommonNotionService');
require('../../linker/services/LinkerService');
require('../services/ToBeReadremoteService');

var module = angular.module('flow.directives');

module.directive('sinoNotionEdit', function(CommonService, $toast, CommonNotionService,
  LinkerService, NotionService, ToBeReadRemoteService, $ionicPopup, $q, $ionicLoading) {
  var notionTypeFlow = 'flow';

  return {
    restrict: 'A',
    link: function(scope, ele, attrs) {
      ele.on('click', function($event) {
        scope.$evalAsync(function() {
          if (attrs.notionType === notionTypeFlow) {
            scope.editFlowNotion();
          } else {
            scope.editYBNotion();
          }
        });
      });

      scope.editFlowNotion = function() {
        scope.okButton = attrs.okButton || '保存意见';
        scope.notion = scope.$parent.$eval(attrs.notion);
        scope.stashNotion = {};
        scope.stashNotion.notion = scope.$parent.$eval(attrs.notion) || '';
        openEditNotion();
      };

      scope.editYBNotion = function() {
        scope.stashNotion = {};
        scope.stashNotion.notion = scope.$parent.$eval(attrs.notion) || '';
        if(!_.isEmpty(scope.stashNotion.notion)) {
          saveToBeReadNotion();
        } else {
          scope.okButton = attrs.okButton || '阅毕';
          scope.notion = scope.$parent.$eval(attrs.notion);
          openEditNotion();
        }
      };

      function openEditNotion() {
        var notionUrl = 'views/flow/modal/editNotion.tpl.html';
        if (!scope.modal) {
           CommonService.createModal(notionUrl, scope, false).then(function(modal) {
            scope.modal = modal;
            scope.modal.show();
          });
        } else {
          scope.modal.show();
        }
      }

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

      scope.closeNotionModal = function() {
        if (scope.modal) {
          scope.modal.hide();
        }
      };

      scope.saveNotion = function() {
        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard.isVisible) {
          window.cordova.plugins.Keyboard.close();
        }

        return (attrs.notionType === notionTypeFlow) ? saveFlowNotion() : saveToBeReadNotion();
      };

      function saveToBeReadNotion() {
        var needSavePromise = $q.when(true);
        if(_.isEmpty(scope.stashNotion.notion)) {
          needSavePromise = $ionicPopup.confirm({
            title: '阅毕',
            content: '确定不填写意见？',
            okText: '确定',
            cancelText: '取消'
          });
        }

        return needSavePromise.then(function(need) {
          if (!need) { return; }

          $ionicLoading.show({
            template: '正在处理中，请等待...'
          });
          return ToBeReadRemoteService.saveYb(attrs.daiyueId, scope.stashNotion.notion)
            .then(function(data) {
            $ionicLoading.hide();
            if (data) {
              $toast.showShortCenter('操作成功!');
              scope.closeNotionModal();
              scope.onEdit({notion: scope.stashNotion.notion});
            } else {
              $toast.showShortCenter('操作失败!');
            }
          }, function() {
            $ionicLoading.hide();
            $toast.showShortCenter('操作失败!');
          });
        });
      };

      function saveFlowNotion() {
        var opinion = {
          'recordId': attrs.recordId,
          'flowTypeId': attrs.flowType,
          'notionName': attrs.flowNotionName,
          'notion': scope.stashNotion.notion.replace(/<[^>]*>/g, ''),
          'tableName': attrs.tableName,
          'signFieldName': '',
          'idFieldName': attrs.tableId
        };
        opinion.signTime = _.formatDate(new Date(), 'Y-m-d H:i:s');
        return NotionService.saveTempNotion(opinion).then(function(data) {
          $toast.showShortCenter('保存意见成功!');
          scope.closeNotionModal();
          scope.$parent.$eval(attrs.onEdit, {notion: scope.stashNotion.notion});
          scope.onEdit({notion: scope.stashNotion.notion});
        }, function() {
          $toast.showShortCenter('保存意见失败!');
        })
      };

      scope.setCommonNotion = function(notion) {
        scope.stashNotion.notion = scope.stashNotion.notion + notion;
      }

      scope.saveCommonNotion = function() {
        if (!scope.stashNotion.notion) {
          $toast.showShortCenter('添加的意见不能为空!');
          return;
        }
        return LinkerService.getCurrentUser().then(function(loginUser) {
          return CommonNotionService.saveCommonNotion(loginUser.userId, scope.stashNotion.notion)
          .then(function(data) {
            if (data) {
              $toast.showShortCenter('添加成功!');
            }
            scope.$broadcast('scroll.infiniteScrollComplete');
            scope.$broadcast('scroll.resize');
          });
        });
      };
    }
  };
});
