var angular = require('angular');
var ionic = require('ionic');
require('jsUtil');
require('../modules');
require('../../appconfig/services/appFlowConfigService');
require('uiRouter');
'use strict';

var module = angular.module('login.services');

module.factory('LoginService', function($http, $q, $rootScope, localforage, $state, LinkerService, AppConfig, sinoNetwork, appFlowConfigService) {
  var _loginSuccessAction = function() {};

  /**
   * 登录。
   * {
   * "success":true;      //成功为true，失败为false
   * }
   */
  function login(params, successFn) {
    successFn = successFn || _loginSuccess;
    params.devSn = window.device.uuid;
    params.device = getDeviceInfo();
    return $http({
      method: 'POST',
      url: '/login',
      data: params,
      timeout: 15000//15s
    }).then(function(response) {
      applyLoginResponse(response, successFn);
      return response.data;
    });
  }

  /**
   * 注销登录。
   * @return {Object}
   * {
   * "status":true;      //成功为true，失败为false
   * }
   */
  function logout() {
    var success = {status: true},
      userId = LinkerService.currentUserId;

    localStorage.removeItem('userToken');
    localStorage.removeItem('validDate');
    LinkerService.logout();
    $rootScope.$broadcast('logout', userId);
    return $q.when(success);
  }

  function calogin() {
    return sinoNetwork.getCACert().then(function(cert) {
      if (_.isEmpty(cert) || _.isEmpty(cert.cert)) {
        return {success: false, message: '登录失败,证书不存在！'};
      } else {
        return login({cert: cert.cert});
      }
    });
  }

  /**
   * 判断用户是否曾经登录过
   *
   * 方式为判断用户身份是否认证过，并且还在认证有效期内
   *
   * @return {Boolean}
   */
  function onceLogin() {
    var userId = localStorage.getItem('userId'),
      userToken = localStorage.getItem('userToken'),
      validDate = localStorage.getItem('validDate');
    return $q.when((userId && userToken && validDate && parseInt(validDate) >= new Date().getTime()));
  }

  /**
  * 初始化流程登录方法
  *
  * 1.若果初始化之前登录过，并且没有过期的话直接进入下一步
  * 2.否则的话，我们查看是否可以同ca登录，若果ca证书存在的话，通过ca证书登录。
  */
  function onLoginAction(nextAction) {
    _loginSuccessAction = nextAction;
    onceLogin().then(function(success) { // 1、是否登录过
      if (success && appFlowConfigService.needGesturePassword()) { // 2、登录过，并且需要手势密码
         _loginSuccessAction();
        return success;
      } else {
        return toPasswordOrCA();// 3、若果没有登录过，判断使用CA或者密码
      }
    });
  }

  function toPasswordOrCA() {
    return sinoNetwork.getCACert().then(function(cert) {
      if (_.isEmpty(cert.cert) && (AppConfig.getCustomResult('passwordLoginEnable'))) {
        $state.go('login');
      } else {
        $state.go('calogin');
      }
    });
  }

  function getDeviceInfo() {
    var deviceInfo = {},
      device = window.device;
    //设备唯一uuid
    deviceInfo.devSn = device.uuid;
    //手机设备型号
    deviceInfo.devModel = device.model;
    //设备名称
    deviceInfo.devName = device.model;
    //操作系统平台
    deviceInfo.osType = device.platform;
    //对应操作系统的版本
    deviceInfo.osVersion = device.version;
    //浏览器版本号
    deviceInfo.browserVersion = '';
    //app应用的版本号
    deviceInfo.appVersion = AppConfig.version;
    deviceInfo.terminalType = ionic.Platform.isWebView()? 'app' : 'browser';
    return deviceInfo;
  }

  function applyLoginResponse(response, successFn) {
    var data = response.data;
    if (data.success && !data.mask) {
      applyUserToken(response);
      applyUserId(response);
      applyValidateDate(response);
      successFn(response);
    }
  }

  function applyUserToken(response) {
    var userToken = response.headers('userToken')? response.headers('userToken') : response.data && response.data.userToken;
    localStorage.setItem('userToken', userToken);
  }

  function applyUserId(response) {
    var userId = response.data && response.data.userId;
    LinkerService.setCurrentUser(userId);
    localStorage.setItem('userId', userId);
  }

  function applyValidateDate(response) {
    var validDate = response.data && response.data.validDate;
    if (validDate) {
      validDate = _.parseDate(validDate, 'Y-m-d h:i:s').getTime();
    }
    localStorage.setItem('validDate', validDate);
  }

  function _loginSuccess(response) {
    $rootScope.$broadcast('login', response.data);
    $rootScope.$broadcast('login.buildWebsocket');
    if (jsUtil.isObjectExist('cordova.plugins.Keyboard') &&
      window.cordova.plugins.Keyboard.isVisible) {
      window.cordova.plugins.Keyboard.close();
    }
    if (_loginSuccessAction) {
      _loginSuccessAction();
    }
  }

  function getLastLoginUser() {
    var userJSON = localStorage.getItem('lastLoginUser');
    try {
        return userJSON ? JSON.parse(userJSON) : null;
    } catch (e) {
        return null;   
    }
  }

  return {
    login: login,
    logout: logout,
    calogin: calogin,
    onLoginAction: onLoginAction,
    getLastLoginUser: getLastLoginUser,
    defaultLoginSuccess: _loginSuccess
  };
});
