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

angular.module('RECRUIT').controller('FormApplicant', 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: ''
        },
        degree: '',
        faculty: '',
        major: ''
      },
      sort: '',
      orderBy: ''
    }
    $('input[name="dateFilter"]').val('')
  }
  $scope.goPages = (appid) => {
    cscForm.action = "FillFormApplicant.jsp"
    cscForm.__applicantid.value = appid
    // 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.transferToCandidate = (p_app) => {
    SwapLang.getConfirm(249).then(function () {
      RecService.RestMapplicant.candidate({appid: p_app.applicantid}).$promise.then(() => {
        SwapLang.getAlert(18).then(function () {
          $scope.removeObject(p_app)
        })
      }, (error) => {
        SwapLang.getAlert(17, error.data.result)
      })
    })
  }

  $scope.disapprove = (p_app) => {
    SwapLang.getConfirm(4).then(function () {
      RecService.RestMapplicant.disApprove({appid: p_app.applicantid}).$promise.then(() => {
        SwapLang.getAlert(19).then(function () {
          $scope.removeObject(p_app)
        })
      }, (error) => {
        SwapLang.getAlert(7, error.data.result)
      })
    })
  }

  $scope.toggleLeft = buildToggler('left');
  function buildToggler(componentId) {
    return function () {
      $mdSidenav(componentId).toggle();
    };
  }

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

  $scope.checkRouting = (p_router) => {
    let result = false
    let beforeState = p_router.filter((p_obj) => {
      return (p_obj.step == 1 && p_obj.status == 0) || (p_obj.step == 2 && (p_obj.status == 0 || p_obj.status == -10 || p_obj.status == 10))
    })

    if (beforeState.length == 0) {
      result = true
    }

    return result
  }

  $scope.checkExamination = () => {
    let result = false
    let routeobj = $scope.applicant.router.find((route) => route.step === 2)

    if (routeobj != undefined) {
      result = true
    }

    return result
  }


  $scope.updateStateRouter = (p_app, p_status) => {
    return $q((resolve, reject) => {
      p_app.jobrouter[p_app.jobrouter.findIndex((p_obj) => {
        return p_obj.step == 3
      })].status = p_status
      resolve(p_app)
    })
  }

  $scope.openPrint = (p_appid, p_dbname, P_jobid) => {
    if (p_dbname == "APF") {
      RecService.RestMrequest.query({funcname: 'getManPowerRequest'}).$promise.then(function (data) {
        let res = data.result.find((item) => {
          return item.jobid === P_jobid
        })
        if (res.dayTypeGroup == "APF01") {
          let win = window.open(`ApplicantPrint_APF_Daily_NEW.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
        } else if (res.dayTypeGroup == "APF02") {
          let win = window.open(`ApplicantPrint_APF_Monthly_NEW.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
        }
      })
    }
    if (p_dbname.toUpperCase().includes("WORKPOINT")) {
      window.open(`ApplicantPrint_WORKPOINT.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    } else if (p_dbname.toUpperCase().includes("PLANETCOMM")) {
      window.open(`ApplicantPrint_PLANETCOMM.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    } else if (p_dbname.toUpperCase().includes("ITE")) {
      window.open(`ApplicantPrint_ITALTHAI.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    } else if (p_dbname.toUpperCase().includes("KOKOTEL")) {
      window.open(`ApplicantPrint_KOKOTEL.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    } else if (p_dbname.toUpperCase().includes("CHATRIUM")) {
      window.open(`ApplicantPrint_CHATRIUM.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    } else {
      window.open(`ApplicantPrint.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    }
  }

  $scope.openTest = (p_appid, p_dbname, P_jobid) => {
    
    //let win = window.open(`ApplicantPrint.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    //let win = window.open(`ApplicantFormPrint.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    //let win = window.open(`ApplicantPrintDHAS.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    //let win = window.open(`ApplicantPrint_APF_Daily_NEW.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    //let win = window.open(`ApplicantPrint_APF_Monthly_NEW.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')

	let win = window.open(`ApplicantTest_ITALTHAI.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')

  
  }
  //End Function Zone


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


  RecService.RestMapplicant.getQuery().$promise.then(function (data) {
    $scope.applicants = data.result
    $scope.isReady = true
  })


  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.goSetCommittee = (applicantid) => {
    cscForm.action = "CommitteeSetupForm.jsp"
    cscForm.__applicantid.value = applicantid
    cscForm.submit()
  }
  // 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


})