'use strict'

angular.module('COMPANY').controller('JobExam', ['$scope', '$http', '$mdDialog', 'GETLANG', 'ComCtrl', function($scope, $http, $mdDialog, GETLANG, ComCtrl){
  $scope.tmp = ''
  // $scope.examlist = []
  $scope.examlist = new ExamRouter()
  $scope.swlang = GETLANG
  $scope.jobid = $('input[name="__jobcodeid"]').val()
  $scope.fabtool = {
    isopen: false,
    selectclass: 'md-scale',
    btnlist: {
      save: true,
      delete: false,
      refresh: true
    }
  }

  // $scope.fabtool = {
  //   isopen: false,
  //   selectclass: 'md-scale'
  // }

  $scope.openExamSelector = function(){
    $mdDialog.show({
      controller: 'ListExamSelect',
      templateUrl: 'dialog.exam.selectlist.html',
      clickOutsideToClose: false,
      parent: angular.element(document.body),
      locals: {data: $scope.examlist.getExamRouter()}
    }).then(function(result){
      $scope.examlist.addExamRouter(result)
      console.log($scope.examlist)
    }, function(){
      console.log('you are cancel')
    })
  }

  $scope.removeExamList = function(index){
    $scope.examlist.removeExamRouter(index)
  }

  $scope.changeList = function(index, inc){
    $scope.examlist.changePositionList(index, inc)
  }

  $scope.save = function(){
    $scope.saveExamRouter(18)
  }

  $scope.saveExamRouter = function(excode){
    let examrouter = {
      examlist: $scope.examlist.getExamRouter(),
      jobcodeid: $scope.jobid
    }

    ComCtrl.ManageExamRouter.save(examrouter).$promise.then(function(result){
      $scope.swlang.getAlert(excode)
    })
  }

  $scope.refresh = function(){
    let tmprouter = $scope.examlist.getExamRouter()
    let prom = []

    $scope.examlist.getExamRouter().forEach((ex) => {
      prom.push(
        ComCtrl.ManageExam.query({examid: ex.id}).$promise.then(function(result){
          ex.examdata = result.exam.examdata
          ex.question = result.exam.question
        })
      )
    })

    Promise.all(prom).then(() => {
      $scope.saveExamRouter(234)
    })
  }

  $scope.check = function(){
    console.log($scope.examlist.getExamRouter())
  }

  ComCtrl.ManageExamRouter.query({jobid: $scope.jobid}).$promise.then(function(result){
    if (result.examlist !== undefined){
      $scope.examlist.setExamRouter(result.examlist)
    }
  })
}])