/**
 * Created by PPMaj on 11/24/2016.
 */
'use strict'

angular.module('RECRUIT').controller('DropResume', function ($q, $scope, $mdDialog, RecService, $filter, $mdSidenav, SwapLang) {

  $scope.isReady = false
  $scope.initCondition = function () {
    $scope.conditions = {
      filter: {
        all: '',
        jobid: '',
        // showUnqualified: true,
        status: {
          qualified: '',
          unqualified: ''
        },
        date: {
          start: '',
          end: ''
        }
      },
      sort: '',
      orderBy: ''
    }
    $('input[name="dateFilter"]').val('')
  }
  $scope.goPages = (app) => {
    cscForm.action = "FillFormApplicant.jsp"
    cscForm.__action.value = "DROP"
    cscForm.__dropresume.value = JSON.stringify(app)
    cscForm.target = "_blank"
    // cscForm.submit()
  }
  $scope.filterQualified = function (item) {
    if ($scope.conditions.filter.status.qualified === '' && $scope.conditions.filter.status.unqualified === '') {
      return item
    }
    else {
      return item.qualified === $scope.conditions.filter.status.qualified ||
        item.qualified === $scope.conditions.filter.status.unqualified
    }
  }
  $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.toggleLeft = buildToggler('left');
  function buildToggler(componentId) {
    return function () {
      $mdSidenav(componentId).toggle();
    };
  }




  //End Function Zone


  $scope.swlang = new swaplang()
  let cscForm = document.cscform
  $scope.lang = getLang()
  $scope.applicants = []
  $scope.dropResume = []
  $scope.initCondition()

  RecService.RestMapplicant.getDropResume().$promise.then(function (data) {
    $scope.dropResume = data.result
    // console.log($scope.dropResume)
    $scope.isReady = true
  })


  $scope.removeObject = (p_app) => {
    $scope.dropResume.splice($scope.dropResume.indexOf(p_app), 1)
  }

  $scope.transferToApplicant = (p_app) => {
    SwapLang.getConfirm(1).then(function () {
      p_app.applicantid = '0'
      RecService.RestMapplicant.transferToApplicant(p_app).$promise.then(() => {
        SwapLang.getAlert(18).then(function () {
          $scope.removeObject(p_app)
        })
      }, (error) => {
        SwapLang.getAlert(17, error.data.result)
      })
    })
  }

  $scope.goSwitchJob = function (event, app) {
    $mdDialog.show({
      controller: $scope.switchJobCtrl,
      templateUrl: 'DIALOGTEMPLATE/SWITCHJOB.TMPL.html',
      parent: angular.element(document.body),
      targetEvent: event,
      clickOutsideToClose: true,
      locals: {
        candidate: app
      }
    }).then(function ($newJob) {
      //refresh
    })
  }
  $scope.switchJobCtrl = function ($scope, $mdDialog, candidate) {
    $scope.isReady = false
    $scope.newJob = {
      requestid: '',
      jobid: ''
    }
    RecService.RestMrequest.query({funcname: 'getManPowerRequest'}).$promise.then(function (data) {
      $scope.openReqs = data.result.filter((item) => {
        return item.requestStatus === "2"
      })
      $scope.isReady = true
    })
    $scope.candidate = candidate


    $scope.hide = function () {
      $mdDialog.hide();
    };
    $scope.cancel = function () {
      $mdDialog.cancel();
    };
    $scope.save = function () {
      console.log($scope.newJob)
      $scope.candidate.jobid = JSON.parse($scope.newJob).jobid
      $scope.candidate.requestid = JSON.parse($scope.newJob).requestid
      RecService.RestMapplicant.saveJobDropResume($scope.candidate).$promise.then(function () {
        SwapLang.getAlert(18)
      })
    };
  }


  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)
      });
    })
    RecService.RestMdegree.getQuery().$promise.then(function (data) {
      angular.forEach(data.result, function (obj) {
        processSourceSearch(obj)
      });
    })
    RecService.RestMajor.getQuery().$promise.then(function (data) {
      angular.forEach(data.result, function (obj) {
        processSourceSearch(obj)
      });
    })
    RecService.RestMfaculty.getQuery().$promise.then(function (data) {
      angular.forEach(data.result, function (obj) {
        processSourceSearch(obj)
      });
    })
  }

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

    $scope.openPrint = (email, dbname, p_appid) => {
        if (dbname == "STD_NEW") {
            RecService.RestMrequest.query({funcname: 'getManPowerRequest'}).$promise.then(function (data) {
                let res = data.result.find((item) => {
                    return item.jobid === p_appid
                })
                if (res.dayTypeGroup == "01") {

                    let win = window.open(`DropResumePrint.jsp?appid=${p_appid}&email=${email}`, '', 'width = 1366, height = 700')
                } else if(res.dayTypeGroup == "02") {
                    let win = window.open(`DropResumePrint_Monthly.jsp?appid=${p_appid}&email=${email}`, '', 'width = 1366, height = 700')
                }
            })
        }
        //let win = window.open(`ApplicantPrint_APF_Monthly_NEW.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
        //let win = window.open(`ApplicantPrint_ITALTHAI.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    }

  $scope.delete = (p_app) => {
    SwapLang.getConfirm(4).then(function () {
      RecService.RestMapplicant.deleteDropResume({email: p_app.email}).$promise.then(() => {
        SwapLang.getAlert(19).then(function () {
          $scope.removeObject(p_app)
        })
      }, (error) => {
        SwapLang.getAlert(7, error.data.result)
      })
    })
  }


  // Jquery Zone
  $('body')
    .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


})