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

angular.module('RECRUIT').controller('FillFormApplicant', function ($scope, $mdDialog, RecService, SwapLang, $filter, $timeout) {
  $scope.isReady = false
  $scope.clsFormApplicant = new FormApplicant()
  $scope.lang = getLang()
  $scope.swaplang = new swaplang();
  $scope.HrSwlang = SwapLang
  let cscForm = document.cscform
  $scope.tabNames = {
    personal: $scope.swaplang.swap2String('SW012958'),
    contact: $scope.swaplang.swap2String('SW012959'),
    family: $scope.swaplang.swap2String('SW012960'),
    education: $scope.swaplang.swap2String('SW001796'),
    jobexp: $scope.swaplang.swap2String('SW012961'),
    skills: $scope.swaplang.swap2String('SW012962'),
    other: $scope.swaplang.swap2String('SW002113'),
    files: $scope.swaplang.swap2String('SW000682')
  }
  $scope.enableValidate = true;
  $scope.action = 'fillform';
  $scope.selectIndex = 0;
  $scope.reqid = '';
  $scope.jobid = '';
  $scope.internal = '';
  $scope.confApp = {};
  $scope.masterdata = {
    zipcode: [],
    gender: [{
      genderid: '1',
      name: {
        tha: 'ชาย',
        eng: 'Male'
      }
    }, {
      genderid: '2',
      name: {
        tha: 'หญิง',
        eng: 'Female'
      }
    }, {
      genderid: '3',
      name: {
        tha: 'ไม่ระบุเพศ',
        eng: 'Not define'
      }
    }],
    status: [{
      id: '1',
      desc: {
        tha: 'มีชีวิต',
        eng: 'Alive'
      }
    }, {
      id: '2',
      desc: {
        tha: 'ถึงแก่กรรม',
        eng: 'Dead'
      }
    }, {
      id: '3',
      desc: {
        tha: 'สูญหาย',
        eng: 'Lost'
      }
    }],
    maritalStatus: [{
      id: '1',
      value: 'S',
      desc: {
        tha: 'โสด',
        eng: 'Single'
      }
    }, {
      id: '2',
      value: 'M',
      desc: {
        tha: 'สมรส',
        eng: 'Married'
      }
    }, {
      id: '3',
      value: 'D',
      desc: {
        tha: 'หย่าร้าง',
        eng: 'Divorce'
      }
    }, {
      id: '4',
      value: 'W',
      desc: {
        tha: 'หม้าย',
        eng: 'Widow'
      }
    }, {
      id: '5',
      value: 'E',
      desc: {
        tha: 'แยกกันอยู่',
        eng: 'Separated'
      }
    }, {
      id: '6',
      value: 'N',
      desc: {
        tha: 'หมั้นแล้ว',
        eng: 'Engaged'
      }
    }],
    country: [
      {
        countryid: '1',
        name: {
          tha: 'ประเทศทดสอบ1',
          eng: 'testCountry1'
        }
      },
      {
        countryid: '2',
        name: {
          tha: 'ประเทศทดสอบ2',
          eng: 'testCountry2'
        }
      }
    ],
    honors: [
      {
        id: '1',
        name: {
          tha: 'เกียรตินิยมอันดับหนึ่งเหรียญทอง',
          eng: 'First-class honors, Gold Medal'
        }
      },
      {
        id: '2',
        name: {
          tha: 'เกียรตินิยมอันดับหนึ่ง',
          eng: 'First-class honors'
        }
      },
      {
        id: '3',
        name: {
          tha: 'เกียรตินิยมอันดับสอง',
          eng: 'Second-class honors'
        }
      }
    ],
    relations: [{
      id: '1',
      name: {
        tha: 'คู่สมรส',
        eng: 'Spouse'
      }
    }, {
      id: '2',
      name: {
        tha: 'พ่อ',
        eng: 'Father'
      }
    }, {
      id: '3',
      name: {
        tha: 'แม่',
        eng: 'Mother'
      }
    }, {
      id: '4',
      name: {
        tha: 'พี่ชาย',
        eng: 'Older Brother'
      }
    }, {
      id: '5',
      name: {
        tha: 'น้องชาย',
        eng: 'Younger Brother'
      }
    }, {
      id: '6',
      name: {
        tha: 'พี่สาว',
        eng: 'Older Sister'
      }
    }, {
      id: '7',
      name: {
        tha: 'น้องสาว',
        eng: 'Younger Sister'
      }
    }, {
      id: '8',
      name: {
        tha: 'บุตร',
        eng: 'Child'
      }
    }],
    bloodgroup: [{
      id: 'Z',
      name: {
        tha: 'ไม่ระบุ',
        eng: 'Not specify'
      }
    }, {
      id: 'A',
      name: {
        tha: 'เอ',
        eng: 'A'
      }
    }, {
      id: 'B',
      name: {
        tha: 'บี',
        eng: 'B'
      }
    }, {
      id: 'O',
      name: {
        tha: 'โอ',
        eng: 'O'
      }
    }, {
      id: 'AB',
      name: {
        tha: 'เอบี',
        eng: 'AB'
      }
    }]
  }
  //Get Config Resume
  RecService.ManageConfig.query({cname: "RESUME"}).$promise.then(function (data) {
    $scope.confApp = data.result.object;
  })
  // Get Prefix
  RecService.PrefixController.query().$promise.then(function (data) {
    $scope.masterdata.prefix = data.prefix
  })
  // Get Degree
  RecService.DegreeController.query().$promise.then(function (data) {
    $scope.masterdata.degree = data.edu
  })
  // Get Faculty
  RecService.FacultyController.query().$promise.then(function (data) {
    $scope.masterdata.faculty = data.faculty
  });
  // Get Skill level
  RecService.LangSkillLevelController.query().$promise.then(function (data) {
    $scope.masterdata.skilllevel = data.skilllevel
  })
  // Get Race
  RecService.RaceController.query().$promise.then(function (data) {
    $scope.masterdata.race = data.race
  })
  // Get Nationality
  RecService.NationalityController.query().$promise.then(function (data) {
    $scope.masterdata.nationality = data.nationality
  })
  // Get Religion
  RecService.ReligionController.query().$promise.then(function (data) {
    $scope.masterdata.religion = data.religion
  })
  // Get Job
  RecService.JobController.query({jobid: 0}).$promise.then(function (data) {
    $scope.masterdata.job = data.job
  })
  // Get Branch
  RecService.BranchController.query().$promise.then(function (data) {
    $scope.masterdata.branch = data.result
  })
  // Get Country
  RecService.RestMcountry.getQuery().$promise.then(function (data) {
    $scope.masterdata.country = data.mcountry
  })
  // Get Institute
  RecService.RestMinstitute.getQuery().$promise.then(function (data) {
    $scope.masterdata.institute = data.minstitute
  })
  // Get Major
  RecService.RestMmajor.getQuery().$promise.then(function (data) {
    $scope.masterdata.major = data.mmajor
  })
  //Get District
  RecService.GetDistrict.getQuery().$promise.then(function (data) {
    $scope.masterdata.district = data.district
  })
  //Get Province
  RecService.getMProvince.getQuery().$promise.then(function (data) {
    $scope.masterdata.province = data.mprovince
  })
  //Get Sourcejob
  RecService.RestMsourceJob.getQuery().$promise.then(function (data) {
    $scope.masterdata.sourcejob = data.msourcejob
  })
  //Get Language
  RecService.RestMlanguage.getQuery().$promise.then(function (data) {
    $scope.masterdata.language = data.result
  })
  //Get Occupation
  RecService.RestMoccupation.getQuery().$promise.then(function (data) {
    $scope.masterdata.occupation = data.result
  })
  //Get Relations
  RecService.RestMrelation.getQuery().$promise.then(function (data) {
    $scope.masterdata.relations = data.result
  })
  //Get Relations
  RecService.RestMpaperList.getQuery().$promise.then(function (data) {
    $scope.masterdata.paper = data.result
  })



  $scope.monthName = [{
    id: 1,
    full: {
      tha: 'มกราคม',
      eng: 'January'
    }, sub: {
      tha: 'ม.ค',
      eng: 'Jan'
    }
  }, {
    id: 2,
    full: {
      tha: 'กุมภาพันธ์',
      eng: 'February'
    }, sub: {
      tha: 'ก.พ',
      eng: 'Feb'
    }
  }, {
    id: 3,
    full: {
      tha: 'มีนาคม',
      eng: 'March'
    }, sub: {
      tha: 'มี.ค',
      eng: 'Mar'
    }
  }, {
    id: 4,
    full: {
      tha: 'เมษายน',
      eng: 'April'
    }, sub: {
      tha: 'เม.ย',
      eng: 'Apr'
    }
  }, {
    id: 5,
    full: {
      tha: 'พฤษภาคม',
      eng: 'May'
    }, sub: {
      tha: 'พ.ค',
      eng: 'May'
    }
  }, {
    id: 6,
    full: {
      tha: 'มิถุนายน',
      eng: 'June'
    }, sub: {
      tha: 'มิ.ย',
      eng: 'Jun'
    }
  }, {
    id: 7,
    full: {
      tha: 'กรกฏาคม',
      eng: 'July'
    }, sub: {
      tha: 'ก.ค',
      eng: 'Jul'
    }
  }, {
    id: 8,
    full: {
      tha: 'สิงหาคม',
      eng: 'August'
    }, sub: {
      tha: 'ส.ค',
      eng: 'Aug'
    }
  }, {
    id: 9,
    full: {
      tha: 'กันยายน',
      eng: 'September'
    }, sub: {
      tha: 'ก.ย',
      eng: 'Sep'
    }
  }, {
    id: 10,
    full: {
      tha: 'ตุลาคม',
      eng: 'October'
    }, sub: {
      tha: 'ต.ค',
      eng: 'Oct'
    }
  }, {
    id: 11,
    full: {
      tha: 'พฤศจิกายน',
      eng: 'November'
    }, sub: {
      tha: 'พ.ย',
      eng: 'Nov'
    }
  }, {
    id: 12,
    full: {
      tha: 'ธันวาคม',
      eng: 'December'
    }, sub: {
      tha: 'ธ.ค',
      eng: 'Dec'
    }
  }]

  $scope.query = (data) => {
    data.result.personal.birthdate = new Date(data.result.personal.birthdate)
    data.result.personal.dateavailable = new Date(data.result.personal.dateavailable)
    data.result.personal.identification.pinstart = new Date(data.result.personal.identification.pinstart)
    data.result.personal.identification.pinend = new Date(data.result.personal.identification.pinend)
    data.result.personal.sso.pinstart = new Date(data.result.personal.sso.pinstart)
    data.result.personal.sso.pinend = new Date(data.result.personal.sso.pinend)

    data.result.skill.vehicle.car.issuedDate = new Date(data.result.skill.vehicle.car.issuedDate)
    data.result.skill.vehicle.car.expiryDate = new Date(data.result.skill.vehicle.car.issuedDate)
    data.result.skill.vehicle.motorcycle.issuedDate = new Date(data.result.skill.vehicle.car.issuedDate)
    data.result.skill.vehicle.motorcycle.expiryDate = new Date(data.result.skill.vehicle.car.issuedDate)




    let prom = []
    data.result.skill.activity.forEach((obj) => {
      prom.push(obj.start = new Date(obj.start))
      prom.push(obj.end = new Date(obj.end))
    })
    data.result.jobexp.job.forEach((p_obj) => {
      prom.push(p_obj.start = new Date(p_obj.start))
      prom.push(p_obj.end = new Date(p_obj.end))
    })
    data.result.jobexp.training.forEach((p_obj) => {
      prom.push(p_obj.start = new Date(p_obj.start))
      prom.push(p_obj.end = new Date(p_obj.end))
    })


    Promise.all(prom).then(() => {
      $timeout(function () {
        // angular.merge($scope.clsFormApplicant.formApplicant, data.result)
        $scope.clsFormApplicant.formApplicant = data.result
        if ($scope.internal) {
          $scope.clsFormApplicant.formApplicant.jobid = $scope.jobid
          $scope.clsFormApplicant.formApplicant.internal = '1'
        }
        $scope.isReady = true
      }, 1000)

    })
    // $scope.enableValidate = false;
  }
  $scope.queryCandidate = function (candidateid) {
    RecService.RestMcandidate.getQuery({id: candidateid}).$promise.then(function (data) {
      $scope.query(data)
    })
  }
  $scope.queryApplicant = function (appid) {
    RecService.RestMapplicant.getQuery({appid: appid}).$promise.then(function (data) {
      $scope.query(data)
    })
  }
  $scope.queryInternal = ($employeeid) => {
    RecService.RestMemployee.getDataForApplicant({id: $employeeid}).$promise.then(function (data) {
      $scope.query(data)
    })

  }

  // $scope.saveApplicant = function () {
  //   $scope.HrSwlang.getConfirm(1).then(function () {
  //     RecService.RestMapplicant.save($scope.clsFormApplicant.formApplicant).$promise.then(function () {
  //       $scope.HrSwlang.getAlert(18).then(function () {
  //         $scope.clsFormApplicant.init()
  //         window.close()
  //       })
  //     }, function () {
  //       $scope.HrSwlang.getAlert(17)
  //     })
  //   })
  // }

// -----------ตัวก่อนหน้านี้-----------
//
  $scope.saveApplicant = function () {
    if ($scope.cscform.$invalid) {
      return $scope.HrSwlang.getAlert(0)
    }
    $scope.clsFormApplicant.formApplicant.requestid = $scope.reqid
    $scope.HrSwlang.getConfirm(1).then(function () {
      RecService.RestMapplicant.save($scope.clsFormApplicant.formApplicant).$promise.then(function () {
        $scope.HrSwlang.getAlert(18).then(function () {
          $scope.clsFormApplicant.init()
          window.close()
        })
      }, function () {
        $scope.HrSwlang.getAlert(17)
      })
    })
  }


  $scope.approveCandidate = function () {
    $scope.HrSwlang.getConfirm(1).then(function () {
      RecService.RestMapplicant.candidate({appid: $scope.clsFormApplicant.formApplicant.applicantid}).$promise.then(function (data) {
        $scope.HrSwlang.getAlert(18)
      }, function () {
        $scope.HrSwlang.getAlert(17)
      })
    })
  }

  $scope.$watch('clsFormApplicant.formApplicant.jobid', function (jobid) {
    let scope = angular.element($('input[name="__referee1position_desc"]'));
    if (jobid != '') {
      RecService.JobController.query({jobid: `'${jobid}'`}).$promise.then(function (data) {
        if ($scope.lang == 'eng') {
          scope.val(data.job[0].jobdesc_eng)
        } else {
          scope.val(data.job[0].jobdesc_tha)
        }
      })
    } else {
      scope.val('')
    }
  })
  $scope.zipcode = {
    home: [],
    current: []
  };

  $scope.generateZipcodeData = function (objname) {
    // NOTE: generate data in csczipcode
    $scope.clsFormApplicant.formApplicant.contact[objname].autoid = ''
    let zipobj = {
      p_zipcode: $scope.clsFormApplicant.formApplicant.contact[objname]["zipcode"]
    }
    RecService.ZipCodeController.getQuery(zipobj).$promise.then(function (data) {
      $scope.zipcode[objname] = data.csczipcode;
    })
  }
  $scope.viewDistrict = function () {
    $scope.generateZipcodeData('home')
    $scope.generateZipcodeData('current')
  }


  $scope.yearlist = function ($maxyear, $minyear) {
    let arr = []
    let nowdate = new Date()
    for (let i = nowdate.getFullYear() - $minyear; i <= nowdate.getFullYear() + $maxyear; i++) {
      arr.push(i)
    }
    return arr
  }

  $scope.calWorkTime = function (index) {
    // NOTE: for calculator time for Job Experience
    let objjob = $scope.clsFormApplicant.formApplicant.jobexp.job[index]

    if (objjob.start.year != '' && objjob.start.month != '' && objjob.end.year != '' && objjob.end.month != '') {
      let startdate = new Date(objjob.start.year, objjob.start.month, 1, 0, 0, 0) // set string to start date
      let enddate = new Date(objjob.end.year, objjob.end.month, 28, 0, 0, 0) // set string end date
      let timeDiff = enddate.getTime() - startdate.getTime()
      let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24))
      let result = convert2yearmonth(diffDays)
      $scope.clsFormApplicant.formApplicant.jobexp.job[index].totalyear.totalyear = result[0]
      $scope.clsFormApplicant.formApplicant.jobexp.job[index].totalyear.totalmonth = result[1]
    }
  }

  function convert2yearmonth(days) {
    // NOTE: cal year to month
    let year = days / 365
    let remainafterdivyear = days % 365
    let month = remainafterdivyear / 30
    return [Math.floor(year), Math.round(month)]
  }

  function DialogController($scope, $mdDialog, jobRouter) {
    $scope.jobRouter = jobRouter
    $scope.lang = getLang();
    $scope.hide = function () {
      $mdDialog.hide()
    }
    $scope.cancel = function () {
      $mdDialog.cancel()
    }
  }


  $scope.uploadProfile = function (fieldName, type) {
    let param = "/hr/RECRUIT/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) {
    let fileName = cscForm.__picture.value
    if (fileName != "") {
      let param = "/hr/RECRUIT/DELETEFILE.jsp?__fieldName=" + fieldName + "&__fileName=" + fileName + "&__uploadType=PICTURE";
      window.open(param, "", "left=150,top=150,width=600,height=400,toolbar=no,status=yes,scrollbars=yes");
      $scope.clsFormApplicant.formApplicant.personal.imgname = ''
    }
  }
  $scope.uploadAttach = (fieldName) => {
    let param = "/hr/RECRUIT/UPLOADFILE.jsp?__fieldName=" + fieldName + "&__uploadType=DOC";
    window.open(param, "", "left=150,top=150,width=600,height=400,toolbar=no,status=yes,scrollbars=yes");
  }
  $scope.deleteAttach = (file) => {
    let fileName = file.fileName
    if (fileName != "") {
      let param = "/hr/RECRUIT/DELETEFILE.jsp?__fileName=" + fileName + "&__uploadType=DOC";
      window.open(param, "", "left=150,top=150,width=600,height=400,toolbar=no,status=yes,scrollbars=yes");
      file.fileName = ''
    }
  }

  $scope.download = (fileName) => {
    window.open("/hr/VIEW.jsp?type=RECRUIT_UPLOAD&dir=dir&subfolder=DOC&filename="+fileName)
  }

  $scope.addAttachFile = () => {
    let filesCount = $scope.clsFormApplicant.formApplicant.other.files.length
    let isEmpty = filesCount === 0
    if (isEmpty) {
      $scope.clsFormApplicant.addFile()
    } else {
      let lastFileRow = $scope.clsFormApplicant.formApplicant.other.files[filesCount-1]
      let isLastPaperTypeValid = lastFileRow.hasOwnProperty('paperType') && lastFileRow.paperType !== ''
      let isLastFileNameValid = lastFileRow.hasOwnProperty('fileName') && lastFileRow.fileName !== ''
      if (isLastPaperTypeValid && isLastFileNameValid) {
        $scope.clsFormApplicant.addFile()
      }
    }
  }
  $scope.removeAttachFile = (fileName, $index) => {
    if (fileName) {
      let param = "/hr/RECRUIT/DELETEFILE.jsp?__fileName=" + fileName + "&__uploadType=DOC";
      window.open(param, "", "left=150,top=150,width=600,height=400,toolbar=no,status=yes,scrollbars=yes");
    }
    $scope.clsFormApplicant.removeFile($index)
  }

  $scope.showAddressSearch = function (ev, type) {
    $mdDialog.show({
      controller: showAddressSearchCtrl,
      templateUrl: 'DIALOGTEMPLATE/ADDRESS_SEARCH.TMPL.html',
      parent: angular.element(document.body),
      targetEvent: ev,
      clickOutsideToClose: true,
      locals: {
        addressSearch: type
      }
    })
      .then(function (answer) {
        $scope.status = 'You said the information was "' + answer + '".';
      }, function () {
        $scope.status = 'You cancelled the dialog.';
      });
  }
  function showAddressSearchCtrl($scope, $mdDialog, addressSearch) {
    $scope.addressSearch = addressSearch
    $scope.cancel = function () {
      $mdDialog.cancel();
    };
  }


  function getReformatZipcode() {
    let reFormatArray = []
    //Get Zipcode
    if ( $scope.masterdata.zipcode.length === 0) {
      RecService.ZipCodeController.getQuery().$promise.then(function (data) {
        $scope.masterdata.zipcode = data.csczipcode
        angular.forEach($scope.masterdata.zipcode, function (obj) {
          reFormatArray.push({
            label: `${obj.districtName['tha']}(${obj.districtName['eng']}), ${obj.provinceName['tha']}(${obj.provinceName['eng']}) ${obj.zipid}`,
            value: ' ',
            data: obj
          })
        });

      })
    } else {
      angular.forEach($scope.masterdata.zipcode, function (obj) {
        reFormatArray.push({
          label: `${obj.districtName['tha']}(${obj.districtName['eng']}), ${obj.provinceName['tha']}(${obj.provinceName['eng']}) ${obj.zipid}`,
          value: ' ',
          data: obj
        })
      });
    }
    return reFormatArray
  }

  // Jquery
  $('body')
    .on('focus', '.datepicker', function () {
      let datepickerOptions = {
        yearRange: "c-80:c+15",
        changeMonth: true,
        changeYear: true,
        showAnim: 'clip',
        required: true
      }
      $(this).datepicker(datepickerOptions)
        .on('keydown', function (e) {
          e.preventDefault();
        })
    })
    .on('focus', '.autocomplete', function () {
      $(this).autocomplete({
        source: getReformatZipcode(),
        autoFocus: true,
        minLength: 3,
        select: function (event, ui) {
          let addressSearch = $(this).data('addresssearch')
          if (ui.item.data != null) {
            $scope.clsFormApplicant.formApplicant.contact[addressSearch].zipcode = ui.item.data
            $mdDialog.cancel();
          }
        }
      });
    });

  $(window).keydown(function (event) {
    if (event.keyCode == 13) {
      event.preventDefault();
    }
  });


  // End Jquery
})