'use strict';

var angular = require('angular'),
  _ = require('jsUtil');

require('../modules');

angular
  .module('warrant.services')
  .factory('WarrantService', WarrantService);

/** @ngInject */
function WarrantService($http, $q, CacheService) {
  var _warrantStatus = {
    type: 'brief', // forever
    date: '2016-07-03',
    isOutDeadline: true
  }; //测试数据

  var validityBegin; //有效期开始时间
  var warrantStatusData = CacheService.get('warrant') || {};

  var service = {
    warrantStatus: warrantStatusData,
    isInValidity: isInValidity, // 获取当前时间是否在有效期内
    getWarrantStatus: getWarrantStatus,
    updateWarrantStatus: updateWarrantStatus,
    getIsOutDeadline: getIsOutDeadline,
    setNowDate: setNowDate,
    calc: calcOutDeadline //为了测试
  };

  /**
   * 更新当前的授权状态
   * @return {Promise}
   */
  function updateWarrantStatus() {
    return $http.get('/license/info', {
      timeout: 15000
    }).then(function(response) {
      var warrantData = response.data;
      if(warrantData) {
        warrantData.isOutDeadline = calcOutDeadline(warrantData) || false;
        CacheService.put('warrant', warrantData);
        service.warrantStatus = warrantStatusData = warrantData;
      }
      return warrantData;
    });
  }

  /**
   * 获取授权状态
   * @return {Promise}
   */
  function getWarrantStatus() {
    return updateWarrantStatus().then(function(data) {
      return data;
    }, function() {
      return $q.when(warrantStatusData);
    });
  }

  /**
   * 判断是否已经过了试用期
   * @return {Boolean}
   */
  function getIsOutDeadline() {
    if(warrantStatusData && !_.isEmpty(warrantStatusData.isOutDeadline)) {
      return $q.when(warrantStatusData.isOutDeadline);
    } else {
      return getWarrantStatus().then(function(data) {
        return $q.when(calcOutDeadline(data));
      });
    }
  }

  function calcOutDeadline(warrant, nowDate) {
    var nowDate = setNowDate(nowDate) || new Date();
    if(warrant.type === 'brief') {
      var deadLine = _.DateUtil.parse(warrant.date, 'Y-m-d');
      var time = (nowDate.getTime() - deadLine.getTime()) / (24 * 60 * 60 * 1000);
      if(time >= 1) { // 已经超过试用期
        return true;
      }
    }
    return false;
  }

  function setNowDate(nowDate) { //为了测试
    if(nowDate) {
      return _.DateUtil.parse(nowDate, 'Y-m-d H:i:s');
    }
  }

  function isInValidity() {
    // 超过10分钟有效期的，validityBegin重置
    if(validityBegin && validityBegin + 10 * 60 * 1000 < Date.now()) {
      validityBegin = null;
    }
    if(validityBegin) { // 则判断是够距离设置的时间在10分钟之内
      return validityBegin + 10 * 60 * 1000 >= Date.now();
    }
    validityBegin = Date.now();
    return false; // 有效期开始时间没有被设置，则第一次进行设置，并返回false
  }

  return service;
}
