'use strict'

angular.module('RECRUIT').controller('RecruitHistory', function ($scope, $mdDialog, RecService, $filter, $timeout, $mdSidenav, SwapLang) {
  $scope.isReady = false
  $scope.initCondition = function () {
    $scope.conditions = {
      filter: {
        all: '',
        jobid: '',
        status : {
          qualified : '',
          unqualified : ''
        },
        date: {
          start: '',
          end: ''
        }
      },
      sort: '',
      orderBy: ''
    }
    $('input[name="dateFilter"]').val('')
  }
  $scope.swlang = new swaplang()
  let cscForm = document.cscform
  $scope.lang = getLang()
  $scope.initCondition()
  $scope.recruitHistorys = []




  $scope.refreshView = () => {
    RecService.RestMapplicantHistory.getQuery().$promise.then(function (data){
      $scope.recruitHistorys = data.result
      $scope.isReady = true
    })
  }
  $scope.refreshView();

  $scope.renew = ($applicant) => {





    SwapLang.getConfirm(250).then(function () {
      RecService.RestMapplicantHistory.renew($applicant).$promise.then(() => {
        SwapLang.getAlert(18)
      }, (error) => {
        // SwapLang.getAlert(7, error.data.result)
      })
    })
  }



  $scope.filterDate = function (item) {
    let startDate = $scope.conditions.filter.date.start
    let endDate = $scope.conditions.filter.date.end
    if (startDate !== '' && endDate !== '') {
      return item.createDate >= startDate && item.createDate <= endDate
    }
    else {
      return item
    }
  }

  $scope.findResult = []
  $scope.findHistory = function () {


    if (!$scope.conditions.filter.all && !$scope.conditions.filter.date.start ) {
      let textReq = $scope.swlang.swap2String('SW012974')
      alert(textReq)
    }
    else {
      let allData = $scope.recruitHistorys
      let filterAll = $filter('filter')(allData, $scope.conditions.filter.all)
      $scope.findResult = $filter('filter')(filterAll, function (value) {
        return $scope.filterDate(value)
      })
      if($scope.findResult.length === 0) {
        let textNoFound = $scope.swlang.swap2String('SW006905')
        alert(textNoFound)
      }
    }

  }

  $scope.toggleLeft = buildToggler('left');
  function buildToggler(componentId) {
    return function() {
      $mdSidenav(componentId).toggle();
    };
  }
  $scope.goPages = (applicantid, candidateid) => {
    cscForm.action = "FillFormApplicant.jsp"
    cscForm.__applicantid.value = applicantid
    cscForm.__candidateid.value = candidateid
    // cscForm.submit()
  }


  function processSourceSearch(obj) {
    let nameEng = obj.name['eng']
    let nameTha = obj.name['tha']
    let newSourceItemEng = {
      label: nameEng,
      value: nameEng
    }
    let isFoundEng = SourceSearch.find(function (element) {
      return element.label === nameEng
    })
    if (isFoundEng === undefined) {
      SourceSearch.push(newSourceItemEng)
    }

    let newSourceItemTha = {
      label: nameTha,
      value: nameTha
    }
    let isFoundTha = SourceSearch.find(function (element) {
      return element.label === nameTha
    })
    if (isFoundTha === undefined) {
      SourceSearch.push(newSourceItemTha)
    }
  }

  let SourceSearch = []
  $scope.initSourceAutoComplete = function () {
    RecService.RestMbu1.getQuery().$promise.then(function (data) {
      angular.forEach(data.result, function (obj) {
        processSourceSearch(obj)
      });
    })
    RecService.RestMbu2.getQuery().$promise.then(function (data) {
      angular.forEach(data.result, function (obj) {
        processSourceSearch(obj)
      });
    })
    RecService.RestMbu3.getQuery().$promise.then(function (data) {
      angular.forEach(data.result, function (obj) {
        processSourceSearch(obj)
      });
    })
    RecService.RestMbu4.getQuery().$promise.then(function (data) {
      angular.forEach(data.result, function (obj) {
        processSourceSearch(obj)
      });
    })
    RecService.RestMbu5.getQuery().$promise.then(function (data) {
      angular.forEach(data.result, function (obj) {
        processSourceSearch(obj)
      });
    })
    RecService.RestMjobcode.getQuery().$promise.then(function (data) {
      angular.forEach(data.result, function (obj) {
        processSourceSearch(obj)
      });
    })
  }

  function getSourceSearch() {
    if (SourceSearch.length === 0) {
      $scope.initSourceAutoComplete()
    }
    return SourceSearch
  }

  $scope.goSetCommittee = (candidateid) => {
    cscForm.action = "CommitteeSetupForm.jsp"
    cscForm.__candidateid.value = candidateid
    cscForm.submit()
  }

  // Jquery Zone
  $('body')
    .on('focus', '.datepicker', function () {
    let datepickerOptions = {
      yearRange: "c-80:c+15",
      dateFormat: "yy-mm-dd",
      changeMonth: true,
      changeYear: true,
      showAnim: 'clip',
      required: true
    };
    $(this).datepicker(datepickerOptions)
      .on('keydown', function (e) {
        e.preventDefault();
      })
    })
    .on('focus', '.autocomplete', function () {
      $(this).autocomplete({
        source: getSourceSearch(),
        autoFocus: true,
        minLength: 3,
        select: function (event, ui) {
        }
      });
    });


  $(window).keydown(function (event) {
    if (event.keyCode === 13) {
      event.preventDefault();
    }
  });
  let label = {
    dateRange: {
      'clear': $scope.swlang.swap2String('SW013047'),
      'custom': $scope.swlang.swap2String('SW012076'),
      'apply': $scope.swlang.swap2String('SW013071')
    }
  }
  let rangesOptionEng = {
    'Today': [moment(), moment()],
    'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
    'Last Week': [moment().subtract(1, 'week').startOf('week'), moment().subtract(1, 'week').endOf('week')],
    'This Month': [moment().startOf('month'), moment().endOf('month')],
    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
  }
  let rangesOptionTha = {
    'วันนี้': [moment(), moment()],
    'เมื่อวาน': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
    '7 วันล่าสุด': [moment().subtract(6, 'days'), moment()],
    '30 วันล่าสุด': [moment().subtract(29, 'days'), moment()],
    'สัปดาห์ที่แล้ว': [moment().subtract(1, 'week').startOf('week'), moment().subtract(1, 'week').endOf('week')],
    'เดือนนี้': [moment().startOf('month'), moment().endOf('month')],
    'เดือนที่แล้ว': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
  }
  $('input[name="dateFilter"]').daterangepicker({
    autoUpdateInput: false,
    locale: {
      cancelLabel: label.dateRange.clear,
      customRangeLabel: label.dateRange.custom,
      applyLabel: label.dateRange.apply
    },
    ranges: ($scope.lang === 'eng') ? rangesOptionEng : rangesOptionTha
  })
    .on('keydown', function (e) {
      e.preventDefault();
    })
    .on('apply.daterangepicker', function (ev, picker) {
      let strStart = picker.startDate.format('YYYY-MM-DD')
      let strEnd = picker.endDate.format('YYYY-MM-DD')
      let strShowDateRange = `${$filter('ddmmyyyyDate')(strStart)} - ${$filter('ddmmyyyyDate')(strEnd)}`
      $scope.$apply(function () {
        $scope.conditions.filter.date.start = strStart
        $scope.conditions.filter.date.end = strEnd
      });
      $(this).val(strShowDateRange);
    })
    .on('cancel.daterangepicker', function (ev, picker) {
      $scope.$apply(function () {
        $scope.conditions.filter.date.start = ''
        $scope.conditions.filter.date.end = ''
      });
      $(this).val('')
    });

  // End Jquery Zone

})