/* app module */
var app = angular.module("app", ['ionic', 'boren-templates']);

app.controller('AppController', ['$scope', '$timeout','$state', '$ionicPopup', '$ionicLoading', function($scope, $timeout, $state, $ionicPopup, $ionicLoading){
	$scope.log_info = function(title,body){
		console.log(title+"  ===  "+body);
	};
  
  $scope.userInfo = {
    name: '薛博仁',
    company: '汉得武汉分公司',
    department: 'MAS部门-费控开发部',
    job: '技术顾问',
    logo: 'img/user_logo.png'
  };

  $scope.setUserInfo = function(userInfo){
    $scope.userInfo = userInfo;
  };

  // 依据 state 进行页面跳转
  $scope.goState = function(state, sec){
    if(sec && sec > 0){
      $timeout(function(){
        $state.go(state); 
      }, 100);  
    }else{
      $state.go(state); 
    }
  };

  $scope.showLoading = function(opts){
    // var opts = {
      //   template: '',
      //   templateUrl: '',
      //   noBackdrop: false,
      //   delay: 0, //number
      //   duration: 0 //number
    // };
    if(!opts || (!opts.templateUrl && !opts.template)){
      opts = {
        templateUrl : "templates/loading/onlyIcon.html"
      };
    }
    $ionicLoading.show(opts);
  };
  $scope.hideLoading = function(template){
    $ionicLoading.hide();
  };

  $scope.showAlert = function(title, bodyStr, thenFuc) {
     var alert_title = title && title!= '' ? title : '提示';
     var alertPopup = $ionicPopup.alert({
       title: alert_title,
       template: bodyStr
     });
     if(thenFuc){
      alertPopup(thenFuc(res));
     }
   };
  $scope.showConfirm = function(title, bodyStr, thenFuc, okText, cancelText) {
    var confirmPopup = $ionicPopup.confirm({
      title: title ? title : "提示",
      template: bodyStr,
      cancelText : cancelText ? cancelText : '取消',
      okText: okText ? okText : '确定'
    });
    if(thenFuc){
     confirmPopup.then(thenFuc);
    }
  };

}]);

/*
*  url: '/detail/{record_id}'
*  url: '/detail/:record_id'
*  $scope.record_id = $stateParams.record_id
*  
*  // 限定id为6位16进制数字
*  url: '/inbox/{inboxId:.*}'
*  url: '/inbox/{inboxId:[0-9a-fA-F]{6}}'
*  url: '/inbox?sort'     /inbox?sort=ascending 将会被匹配
*  
*  Params路由参数 不能和url选项混用
*  如果设置了视图选项-Views，则该状态的‘template’，‘templateUrl’及‘templateProvider’将被忽略
*  
*  $stateparams用来提取在url中的不同参数
*  url: '/inbox/:inboxId/messages/{sorted}?from&to'
*  '/inbox/123/messages/ascending?from=10&to=20'
*  此时对应的 $stateparams 的值是： 
*     {inboxId:'123',sorted:'ascending',from:10,to:20}
*  
*  
*/
app.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('app', {
      url: "/app",
      abstract: true,
      templateUrl: "html/Menu_Left.html"
    })
    .state('login', {
      url: "/login",
      templateUrl: "html/Login.html"
    })
    .state('app.home', {
      url: "/home",
      abstract: true,
      views: {
        'menuContent' :{
          templateUrl: "templates/Home.html"
        }
      }
    })
      .state('app.home.main', {
        url: "/main",
        views: {
          'homeContent' :{
            templateUrl: "html/Home_Main.html"
          }
        }
      })
    .state('app.setting', {
      url: "/setting",
      abstract: true,
      views: {
        'menuContent' :{
          templateUrl: "templates/Setting.html"
        }
      }
    })
      .state('app.setting.main', {
        url: "/main",
        views: {
          'settingContent' :{
            templateUrl: "html/Setting_Main.html"
          }
        }
      })
      .state('app.setting.changepass', {
        url: "/changePass",
        views: {
          'settingContent' :{
            templateUrl: "html/Setting_ChangePass.html"
          }
        }
      })
      .state('app.setting.certify', {
        url: "/certify",
        views: {
          'settingContent' :{
            templateUrl: "html/Setting_Certify.html"
          }
        }
      })
      .state('app.setting.feedback', {
        url: "/feedback",
        views: {
          'settingContent' :{
            templateUrl: "html/Setting_Feedback.html"
          }
        }
      })
      .state('app.setting.aboutus', {
        url: "/aboutus",
        views: {
          'settingContent' :{
            templateUrl: "html/Setting_AboutUs.html"
          }
        }
      })
    .state('app.icon', {
      url: "/icon",
      abstract: true,
      views: {
        'menuContent' :{
          templateUrl: "templates/Icon.html"
        }
      }
    })
      .state('app.icon.main', {
        url: "/main",
        views: {
          'iconContent' :{
            templateUrl: "html/Icon_Main.html"
          }
        }
      })
    .state('app.list', {
      url: "/list",
      abstract: true,
      views: {
        'menuContent' :{
          templateUrl: "templates/List.html"
        }
      }
    })
      .state('app.list.main', {
        url: "/main",
        views: {
          'listContent' :{
            templateUrl: "html/List_Main.html"
          }
        }
      })
      .state('app.list.conllection', {
        url: "/collection",
        views: {
          'listContent' :{
            templateUrl: "html/List_Collection.html"
          }
        }
      })
    .state('app.error', {
      url: "/error",
      views: {
        'menuContent' :{
          templateUrl: "html/Error.html"
        }
      }
    });
  // 主要用于重定向路由  
  $urlRouterProvider
    .when('','app/home/main')
    .when('/app/home','app/home/main')
    .when('/app/setting','app/setting/main')
    .otherwise("/app/home/main");
    // .rule(function($injector, $location){
    //   return '/app/setting/aboutus';
    // });
    // .otherwise(function($injector, $location){
    //   $location.path("/app/error");
    // });
});

