'use strict';

var angular = require('angular');

require('../modules');
require('../services/DeviceManager');
require('jsUtil');
require('../../login/services/LoginService');

var module = angular.module('devicemanager.controller');

module.controller('DeviceBindCtrl', function($scope, DeviceManager, LinkerService, Timer,
  $q, $ionicActionSheet, LoginService, $state, AppConfig) {
  $scope.viewStatus = false;
  $scope.bindStatus = null;
  $scope.bindSucess = true;
  $scope.devSn = DeviceManager.getDevSn() || '';

  var delayId;
  var timer = Timer.interval(function() {
    $scope.bindStatus = DeviceManager.getPageInfoStatus();
    if($scope.bindStatus === 1) {
      if (delayId) {
        Timer.clear(delayId);
      }
      delayId = Timer.delay(function() {
        $scope.viewStatus = true;
      }, 500);
    } else {
      $scope.viewStatus = false;
    }
  }, 500);

  $scope.$on('$destroy', function() {
    Timer.clear(timer);
  });

  /**
   * 绑定
   */
  $scope.bind = function() {
    return DeviceManager.bind(LinkerService.currentUserId, $scope.devSn).then(function() {
      return DeviceManager.viewApprovalStatus(LinkerService.currentUserId, $scope.devSn);
    });
  };
  /**
   * 申请绑定
   */
  $scope.applyBind = function() {
    return DeviceManager.submitApply(LinkerService.currentUserId, $scope.devSn);
  };

  /**
   * 查看绑定申请的审核状态
   */
  $scope.viewApprovalStatus = function() {
    return DeviceManager.viewApprovalStatus(LinkerService.currentUserId, $scope.devSn);
  };

  /**
   * 重新登录
   */
  $scope.toLogin = function() {
    LoginService.logout();

    if(!AppConfig.getCustomResult('passwordLoginEnable')) {
      $state.go('calogin');
    } else {
      $state.go('login'); // 定制是否有密码登录
    }
  };

  function actionSheet() {
    var deferred = $q.defer();
    $scope.needLogout = true;
    // if ($scope.needLogout) {
      $ionicActionSheet.show({
        buttons: [{
          text: '<i class="icon ion-log-out sino-logout-icon"></i>退出登录'
        }],
        cancelText: '取消',
        cancel: function() {
          deferred.reject('取消登录');
          return true;
        },
        buttonClicked: function() {
          deferred.resolve(true);
          return true;
        }
      });
    // } else {
    //   deferred.resolve(false);
    // }
    return deferred.promise;
  }
});
