'use strict'

angular.module('APS_INTERVIEW').controller('InterviewForm', ['$scope', '$http', '$sce', 'InterviewcandidateCtrl', 'RecService', function($scope, $http, $sce, InterviewcandidateCtrl, RecService){
  $scope.candidateid = $('input[name="candidateid"]').val()
  $scope.committeeid = $('input[name="committeeid"]').val()
  $scope.judge = $('input[name="judge"]').val()
  $scope.notedit = ($('input[name="notedit"]').val() == 'true')
  $scope.lang = getLang()
  $scope.candidate = {}
  $scope.hrFullname = ''
  $scope.hrJob = ''
  $scope.contextPath = ''
  $scope.headdata = {
    fullname: '',
    job: '',
    status: 0,
    committee_fullname: '',
    apsdate: '',
    jobrouter: ''
  }
  $scope.formdata = {
    form: '',
    comment: '',
    job_other: '',
    appropriate: '',
    apsdate: '',
    status: 0,
  }
  let question = new Question()
  $scope.examdata = {}
  $scope.score2 = ''
  $scope.score3 = ''
  $scope.score4 = ''
  $scope.score5 = ''

  let DocumentContainer
  let WindowObject

  $scope.comment = [{
    comment:''
  },{
    comment:''
  },{
    comment:''
  }]
  $scope.apsform = [{
    topic : "บุคลิกลักษณะ กิริยามารยาท การแต่งตัว",
    score : 0
  },{
    topic : "มนุษยสัมพัทธ์",
    score : 0
  },{
    topic : "การสื่อข้อความ การตอบคำถาม การใช้คำพูด",
    score : 0
  },{
    topic : "ประวัติการศึกษา และการฝึกอบรม",
    score : 0
  },{
    topic : "ภูมิหลัง และสถามภาพทางครอบครัว",
    score : 0
  },{
    topic : "ประสบการณ์ ลักษณะงานที่ผ่านมา",
    score : 0
  },{
    topic : "ความรอบรู้ในงานที่สมัคร ความรู้ทางเทคนิค และวิธีปฏิบัติ",
    score : 0
  },{
    topic : "ความสามารถพิเศษที่เอื้อต่องานที่สมัคร",
    score : 0
  },{
    topic : "สติปัญญา ความคิด ริเริ่ม ความคิดเห็น หวพริบ การแก้ไขปัญหาเหตุผล",
    score : 0
  },{
    topic : "ทัศนคติความมุ่งหมายในชีวิต การงาน และสังคมรอบข้าง",
    score : 0
  }]
  $scope.myparam = {
    candidateid: $scope.candidateid,
    committeeid: $scope.committeeid,
    judge: $scope.judge
  };

  RecService.RestMcandidate.getQuery({id: $scope.candidateid}).$promise.then(function (data){
    $scope.candidate = data.result;
    if ($scope.candidate.other.hasOwnProperty('apsform')) {
      $scope.formdata = $scope.candidate.other.apsform
    } else {
      $scope.formdata.apsdate = new Date()
    }
    // $scope.headdata.committee_fullname = $scope.hrFullname
    // $scope.headdata.jobrouter = $scope.candidate.jobrouter

    setFormAPS()
    setExamData1()
    setExamScore2()
    setExamScore3()
    setExamScore4()
    setExamScore5()
  })


  // InterviewcandidateCtrl.manageInterviewForm.query($scope.myparam).$promise.then(function(data){
  //   $scope.headdata = data.header
  //   $scope.formdata = data.apsform
  //   setFormAPS()
  //   setExamData1()
  //   setExamScore2()
  //   setExamScore3()
  //   setExamScore4()
  //
  //   console.log(data)
  // })

  let  setExamData1 = () => {
    let data = $scope.candidate.jobrouter
    let router = {}
    let isReady = false

    for(let x=0;x<data.length;x++){
      if(data[x].examdata != null){
        if(data[x].examdata.topic.tha.includes("Personality") ||
            data[x].examdata.topic.eng.includes("Personality")){
          router = data[x]
          isReady = true
        }
      }
    }
    if(isReady){
      $scope.examdata = question.getDHASPIT(router)
    }
  }

  let setExamScore2 = () => {
    let data = $scope.candidate.jobrouter
    let router = {}
    let isReady = false

    for(let x=0;x<data.length;x++){
      if(data[x].examdata != null){
        if(data[x].examdata.topic.tha.includes("ความพร้อมหัวหน้างาน") ||
            data[x].examdata.topic.eng.includes("ความพร้อมหัวหน้างาน")){
          router = data[x]
          isReady = true
        }
      }
    }
    if(isReady){
      $scope.score2 = question.getRealScore(router.question)
    }
  }

  let setExamScore3 = () => {
    let data = $scope.candidate.jobrouter
    let router = {}
    let isReady = false

    for(let x=0;x<data.length;x++){
      if(data[x].examdata != null){
        if(data[x].examdata.topic.tha.includes("ความถนัดเชิงเหตุผลนามธรรม") ||
            data[x].examdata.topic.eng.includes("ความถนัดเชิงเหตุผลนามธรรม")){
          router = data[x]
          isReady = true
        }
      }
    }
    if(isReady){
      $scope.score3 = question.getRealScore(router.question)
    }
  }

  let setExamScore4 = () => {
    let data = $scope.candidate.jobrouter
    let router = {}
    let isReady = false

    for(let x=0;x<data.length;x++){
      if(data[x].examdata != null){
        if(data[x].examdata.topic.tha.includes("ADVANCE ENGLISH") ||
            data[x].examdata.topic.eng.includes("ADVANCE ENGLISH")){
          router = data[x]
          isReady = true
        }
      }
    }
    if(isReady){
      $scope.score4 = question.getRealScore(router.question)
    }
  }

  let setExamScore5 = () => {
    let data = $scope.candidate.jobrouter
    let router = {}
    let isReady = false

    for(let x=0;x<data.length;x++){
      if(data[x].examdata != null){
        if(data[x].examdata.topic.tha.includes("คณิตศาสตร์") ||
            data[x].examdata.topic.eng.includes("คณิตศาสตร์")){
          router = data[x]
          isReady = true
        }
      }
    }
    if(isReady){
      $scope.score5 = question.getRealScore(router.question)
    }
  }


  let setFormAPS = () => {
    if($scope.formdata.form == ''){
      $scope.formdata.form = $scope.apsform
    }
    if($scope.formdata.comment == ''){
      $scope.formdata.comment = $scope.comment
    }
  }

  $scope.getSumScore = () => {
    let result = 0
    if($scope.formdata.form != undefined){
      for(var i = 0; i <$scope.formdata.form.length; i++){
        let form = $scope.formdata.form[i];
        result += parseInt(form.score)
      }
    }
    return result;
  }

  $scope.getSumScoreByScore = (score) => {
    let result = 0
    if($scope.formdata.form != undefined){
      for(var i = 0; i <$scope.formdata.form.length; i++){
        let form = $scope.formdata.form[i];
        if(form.score == score){
          result += parseInt(form.score)
        }
      }
    }
    return result;
  }

  $scope.addComment = () => {
    let data = {
      comment : ''
    }
    $scope.formdata.comment.push(data)
  }
  $scope.delComment = () => {
    $scope.formdata.comment.pop()
  }

  $scope.saveDraff = () => {

    if (confirm(MyCode[1])){
      $scope.formdata.status = 1
      let model = {
        candidateid: $scope.candidate.candidateid,
        apsform: $scope.formdata
      }
      RecService.RestMcandidate.updateApsForm(model).$promise.then(function () {
        alert(MyCode[18]);
        window.opener.location.reload();
      })
    }


    // if (confirm(MyCode[1])){
    //   $scope.sendparam = $scope.sendparam = setParam('0')
    //   InterviewcandidateCtrl.manageInterviewForm.save(JSON.stringify($scope.sendparam))
    //   .$promise.then(function(){
    //     alert(MyCode[18]);
    //     window.opener.location.reload();
    //   });
    // }
  }

  $scope.save = () => {
    if(chkData()){
      if (confirm(MyCode[1])){
        // $scope.sendparam = setParam('1')
        $scope.formdata.status = 2
        let model = {
          candidateid: $scope.candidate.candidateid,
          apsform: $scope.formdata
        }
        RecService.RestMcandidate.updateApsForm(model).$promise.then(function () {
          alert(MyCode[18]);
          window.opener.location.reload();
        })
      }
    }else{
      alert('กรุณากรอกข้อมูลให้ครบถ้วน')
    }
  }

  let setParam = (type) => {
    let param = {
      headdata: $scope.headdata
      ,apsform: $scope.formdata
      ,savetype: type
    }
    return param
  }

  let chkData = () => {
    let result = true
    let objlist = $scope.formdata.form.filter((form) => form.score == 0)
    if (objlist.length>0){
      result = false
    }
    if($scope.formdata.appropriate == '2'){
      if($scope.formdata.job_other == ''){
        result = false
      }
    }else{
      $scope.formdata.job_other = ''
    }
    return result
  }

  $scope.goprint = function(){
    hidelement();
    promisePrint().then((obj) => {
      WindowObject.focus();
      // window.close();
      WindowObject.print();
    })
  }

  function promisePrint(){
    return new Promise((resolve, reject) => {
      DocumentContainer = document.getElementById('target_warpper');
      WindowObject = window.open('', 'PrintWindow', 'width=1200,height=666,top=10,right=10,toolbars=no,scrollbars=yes,status=no,resizable=yes');
      WindowObject.document.writeln('<!DOCTYPE html>');
      WindowObject.document.writeln('<html><head><title></title>');
      WindowObject.document.writeln(`<link rel="stylesheet" type="text/css" href="${$scope.contextPath}/EMPVIEW/css/APP_UP/style_apsup.css">`);
      WindowObject.document.writeln(`<link rel="stylesheet" type="text/css" href="${$scope.contextPath}/EMPVIEW/css/APS_Interview/style_printInterview.css">`);
      WindowObject.document.writeln(`<link rel="stylesheet" type="text/css" href="${$scope.contextPath}/CSS/Bootstrap/css/bootstrap.css">`);
      WindowObject.document.writeln(`<link rel="stylesheet" type="text/css" href="${$scope.contextPath}/CSS/EMPVIEW_LAYOUT.min.css">`);
      WindowObject.document.writeln(`<link rel="stylesheet" type="text/css" href="${$scope.contextPath}/CSS/font-awesome.css">`);
      WindowObject.document.writeln('</head><body>');
      WindowObject.document.writeln(DocumentContainer.innerHTML);
      WindowObject.document.writeln('</body></html>');
      WindowObject.document.close();
      setTimeout(() => resolve(WindowObject), 1000)
    })
  }

  function hidelement(){
    let txt = ''
    let chk = false

    $(".score1").each(function(){
      if($(this).hasClass("ng-hide")){
        $(this).hide()
      }
    });

    $(".score2").each(function(){
      chk = $(this).prop('checked');
      if(chk){
        $(this).parents("td").append("<i class='fa fa-check'></i>");
      }
      $(this).hide();
    });

    if($(".score3_1").prop('checked')){
      $(".score3_1").parents(".form-inline").prepend("<i class='fa fa-check'></i>");
      $(".score3_1").hide()
    }else{
      $(".score3_1").hide()
      $(".label1").hide()
    }

    if($(".score3_2").prop('checked')){
      $(".score3_2").parents(".form-inline").prepend("<i class='fa fa-check'></i>");
      $(".score3_2").hide()
    }else{
      $(".score3_2").hide()
      $(".label2").hide()
    }

    if($(".score3_3").prop('checked')){
      $(".score3_3").parents(".form-inline").prepend("<i class='fa fa-check'></i>");
      $(".score3_3").hide()
      debugger;
      txt = $(".extend3").val()
      $(".extend3").parents(".form-inline").find("#job_other").text(txt)
    }else{
      $(".score3_3").hide()
      $(".label3").hide()
    }
    $(".extend3").removeClass('form-control')
    $(".extend3").hide()


    $("textarea").each(function(){
      txt = $(this).val()
      if(txt ==''){
        $(this).parents(".showtxt").find("p").removeClass('hide')
        $(this).parents(".showtxt").find("p").clone().appendTo($(this).parents(".showtxt"))
      }else{
        $(this).parents(".showtxt").find("p").removeClass('txt-underline hide')
        $(this).parents(".showtxt").find("p").addClass('txt-underline2')
        $(this).parents(".showtxt").find("p").text(txt)
      }
      $(this).hide()
    });

    $('.btn').hide()
    $('.icon-btn').hide()

  }

}]);