// 用于页面之间跳转时的数据共享 

app.service('AjaxService', ['$http','$q', function($http, $q){
  var service = {};

  service.config = {
        //baseUrl:"http://1.202.156.238/" //测试IP
        baseUrl:"http://uathecapp.sinosig.com/" //测试环境 域名(当前只能内网访问2015-07-02)
        //baseUrl:"http://111.203.203.12/" // 正式IP
        //baseUrl:"http://hecapp.sinosig.com/" // 正式环境 域名(当前只能外网访问2015-07-02)
  };
  service.urls = {
        url_login: service.config.baseUrl + "app_login.svc",
        url_todo_list: service.config.baseUrl + 'modules/app/to_do_list.svc',
        url_done_list: service.config.baseUrl + 'modules/app/approve_history.svc',
        
        url_detail_budget: service.config.baseUrl + "modules/app/bgt_change_detail.svc",
        url_detail_postpay: service.config.baseUrl + "modules/app/exp_rep_detail.svc",
        url_detail_loan: service.config.baseUrl + "modules/app/csh_pay_req_detail.svc",
        url_detail_application: service.config.baseUrl + "modules/app/exp_req_detail.svc",
        url_approve_history: service.config.baseUrl + "modules/app/doc_approve_history.svc",
        url_node_actions: service.config.baseUrl + "modules/app/nodeaction.svc"
  };

  service.post = function(url, datas){
      var promise = $http({
            method: 'POST',
            headers: {
                'Content-type': "application/x-www-form-urlencoded"
            },
            url: url,
            data: datas
        });
        return promise;
  };

  return service;
}]);

app.service('UtilService', [function(){
  var util = {};
  util.encodeParameters = function(parameters){
      var jsonParameters = JSON.stringify({  parameter  : parameters});
      return '_request_data=' + encodeURIComponent(jsonParameters);
  };

  util.codeMesgs = [
      { code: 408, message: "请求超时,请稍候再试"  },
      { code: 503, message: "服务器暂无响应,请稍候再试" },
      { code: 404, message: '该页面已不存在,请联系系统管理员' },
  ];
  util.getError = function(code){
        var errorMessage = "";
        for (var i = this.codeMesgs.length - 1; i >= 0; i--) {
            if(code == this.codeMesgs[i].code){
                errorMessage =  this.codeMesgs[i].message;
            }
        };
        if(errorMessage == "" ){
            errorMessage = "连接错误，状态码: " + code;
        }
        return errorMessage;
  };
  util.showError = function(title, message){
  	ons.notification.alert({
  		title: "Error - "+title,
  		message: message,
  		buttonLabel: '了解',
  		animation: 'slide'
  	});
  };
  util.showAjaxErrorByCode = function(code, title){
  	var title = title ? title : '网络错误';
  	var message = util.getError(code);
  	util.showError(title ,message);
  };
  return util;
}]);
