'use strict';

var angular = require('angular');

require('../modules');
require('../services/DeviceLoginRecordsService');
require('../services/PasswordVerifyService');

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

module.controller('DeviceListCtrl', function($rootScope, $scope, DeviceLoginRecordsService,
  LinkerService, $state, $location, $ionicPopup, $toast,
  $ionicLoading, PasswordVerifyService) {

  $scope.refreshState = {
    begin: false,
    done: false
  };

  $scope.device = window.device;

  $scope.$on('$ionicView.loaded', function() {
    $scope.onRefresh();
  });

  //展示登录设备历史
  function getUserLoginRecordsOnDevice () {
    var userId = LinkerService.currentUserId;
    return DeviceLoginRecordsService.getRelatedDevices(userId)
    .then(function(data) {
      data = data || [];
      data = data.filter(function(item) {
        return item.applyUserId === userId || item.userId === userId;
      });
      $scope.loginDeviceRecords = data;
    });
  }

  //页面上的返回按钮
  $scope.goBack = function() {
    $state.go('devicemanager.accountProtect');
  };

  //锁定设备
  $scope.lock = function(item) {
    popupConfirmPassword(function() {
      lockAndUnlock(item.devSn, 'LOCK');
    });
  };

  //解锁设备
  $scope.unlock = function(item) {
    popupConfirmPassword(function() {
      lockAndUnlock(item.devSn, 'UNLOCK');
    });
  };

  function createBindFn(bindFn, loadingText, successFn) {
    return function(item) {
      popupConfirmPassword(function() {
        $ionicLoading.show({
          template: loadingText
        });
        DeviceLoginRecordsService[bindFn](item.devBindingId).then(function() {
          successFn(item);
        }, function() {
          $toast.showShortBottom('操作失败');
        })['finally'](function() {
          $ionicLoading.hide();
        });
      });
    };
  }

  /**
   *
   */
  $scope.applyBind = createBindFn('applyBind', '正在绑定', function(item) {
    item.bindingUserID = LinkerService.currentUser.userId;
    item.userId = LinkerService.currentUser.userId;
    item.bindingStatus = '2';
  });

  /**
   * 退回绑定申请，即绑定申请不通过
   */
  $scope.rejectBind = createBindFn('rejectBind', '正在退回绑定申请', function(item) {
    var index = $scope.loginDeviceRecords.indexOf(item);
    if (index >= 0) {
      $scope.loginDeviceRecords.splice(index, 1);
    }
  });

  $scope.unBind = createBindFn('unBind', '正在解除绑定', function(item) {
    var index = $scope.loginDeviceRecords.indexOf(item);
    if (index >= 0) {
      $scope.loginDeviceRecords.splice(index, 1);
    }
  });

  $scope.getLoginHistory = function() {
    $state.go('devicemanager.showLoginHistory');
  };

  $scope.onRefresh = function() {
    $scope.refreshState.begin = true;
    $scope.refreshState.done = false;
    getUserLoginRecordsOnDevice().then(function() {
      $scope.$broadcast('scroll.refreshComplete');
    })['finally'](function() {
      $scope.refreshState.done = true;
    });
  };

  /**
   * 解锁与锁定
   */
  function lockAndUnlock(devSn, lockStatus) {
    var userId = LinkerService.currentUserId;
    return DeviceLoginRecordsService.lockDevice(userId, lockStatus, devSn)
    .then(function(data) {
      if (data) {
        for(var i = 0; i < $scope.loginDeviceRecords.length; i ++) {
          if ($scope.loginDeviceRecords[i].devSn === devSn) {
            $scope.loginDeviceRecords[i].lockStatus = lockStatus;
            return;
          }
        }
      } else {
        $toast.showShortCenter('解锁失败，请重新操作');
      }
    });
  }

  function popupConfirmPassword(fn) {
    var $popupScope = $scope.$new();
    $popupScope.data = {};
    $ionicPopup.show({
      template: '<input type="password" ng-model="data.password">',
      title: '安全性操作',
      subTitle: '请输入登录密码',
      scope: $popupScope,
      buttons: [{
        text: '取消',
        onTap: function() {
          $popupScope.data.password = '';
        }
      }, {
        text: '<b>登录</b>',
        type: 'button-positive',
        onTap: function() {
          var userName = LinkerService.currentUser.userName;
          var user = {
            userName: userName,
            password: $popupScope.data.password
          };
          PasswordVerifyService.isTurePassword(LinkerService.currentUserId, user.password).then(function(data) {
            if(data) {
              $popupScope.data.password = '';
              fn();
            }else {
              $toast.showShortCenter('密码错误，请重新输入。');
            }
          });
        }
      }]
    });
  }
});
