var angular = require('angular');
require('../modules');
require('../services/InfoReleaseService');
'use strict';

var module = angular.module('info');
module.controller('InfoDetailCtrl', function($scope, $state,
  $stateParams, $q, AppConfig, InfoReleaseService, ModelService) {
  var modelId = $stateParams.modelId,
    pid = $stateParams.pid,
    infoId = $stateParams.infoId,
    pageNo = parseInt($stateParams.pageNo);
  $scope.title = $stateParams.modelName;
  $scope.recordId = $stateParams.infoId;
  $scope.tableName = 'S_CONTENT_' + modelId;

  /**
   * 初始化页面
   */
  $scope.$on('$ionicView.enter', function() {
    init();
    inCreateNotion();
  });
  var picId = null;

  function init() {
    return InfoReleaseService.getInfoByInfoId(pid, infoId)
    .then(function(data) {
      $scope.inf = data;

      if(!$scope.inf.originContent) {
        $scope.waiting = true;
      } else {
        $scope.waiting = false;
      }
      $scope.waitingText = '正文载入中...';
      $scope.waitError = false;//正文内容加载失败
    }).then(function() {
      if(!$scope.inf.originContent) {
        return InfoReleaseService.getInfo(pid, modelId, infoId).then(function(data) {
          $scope.waiting = false;
          $scope.inf.originContent = data.content;
          ModelService.getModelOfId(pid).then(function(model) {
            if (model.notion !== false && model.notion !== 'false') {
              ++$scope.inf.notion;
            }
          });

          return data;
        }, function() {
          $scope.waiting = false;
          $scope.waitError = true;//加载失败
          $scope.waitingText = '正文加载失败！';
        });
      }
    });
  }

  function inCreateNotion() {
    ModelService.getModelOfId(pid).then(function(model) {
      if (model.notion !== false && model.notion !== 'false') {
        InfoReleaseService.updateNotion(pid, modelId, infoId, pageNo);
      }
    });
  }

  /**
   * 刷新
   */
  $scope.onRefresh = function() {
    $scope.loaderror = false;
    init();
  };

});
