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

angular.module('RECRUIT').controller('Candidate', function ($scope, $mdDialog, RecService, $filter, $timeout, $mdSidenav, SwapLang) {
  $scope.isReady = false
  $scope.showConfirm = false
  $scope.waitToMoveHistory = {}
  $scope.editRemark = []
  $scope.tempEditRemark = ''
  $scope.initCondition = function () {
    $scope.conditions = {
      filter: {
        all: '',
        jobid: '',
        status : {
          qualified : '',
          unqualified : ''
        },
        date: {
          start: '',
          end: ''
        }
      },
      sort: '',
      orderBy: ''
    }
    $('input[name="dateFilter"]').val('')
  }
  $scope.refreshView = () => {
    RecService.RestMcandidate.getQuery().$promise.then(function (data){
      $scope.candidates = data.result;
      $scope.isReady = true
    })
  };
  $scope.select_mstatus = '';
  $scope.change_mstatus = function(p_status, p_candidateid) {
    $scope.up_status = {
      mstatus : p_status,
      candidateid : p_candidateid,
    };
    RecService.RestMcandidate.updateStatus($scope.up_status).$promise.then(function () {});
  };

  $scope.updateRemark = function(remark, candidateid) {
    $scope.editRemark[candidateid] = false
    RecService.RestMcandidate.updateRemark({remark : remark, candidateid : candidateid}).$promise.then(function () {});
  };

  // $scope.cancelUpdateRemark = function(remark, candidateid) {
  //   $scope.editRemark[candidateid].state = false
  //   remark = $scope.editRemark[candidateid].temp
  //
  // };
  //
  // $scope.onEditRemark = (remark, candidateid) => {
  //   $scope.editRemark[candidateid].state = true
  //   $scope.editRemark[candidateid].temp = remark
  //   console.log($scope.editRemark[candidateid].temp)
  // }

    $scope.status = []
    RecService.RestMStatus.getQuery().$promise.then(function (data) {
        $scope.status = data.result
    })



  $scope.initMasterData = function () {
    RecService.ManageConfig.query({cname: 'EMAIL'}).$promise.then(function (data) {
      $scope.emailTemplates = data.result.object.email
    })
    RecService.PrefixController.query().$promise.then(function (data) {
      $scope.prefixs = data.prefix
    })
    $scope.refreshView();
  }
  $scope.initMasterData()
  $scope.swlang = new swaplang()
  let cscForm = document.cscform
  $scope.lang = getLang()
  $scope.initCondition()
  $scope.prefixs = []
  $scope.candidates = []
  $scope.emailTemplates = []








  $scope.transferCtrl = ($scope, candidate, $mdDialog) => {
    $scope.mode = ''
    $scope.candidate = candidate
    $scope.candidate.dateattendance = '';
    RecService.RestMemplSetupEmployee.getQuery().$promise.then((data) => {
      if (data.result[0].mode === 'A') {
        $scope.mode = 'Auto'
        $scope.candidate.employeeid = '0'
      }
      else {
        $scope.mode = 'Manual'
      }
    })

    $scope.hide = function () {
      $mdDialog.hide();
    };
    $scope.cancel = function () {
      $mdDialog.cancel();
    };
    $scope.save = function () {
      if ($scope.formTransfer.$invalid) {
        return alert(MyCode[0])
      } else if ($scope.candidate.employeeid === '0' && $scope.mode === 'Manual') {
        return alert(MyCode[15])
      }
      $mdDialog.hide($scope.candidate);
    };
  }


  $scope.removeObject = (p_candidate) => {
    $scope.candidates.splice($scope.candidates.indexOf(p_candidate), 1)
  }

  $scope.transferToEmployee = (candidate, event) => {
    RecService.ManageRequestForm.getOpeningMrequest({jobid: candidate.jobid}).$promise.then((data) => {
      if (data.requestid) {
        $mdDialog.show({
          controller: $scope.transferCtrl,
          templateUrl: 'DIALOGTEMPLATE/TRANSFER.TMPL.html',
          parent: angular.element(document.body),
          targetEvent: event,
          clickOutsideToClose: true,
          locals: {
            candidate: candidate
          }
        }).then(function (candidate) {
          RecService.RestMcandidate.transferToEmployee(candidate).$promise.then(function () {
            SwapLang.getAlert(18).then(function () {
              $scope.removeObject(candidate)
            })
          }, function (error) {
            SwapLang.getAlert(17, error.data.result)
          })
        })
      }
      else {
        SwapLang.getAlert(6, 'ไม่พบ หรือ สิ้นสุดการเปิดรับสมัครตำแหน่งตำแหน่งดังกล่าว')
      }
    })
  }

  $scope.getPrefix = function (prefixid) {
    let result = ''
    let prefix = $filter('filter')($scope.prefixs, {mprefixid: prefixid}, true)
    if (prefix.length > 0) {
      result = prefix[0][`prefix_${$scope.lang}`]
    }
    return result
  }
  $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.openPrint = (p_appid, p_dbname, P_jobid) => {
    if (p_dbname.toUpperCase().includes("WORKPOINT")) {
      window.open(`CandidatePrint_WORKPOINT.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    } else if (p_dbname.toUpperCase().includes("PLANETCOMM")) {
      window.open(`CandidatePrint_PLANETCOMM.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    } else if (p_dbname.toUpperCase().includes("ITE")) {
      window.open(`CandidatePrint_ITALTHAI.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    } else if (p_dbname.toUpperCase().includes("KOKOTEL")) {
      window.open(`CandidatePrint_KOKOTEL.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    } else if (p_dbname.toUpperCase().includes("CHATRIUM")) {
      window.open(`CandidatePrint_CHATRIUM.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')
    } else if (p_dbname.toUpperCase().includes("DHAS")) {
      window.open(`CandidatePrint_DHAS.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(`CandidateTest_ITALTHAI.jsp?appid=${p_appid}`, '', 'width = 1366, height = 700')

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

  
  $scope.moveToHistory = () => {
    RecService.RestMcandidate.moveToHistory($scope.waitToMoveHistory).$promise.then(($data) => {
      if ($data.result) {
        $scope.showConfirm = false
        $scope.removeObject($scope.waitToMoveHistory)
        $scope.waitToMoveHistory = {}
      }
    })
  }

  $scope.goGenerate = ($candidate) => {
    let employeeid = $candidate.employeeid
    if (employeeid === '0' || !employeeid) {
      return alert('Employee id not found')
    }
    RecService.RestTadjposition.exist({id: employeeid}).$promise.then(($data) => {
      if ($data.result) {
        SwapLang.getConfirm(59).then(() => {
          cscForm.target = "_blank"
          cscForm.action = "PRU102.jsp"
          cscForm.__employeeid.value = employeeid
          cscForm.submit()
          $scope.showConfirm = true
          $scope.waitToMoveHistory = $candidate
        }, (error)=>{

        })
      } else {
        cscForm.target = "_blank"
        cscForm.action = "PRU102.jsp"
        cscForm.__employeeid.value = employeeid
        cscForm.submit()
        $scope.showConfirm = true
        $scope.waitToMoveHistory = $candidate
      }
    }, () => {
      alert('Employee id not found')
    })
  }

  $scope.disapprove = ($candidate, $event) => {

    $mdDialog.show({
      controller: $scope.disapproveCtrl,
      templateUrl: 'DIALOGTEMPLATE/DISAPPROVE.TMPL.html',
      parent: angular.element(document.body),
      targetEvent: $event,
      clickOutsideToClose: true,
      locals: {
        candidate: $candidate
      }
    }).then(function (data) {
      $scope.refreshView();
    })
  }
  $scope.disapproveCtrl = function ($scope, $mdDialog, candidate) {
    $scope.isReady = false
    $scope.candidate = candidate
    $scope.disApprovemodel = {
      candidateid: candidate.candidateid,
      remark: ''
    }

    $scope.hide = function () {
      $mdDialog.hide();
    };
    $scope.cancel = function () {
      $mdDialog.cancel();
    };
    $scope.save = function () {
      RecService.RestMcandidate.disApprove($scope.disApprovemodel).$promise.then(()=> {
        SwapLang.getAlert(18).then(function () {
          let router = $scope.candidate.jobrouter.find((item) => {
            return item.step === 6
          })
          router.status = -1
          $scope.candidate.qualified = false
        })
      }, (error)=>{
        SwapLang.getAlert(5, error.data.result)
      })
    };
  }

  $scope.evaluate = (event, candidate) => {
    // window.open(`EVALUATE_SENA.jsp?candidateid=${candidate.candidateid}`, '', 'width = 1366, height = 700')


    RecService.ManageRequestForm.getOpeningMrequest({jobid: candidate.jobid}).$promise.then((data) => {
      if (data.requestid) {
        $mdDialog.show({
          controller: $scope.evaluateCtrl,
          templateUrl: 'DIALOGTEMPLATE/EVALUATE.TMPL.html',
          parent: angular.element(document.body),
          targetEvent: event,
          clickOutsideToClose: true,
          locals: {
            candidate: candidate
          }
        }).then(function (data) {
          $scope.refreshView();
        })
      }
      else {
        SwapLang.getAlert(6, 'ไม่พบ หรือ สิ้นสุดการเปิดรับสมัครตำแหน่งตำแหน่งดังกล่าว')
      }
    })
  }

  $scope.evaluateCtrl = ($scope, $mdDialog, candidate, RecService) => {
    $scope.candidate = candidate
    $scope.isConfirmDelete = []
    $scope.MyCode = MyCode

    $('body').on('change', '.inputFileName', function () {
      let attrName = $(this).attr('name')
      let splitAttrName = attrName.split('-')
      let employeeid = splitAttrName[2]
      let fileName = $(this).val()
      $scope.$apply(()=>{
        let evaluateItemModel = {
          employeeid: employeeid,
          fileName: fileName
        }
        $scope.candidate.evaluate.push(evaluateItemModel)
        // $scope.saveCandidate($scope.candidate)
      })
    })

    $scope.checkEvaluated = (employeeid)=> {
      return ($filter('filter')($scope.candidate.evaluate, {employeeid:employeeid}, true)).length > 0
    }

    $scope.uploadEvaluate = function (fieldName,type) {
      let param = "UPLOADFILE.jsp?__fieldName=" +fieldName +"&__uploadType="+type;
      window.open(param,"","left=150,top=150,width=600,height=400,toolbar=no,status=yes,scrollbars=yes");
    }

    $scope.deleteFile = function (fieldName, type, employeeid, index) {
      let evaluateItem = $filter('filter')($scope.candidate.evaluate, {employeeid:employeeid}, true)
      let fileName = evaluateItem[0].fileName
      if(fileName !== ""){
        let param = "DELETEFILE.jsp?__fieldName=" +fieldName +"&__fileName=" +fileName +"&__uploadType="+type;
        window.open(param,"","left=150,top=150,width=600,height=400,toolbar=no,status=yes,scrollbars=yes");
        for(let i = 0; i < $scope.candidate.evaluate.length; i++) {
          let obj = $scope.candidate.evaluate[i];
          if(evaluateItem.indexOf(obj) !== -1) {
            $scope.candidate.evaluate.splice(i, 1)
            // $scope.saveCandidate($scope.candidate)
          }
        }
      }
      $scope.isConfirmDelete[index] = false


    }
    $scope.showPDF = (employeeid) => {
      let evaluateItem = $filter('filter')($scope.candidate.evaluate, {employeeid:employeeid}, true)
      if (evaluateItem.length > 0) {
        let fileName = evaluateItem[0].fileName
        window.open("/hr/VIEW.jsp?type=RECRUIT_UPLOAD&dir=dir&subfolder=PDF&filename="+fileName)
      }
    }

    $scope.hide = function () {
      $mdDialog.hide();
    };
    $scope.cancel = function () {
      $mdDialog.cancel();
    };
    $scope.save = function () {
      $scope.saveCandidate($scope.candidate)
      $mdDialog.hide($scope.candidate);
    };

    $scope.saveCandidate = (p_data)=> {
      let indexInterview = p_data.jobrouter.findIndex(((item) => { return item.step === 5}))
      if (indexInterview !== -1) {
        p_data.jobrouter[indexInterview].status = 0
        if (p_data.committee.length === p_data.evaluate.length) {
          p_data.jobrouter[indexInterview].status = 1
        }
      }
      RecService.RestMcandidate.save(p_data)
    }
  }

  $scope.goSwitchJob = function (event, candidate) {
    RecService.ManageRequestForm.getOpeningMrequest({jobid: candidate.jobid}).$promise.then((data) => {
      if (data.requestid) {
        $mdDialog.show({
          controller: $scope.switchJobCtrl,
          templateUrl: 'DIALOGTEMPLATE/SWITCHJOB.TMPL.html',
          parent: angular.element(document.body),
          targetEvent: event,
          clickOutsideToClose: true,
          locals: {
            candidate: candidate,
            requestid : data.requestid
          }
        }).then(function () {
          //refresh
          $scope.refreshView();
        })
      }
      else {
        SwapLang.getAlert(6, 'ไม่พบ หรือ สิ้นสุดการเปิดรับสมัครตำแหน่งตำแหน่งดังกล่าว')
      }
    })
  };

  $scope.switchJobCtrl = function ($scope, $mdDialog, candidate, requestid, $filter) {
    $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 () {
      $scope.candidate.jobid = JSON.parse($scope.newJob).jobid
      $scope.candidate.requestid = JSON.parse($scope.newJob).requestid
      RecService.RestMcandidate.save($scope.candidate).$promise.then(function () {
        SwapLang.getAlert(18)
      })
    };
  }


  $scope.appointmentApplicant = function (event, candidate) {
    RecService.ManageRequestForm.getOpeningMrequest({jobid: candidate.jobid}).$promise.then((data) => {
      if (data.requestid) {
        $mdDialog.show({
          controller: $scope.appointmentCtrl,
          templateUrl: 'DIALOGTEMPLATE/APPOINTMENT.TMPL.html',
          parent: angular.element(document.body),
          targetEvent: event,
          clickOutsideToClose: true,
          locals: {
            emailTemplates: $scope.emailTemplates,
            candidate: candidate,
            prefixs: $scope.prefixs,
            requestid : data.requestid
          }
        }).then(function () {
          //refresh
          $scope.refreshView();
        })
      }
      else {
        SwapLang.getAlert(6, 'ไม่พบ หรือ สิ้นสุดการเปิดรับสมัครตำแหน่งตำแหน่งดังกล่าว')
      }
    })
  };


  $scope.appointmentCtrl = function ($scope, $mdDialog, emailTemplates, candidate, prefixs, requestid, $filter) {
    
   
    $scope.isLoading = false
    $scope.emailExpr = /^.+@myhr.co.th$/
    $scope.job = {}
    RecService.RestMjobcode.getQuery({id:candidate.jobid}).$promise.then(function (data) {
      $scope.job = data.result
    })
    $scope.committees = []
    let param = {
      'canid' : candidate.candidateid,
      'appid' : candidate.applicantid
    }
  
    RecService.ManageCommittee.query(param).$promise.then(function (data) {
      //console.log(data);
      // $scope.committees = data.committee
    })
    $scope.committees = candidate.committee
    $scope.appointment = {
      appointmentid: '0',
      candidateid: candidate.candidateid,
      personal: candidate.personal,
      requestid: requestid,
      jobid: candidate.jobid,
      detail: {
        type: '',
        date: '',
        time: {
          start: '',
          end: ''
        },
        address: '',
        remark: '',
        sendMail: {
          status: '0',
          from: '',
          candidate: [],
          referee: [],
          atAppFile: false
        }
      }
    }
    $scope.fileName = ''
    $scope.fileNames = []
    $scope.swaplang = new swaplang();
    $scope.tabNames = {
      all: $scope.swaplang.swap2String('SW008544'),
      candi: $scope.swaplang.swap2String('SW000139'),
      commi: $scope.swaplang.swap2String('SW004819')
    }
    $scope.prefixs = prefixs
    $scope.lang = getLang();
    $scope.candidateEmailLang = getLang()
    $scope.refereeEmailLang = getLang()
    $scope.candidate = candidate
    $scope.emailTemplates = emailTemplates
    $scope.appointmentType = [
      {
        id: '1',
        desc: {
          tha: 'สอบสัมภาษณ์',
          eng: 'Interview'
        }
      },
      {
        id: '2',
        desc: {
          tha: 'สอบข้อเขียน',
          eng: 'Examination'
        }
      }
    ]
    $('body').on('change', '.inputMailFile', function () {
      let fileName = $(this).val()
      $scope.$apply(()=>{
        // $scope.fileName = fileName
        $scope.fileNames.push(fileName)
      })
    })
    $scope.upload = function (fieldName) {
      let param = "UPLOADFILE.jsp?__fieldName=" +fieldName ;
      window.open(param,"","left=150,top=150,width=600,height=400,toolbar=no,status=yes,scrollbars=yes");
    }
    $scope.deleteFile = function (fieldName) {
      // let fileName = $scope.fileName
      let fileNames = $scope.fileNames

      // if(fileName !== ""){
      //   let param = "DELETEFILE.jsp?__fieldName=" +fieldName +"&__fileName=" +fileName;
      //   window.open(param,"","left=150,top=150,width=600,height=400,toolbar=no,status=yes,scrollbars=yes");
      //   $scope.fileName = ''
      // }

      if(fileNames.length > 0){
        fileNames.forEach(($fileName) => {
          let param = "DELETEFILE.jsp?__fieldName=" +fieldName +"&__fileName=" + $fileName;
          window.open(param,"","left=150,top=150,width=600,height=400,toolbar=no,status=yes,scrollbars=yes");
        })
        $scope.fileNames = []
      }
    }
    $scope.getAllRefereeEmail = function () {
      let email = ''
      $scope.committees.forEach((ref) => {
        email += `${ref.email},`
      })
      return email.substring(0, email.length - 1)
    }
    $scope.hide = function () {
      $mdDialog.hide();
    };
    $scope.cancel = function () {
      $mdDialog.cancel();
    };
    $scope.save = function () {
      if ($scope.formAppointment.$invalid) {
        return alert(MyCode[0])
      }
      let originalAppointment = angular.copy($scope.appointment)
      let tempMail = angular.copy($scope.appointment.detail.sendMail)
      let objSendMail = tempMail

      objSendMail.allMail = objSendMail.candidate.concat(objSendMail.referee)
      objSendMail.allMail.forEach((mail) => {
        mail.content = `<pre>${mail.content}</pre>`
        if (objSendMail.from !== '') {
          mail.from = objSendMail.from
        }
        if ($scope.fileNames.length > 0) {
          let uploadDir = $('input[name="__uploadDir"]').val()
          // mail.atfile = uploadDir + $scope.fileName
          mail.atfiles = $scope.fileNames.map(($fileName) => {
            return uploadDir + $fileName
          })
          // mail.clearAtFile = true
        }
        mail.atAppFile = objSendMail.atAppFile
      })
      $scope.appointment.detail.sendMail = tempMail
      let dataToSave = angular.copy($scope.appointment)
      $scope.appointment = originalAppointment
      $scope.isLoading = true
      RecService.RestMappointment.save(dataToSave).$promise.then(function () {
        SwapLang.getAlert(18)
      }, (error) => {
        alert(error.data.result)
        $scope.isLoading = false
        //SwapLang.getAlert(17, error.data.result)
      })
    };

    $scope.bindEmailVar = function (mailContent, lang, index) {

      let newMailContent = mailContent

      function getCommiPrefix() {
        let result = ''
        if (index === -1) {
          let allPrefix = ''
          $scope.committees.forEach((com) => {
            allPrefix += `${findObjWithAttr($scope.prefixs, 'mprefixid', com.prefixid)[`prefix_${lang}`]}, `
          })
          result = allPrefix.substring(0, allPrefix.length - 2)
        }
        else {
          result = findObjWithAttr($scope.prefixs, 'mprefixid', $scope.committees[index].prefixid)[`prefix_${lang}`]
        }
        return result
      }

      function getCommiFname() {
        let result = ''
        if (index === -1) {
          let allFname = ''
          $scope.committees.forEach((com) => {
            allFname += `${com.fname[lang]}, `
          })
          result = allFname.substring(0, allFname.length - 2)
        }
        else {
          result = $scope.committees[index].fname[lang]
        }
        return result
      }

      function getCommiLname() {
        let result = ''
        if (index === -1) {
          let allLname = ''
          $scope.committees.forEach((com) => {
            allLname += `${com.lname[lang]}, `
          })
          result = allLname.substring(0, allLname.length - 2)
        }
        else {
          result = $scope.committees[index].lname[lang]
        }
        return result
      }

      function getCommiFullname(pre, fname, lname) {
        let result = ''
        let arrPre = pre.split(', ')
        let arrFname = fname.split(', ')
        let arrLname = lname.split(', ')
        if (index === -1) {
          let allFullname = ''
          arrPre.forEach((com, index) => {
            allFullname += `${arrPre[index]}${arrFname[index]}  ${arrLname[index]}, `
          })
          result = allFullname.substring(0, allFullname.length - 2)
        }
        else {
          result = `${arrPre[index]}${arrFname[index]}  ${arrLname[index]}`
        }
        return result
      }

      function getCommiPreFname(pre, fname) {
        let result = ''
        let arrPre = pre.split(', ')
        let arrFname = fname.split(', ')
        if (index === -1) {
          let allString = ''
          arrPre.forEach((com, index) => {
            allString += `${arrPre[index]}  ${arrFname[index]}, `
          })
          result = allString.substring(0, allString.length - 2)
        }
        else {
          result = `${arrPre[index]}  ${arrFname[index]}`
        }
        return result
      }

      function getCommiPreLname(pre, lname) {
        let result = ''
        let arrPre = pre.split(', ')
        let arrLname = lname.split(', ')
        if (index === -1) {
          let allString = ''
          arrPre.forEach((com, index) => {
            allString += `${arrPre[index]}  ${arrLname[index]}, `
          })
          result = allString.substring(0, allString.length - 2)
        }
        else {
          result = `${arrPre[index]}  ${arrLname[index]}`
        }
        return result
      }

      function getCommiFnameLname(fname, lname) {
        let result = ''
        let arrFname = fname.split(', ')
        let arrLname = lname.split(', ')
        if (index === -1) {
          let allFullname = ''
          arrFname.forEach((com, index) => {
            allFullname += `${arrFname[index]}  ${arrLname[index]}, `
          })
          result = allFullname.substring(0, allFullname.length - 2)
        }
        else {
          result = `${arrFname[index]}  ${arrLname[index]}`
        }
        return result
      }



      function getAppointmentDay() {
        let result = ''
        if ($scope.appointment.detail.date) {
          result = $filter('date')($scope.appointment.detail.date, 'd')
        }
        return result
      }

      function getAppointmentMonth() {
        let result = ''
        if ($scope.appointment.detail.date) {
          if (lang === 'eng') {
            result = monthFullName[$filter('date')($scope.appointment.detail.date, 'M')-1]
          }
          else if(lang === 'tha') {
            result = monthFullNameTh[$filter('date')($scope.appointment.detail.date, 'M')-1]
          }
        }
        return result
      }

      function getAppointmentYear() {
        let result = ''
        if ($scope.appointment.detail.date) {
          if (lang === 'eng') {
            result = $filter('date')($scope.appointment.detail.date, 'yyyy')
          }
          else if(lang === 'tha') {
            result = (parseInt($filter('date')($scope.appointment.detail.date, 'yyyy')) + 543).toString()
          }
        }
        return result
      }


      let candi = {
        prefix: findObjWithAttr($scope.prefixs, 'mprefixid', $scope.candidate.personal.prefixid)[`prefix_${lang}`],
        fname: $scope.candidate.personal.fname[lang],
        lname: $scope.candidate.personal.lname[lang],
      }
      let commi = {
        prefix: getCommiPrefix(),
        fname: getCommiFname(),
        lname: getCommiLname(),
      }
      let key = {
        job: '${JOB}',
        date: {
          day:'${DAY}',
          month:'${MONTH}',
          year:'${YEAR}'
        },
        time: {
          start: '${TIMESTART}',
          end: '${TIMEEND}'
        },
        place:'${PLACE}',
        candi: {
          id: '${CID}',
          prefix: '${CPREFIX}',
          fname: '${CFNAME}',
          lname: '${CLNAME}',
          preFname: '${CPREFIX+CFNAME}',
          preLname: '${CPREFIX+CLNAME}',
          fnameLname: '${CFNAME+CLNAME}',
          fullname: '${CFULLNAME}',
        },
        commi: {
          prefix: '${CMPREFIX}',
          fname: '${CMFNAME}',
          lname: '${CMLNAME}',
          preFname: '${CMPREFIX+CMFNAME}',
          preLname: '${CMPREFIX+CMLNAME}',
          fnameLname: '${CMFNAME+CMLNAME}',
          fullname: '${CMFULLNAME}'
        }

      }
      let valCandi = {
        id: $scope.candidate.applicantid,
        prefix: candi.prefix,
        fname: candi.fname,
        lname: candi.lname,
        preFname: `${candi.prefix}  ${candi.fname}`,
        preLname: `${candi.prefix}  ${candi.lname}`,
        FnameLname: `${candi.fname}  ${candi.lname}`,
        fullname: `${candi.prefix}${candi.fname}  ${candi.lname}`
      }
      let valCommi = {
        prefix: commi.prefix,
        fname: commi.fname,
        lname: commi.lname,
        preFname: getCommiPreFname(commi.prefix, commi.fname),
        preLname: getCommiPreLname(commi.prefix, commi.lname),
        FnameLname: getCommiFnameLname(commi.fname, commi.lname),
        fullname: getCommiFullname(commi.prefix, commi.fname, commi.lname)
      }
      let keyArr = []
      let cutOpen = mailContent.split('${')
      for (let i = 0; i < cutOpen.length; i++) {
        let cutEnd = cutOpen[i].split('}')
        keyArr.push(cutEnd[0])
      }
      keyArr.forEach((strKey) => {
        let variable = '${' + strKey + '}'
        switch (variable) {
          case key.candi.id :
            newMailContent = newMailContent.replace(key.candi.id, valCandi.id)
            break
          case key.candi.prefix :
            newMailContent = newMailContent.replace(key.candi.prefix, valCandi.prefix)
            break
          case key.candi.fname :
            newMailContent = newMailContent.replace(key.candi.fname, valCandi.fname)
            break
          case key.candi.lname :
            newMailContent = newMailContent.replace(key.candi.lname, valCandi.lname)
            break
          case key.candi.preFname :
            newMailContent = newMailContent.replace(key.candi.preFname, valCandi.preFname)
            break
          case key.candi.preLname :
            newMailContent = newMailContent.replace(key.candi.preLname, valCandi.preLname)
            break
          case key.candi.fnameLname :
            newMailContent = newMailContent.replace(key.candi.fnameLname, valCandi.FnameLname)
            break
          case key.candi.fullname :
            newMailContent = newMailContent.replace(key.candi.fullname, valCandi.fullname)
            break
          case key.commi.prefix :
            newMailContent = newMailContent.replace(key.commi.prefix, valCommi.prefix)
            break
          case key.commi.fname :
            newMailContent = newMailContent.replace(key.commi.fname, valCommi.fname)
            break
          case key.commi.lname :
            newMailContent = newMailContent.replace(key.commi.lname, valCommi.lname)
            break
          case key.commi.preFname :
            newMailContent = newMailContent.replace(key.commi.preFname, valCommi.preFname)
            break
          case key.commi.preLname :
            newMailContent = newMailContent.replace(key.commi.preLname, valCommi.preLname)
            break
          case key.commi.fnameLname :
            newMailContent = newMailContent.replace(key.commi.fnameLname, valCommi.FnameLname)
            break
          case key.commi.fullname :
            newMailContent = newMailContent.replace(key.commi.fullname, valCommi.fullname)
            break
          case key.date.day :
            newMailContent = newMailContent.replace(key.date.day, getAppointmentDay())
            break
          case key.date.month :
            newMailContent = newMailContent.replace(key.date.month, getAppointmentMonth())
            break
          case key.date.year :
            newMailContent = newMailContent.replace(key.date.year, getAppointmentYear())
            break
          case key.time.start :
            newMailContent = newMailContent.replace(key.time.start, $scope.appointment.detail.time.start)
            break
          case key.time.end :
            newMailContent = newMailContent.replace(key.time.end, $scope.appointment.detail.time.end)
            break
          case key.job :
            newMailContent = newMailContent.replace(key.job, $scope.job.name[lang])
            break
          case key.place :
            newMailContent = newMailContent.replace(key.place, $scope.appointment.detail.address)
            break
        }
      })

      return newMailContent
    }
    $scope.isChooseTemplate = {
      candidate: [],
      referee: []
    }
    $scope.selectedTemplate = {
      candidate: [],
      referee: []
    }

    $scope.chooseTemplate = function (who, index, lang) {
      switch (who.toUpperCase()) {
        case 'CANDIDATE' :
          $scope.isChooseTemplate.candidate[index] = !$scope.isChooseTemplate.candidate[index]
          if ($scope.selectedTemplate.candidate[index] && !$scope.isChooseTemplate.candidate[index]) {
            $scope.appointment.detail.sendMail.candidate[index]['content'] = $scope.bindEmailVar(JSON.parse($scope.selectedTemplate.candidate[index]).content[lang], lang, -1)
            $scope.appointment.detail.sendMail.candidate[index]['subject'] = JSON.parse($scope.selectedTemplate.candidate[index]).name
          }
          break;
        case 'REFEREE' :
          $scope.isChooseTemplate.referee[index] = !$scope.isChooseTemplate.referee[index]
          if ($scope.selectedTemplate.referee[index] && !$scope.isChooseTemplate.referee[index]) {
            $scope.appointment.detail.sendMail.referee[index]['content'] = $scope.bindEmailVar(JSON.parse($scope.selectedTemplate.referee[index]).content[lang], lang, -1)
            $scope.appointment.detail.sendMail.referee[index]['subject'] = JSON.parse($scope.selectedTemplate.referee[index]).name
          }
          break;
      }
    }

    $scope.hours = function () {
      let hours = []
      for (let i = 0; i < 24; i++) {
        let hour = i.toString().paddingLeft("00")
        for (let j = 0; j < 60; j += 30) {
          hours.push(hour + '.' + j.toString().paddingLeft("00"))
        }
      }
      return hours
    }
    $scope.endHours = function () {
      let endHours = []
      let splitTime = $scope.appointment.detail.time.start.split('.')
      let startHour = parseInt(splitTime[0])
      let startmin = parseInt(splitTime[1])
      for (let i = startHour; i < 24; i++) {
        let hour = i.toString().paddingLeft("00")
        if (i == startHour) {
          let j
          for (j = startmin += 30; j < 60; j += 30) {
            endHours.push(hour + '.' + j.toString().paddingLeft("00"))
          }
        }
        else {
          for (let j = 0; j < 60; j += 30) {
            endHours.push(hour + '.' + j.toString().paddingLeft("00"))
          }
        }
      }
      return endHours
    }
    String.prototype.paddingLeft = function (paddingValue) {
      return String(paddingValue + this).slice(-paddingValue.length);
    };
  }

  $scope.checkIsEvaluate = (router) => {
    let indexWaitInterview = router.findIndex((item) => { return item.step === 4})
    return indexWaitInterview !== -1
  }
  $scope.checkIsHire = (router) => {
    let allPass = true
    router.forEach((item) => {
      let isIgnoreRouter = item.step === 4 || item.step === 6 || item.step === 7
      if (!(item.status === 1 || item.status === 2) && !isIgnoreRouter) {
        allPass = false
      }
    })
    return allPass
  }

  $scope.defineIndexRouter = function (objRouter) {
    let index = {
      fillForm: null,
      exam: null,
      waitCandidate: null,
      waitInterview: null,
      interview: null,
      waitHiring: null,
      hiring: null
    }
    angular.forEach(objRouter, function (item, i) {
      switch (item.step) {
        case 1 :
          index.fillForm = i
          break;
        case 2 :
          index.exam = i
          break;
        case 3 :
          index.waitCandidate = i
          break;
        case 4 :
          index.waitInterview = i
          break;
        case 5 :
          index.interview = i
          break;
        case 6 :
          index.waitHiring = i
          break;
        case 7 :
          index.hiring = i
          break;
      }
    })
    return index
  }



  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 = (candidateid) => {
    cscForm.action = "CommitteeSetupForm.jsp"
    cscForm.__candidateid.value = candidateid
    cscForm.target = "_blank"
    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

})