"use strict";

appCore.controller("HeroAddCtrl", ["$state", "$scope", "$http", "$timeout", "$uibModal", "vServices", "filterFilter", function ($state, $scope, $http, $timeout, $uibModal, vServices, filterFilter) {
  $scope.params = $state.params;
  $scope.today = moment().format("DD-MM-YYYY");
  $scope.$root.page.title = "Add Hero";
  $scope.btn = { text: "Add Hero" };
  $scope.designationOptions = [];
  $scope.managerOptions = [];
  $scope.revenueCenters = [];
  $scope.assessmentGroups = [];
  $scope.countryList = [];
  $scope.locationOptions = [
    { value: "Noida-India", label: "Noida-India" },
    { value: "Bangalore-India", label: "Bangalore-India" },
    { value: "Phoenix-USA", label: "Phoenix-USA" },
    { value: "Dallas-USA", label: "Dallas-USA" },
    { value: "Melbourne-Australia", label: "Melbourne-Australia" }
  ];
  $scope.skillsOptions = [];
  // $scope.isAllowToEdit = $scope.$root.gUser.emp_acls.split(',').indexOf('72')>=0 || $scope.$root.gUser.is_admin ?true:false;
  // $scope.isAllowToEdit = $scope.$root.gUser.emp_acls.split(',').indexOf('72')>=0 || $scope.$root.gUser.id==1 ?true:false;
  $scope.userACL = $scope.$root.gUser.emp_acls;
  $scope.isAllowToEdit = ($scope.userACL.includes(",72,") || $scope.userACL.includes(",73,") || $scope.userACL.includes(",74,")) || !$scope.userACL.includes(",27,") ? true : false;
  $scope.isAllowToEditLocation = false;
  // $scope.departmentOptions = [
  //   {value: "", label: "Select"},
  //   {value: "Accounts", label: "Accounts"},
  //   {value: "Admin", label: "Admin"},
  //   {value: "Analyst", label: "Analyst"},
  //   {value: "Development", label: "Development"},
  //   {value: "Design", label: "Design"},
  //   {value: "HR", label: "HR"},
  //   {value: "IT", label: "IT"},
  //   {value: "Operations", label: "Operations"},
  //   {value: "Project Management", label: "Project Management"},
  //   {value: "Quality", label: "Quality"},
  //   {value: "Software Testing", label: "Software Testing"},
  //   {value: "Sales & Marketing", label: "Sales & Marketing"},
  //   {value: "Technical", label: "Technical"},
  // ];
  $scope.departmentOptions = [];
  $scope.gstatus = [{ label: "Active", value: "active" }, { label: "Inactive", value: "inactive" }];
  $scope.hero = {
    emp_nick_name: "",
    emp_first_name: "",
    emp_middle_name: "",
    emp_last_name: "",
    emp_code: null,
    emp_doj: $scope.today,
    emp_dob: $scope.today,
    emp_country: '1',
    emp_email: "",
    emp_mobile: "",
    emp_marital_status: "",
    emp_location: "Noida-India",
    emp_designation: 0,
    // emp_department: $scope.departmentOptions[0].value,
    emp_dept: 0,
    emp_gender: "",
    emp_status: "active",
    emp_yoe: 0,
    emp_skype: "",
    emp_skills: [],
    emp_pool: 8,
    emp_lm: 0,
    emp_tag: 0,
    emp_revenue_center: 0,
    emp_ag_id: 1,
    emp_relevant_yoe: 0,
    /*emp_pm: 0,*/
    is_admin: false,
    emp_batch_code: "",
    is_admin_am: false,
    emp_allocation_hours: 10,
    workingtz: 'Asia/Kolkata'
  };
  $scope.selectSkills = [];

  $scope.loadSkills = (query) => {
    let k = $scope.skillsOptions.filter((skill) => {
      return skill.toLowerCase().includes(query);
    });
    if (k.length > 0) {
      return k;
    }
    else {
      return $scope.skillsOptions;
    }

  };

  const forFocus = (d) => $(document).find("#" + d).focus();
  $scope.addHero = () => {
    const mobilePattern = new RegExp("^[0-9()+ -]*$");
    if (!$scope.hero.emp_code || typeof $scope.hero.emp_code === "object") {
      toastr.warning("Please fill code", "Required", { timeOut: 5000 });
      forFocus("emp_code");
      return false;
    }
    if (!$scope.hero.emp_first_name || typeof $scope.hero.emp_first_name === "object") {
      toastr.warning("Please fill first name", "Required", { timeOut: 5000 });
      forFocus("emp_first_name");
      return false;
    }
    if (!$scope.hero.emp_mobile) {
      toastr.warning("Please fill mobile number", "Required", { timeOut: 5000 });
      forFocus("emp_mobile");
      return false;
    }
    if (!mobilePattern.test($scope.hero.emp_mobile)) {
      toastr.warning("Please fill valid mobile number", "Required", { timeOut: 5000 });
      forFocus("emp_mobile");
      return false;
    }
    if (!$scope.hero.emp_email || typeof $scope.hero.emp_email === "object") {
      toastr.warning("Please fill valid email address", "Required", { timeOut: 5000 });
      forFocus("emp_email");
      return false;
    }
    if (!$scope.hero.emp_designation || typeof $scope.hero.emp_designation === "object") {
      toastr.warning("Please select designation", "Required", { timeOut: 5000 });
      forFocus("emp_designation");
      return false;
    }
    if (!$scope.hero.emp_dept || typeof $scope.hero.emp_dept === "object") {
      toastr.warning("Please select department", "Required", { timeOut: 5000 });
      forFocus("emp_department");
      return false;
    }
    try {
      $scope.hero.emp_skills = $scope.selectSkills.map((o) => o.text);
      $scope.hero.emp_skills = $scope.hero.emp_skills.toString();

    } catch (e) {
    }
    $scope.hero.is_admin = $scope.hero.is_admin ? $scope.hero.is_admin.toString() : "false";
    // $scope.hero.emp_code = ($scope.hero.emp_code.toString().indexOf("E-") > -1 ? "" : "E-") + $scope.hero.emp_code;
    $scope.hero.emp_code = $scope.hero.emp_code;
    $scope.hero.is_admin_am = $scope.hero.is_admin_am ? $scope.hero.is_admin_am : false;

    if (!$scope.params.employeeid) {
      vServices.callApi("employee/add", "POST", $scope.hero).then(function (res) {
        if (res) {
          toastr.success(res, "Success!", { timeOut: 5000 });
          $state.go("heroList", {}, { reload: true });
        }
      });
    }
    else {
      vServices.callApi("employee/edit", "PUT", $scope.hero).then(function (res) {
        if (res) {
          toastr.success(res, "Success!", { timeOut: 5000 });
          $scope.$root.updateMenu();
          $state.go("heroList", {}, { reload: true });
        }
      });
    }
  };

  const init = () => {
    vServices.callApi("commonfunc/getCountriesList", "GET", {}).then(function (res) {
      if (res && res.length > 0)
        $scope.countryList = res;
    });
    if ($state.current.name === "editProfile") {
      $scope.params.employeeid = $scope.$root.gUser.id;
      $scope.$root.page.title = "Edit Yourself";
      $scope.btn = { text: "Edit Yourself" };
    }
    else if ($state.current.name === "heroEdit" && $scope.params.employeeid == $scope.$root.gUser.id) {
      $scope.$root.page.title = "Edit Yourself";
      $scope.btn = { text: "Edit Yourself" };
    }
    else if ($state.current.name === "heroEdit") {
      $scope.$root.page.title = "Edit Hero";
      $scope.btn = { text: "Edit Hero" };
    }

    vServices.callApi("department/all", "GET", {}).then((res) => {
      $scope.departmentOptions = res;
    });

    vServices.callApi("designation/all", "GET", {}).then((res) => {
      if (res && res.length > 0) {
        $scope.designationOptions = res;
        $scope.designationOptions.unshift({ "id": 0, "desg_name": "Select", "desg_description": null });
      }
      vServices.callApi("employee/manager/all", "GET", {}).then((res) => {
        if (res && res.length > 0) {
          $scope.managerOptions = res;
          $scope.managerOptions.unshift({ "employeeid": 0, "emp_first_name": "Select", "emp_last_name": "" });
        }
        if ($scope.params.employeeid) {
          $scope.btn = { text: "Edit Hero" };
          vServices.callApi("employee/" + $scope.params.employeeid, "GET", {}).then((res) => {
            if (res) {
              $scope.hero = res;
              $scope.hero.emp_code = $scope.hero.emp_code.split("-")[$scope.hero.emp_code.split("-").length - 1];
              $scope.hero.emp_code = parseFloat($scope.hero.emp_code);
              $scope.hero.emp_doj = moment($scope.hero.emp_doj, "YYYY-MM-DD").format("DD-MM-YYYY");
              $scope.hero.emp_dob = $scope.hero.emp_dob ? moment($scope.hero.emp_dob).format("DD-MM-YYYY") : moment().format("DD-MM-YYYY");
              //$scope.hero.emp_lm = $scope.hero.emp_lm ? $scope.hero.emp_lm : $scope.managerOptions[0].employeeid;
              //$scope.hero.emp_pm = $scope.hero.emp_pm ? $scope.hero.emp_pm : $scope.managerOptions[0].employeeid;
              if ($scope.isAllowToEdit) {
                // $scope.isAllowToEditLocation = ($scope.hero.emp_country == $scope.$root.gUser.emp_country) || $scope.$root.gUser.is_admin ? true : false;
                var isInd = $scope.userACL.includes(",72,") && $scope.hero.emp_country == 1 ? true : false;
                var isAus = $scope.userACL.includes(",73,") && $scope.hero.emp_country == 2 ? true : false;
                var isUsa = $scope.userACL.includes(",74,") && $scope.hero.emp_country == 3 ? true : false;
                var isClearedCountry = (isInd || isAus || isUsa) ? true : false;
                $scope.isAllowToEditLocation = isClearedCountry || $scope.emp_acls.includes(",27,") ? true : false;
              }
              for (let i = 0; i < $scope.managerOptions.length; i++) {
                if ($scope.hero.emp_lm && $scope.managerOptions[i].employeeid === $scope.hero.emp_lm) {
                  $scope.hero.emp_lm = $scope.managerOptions[i].employeeid;
                }
                if ($scope.hero.emp_tag && $scope.managerOptions[i].employeeid === $scope.hero.emp_tag) {
                  $scope.hero.emp_tag = $scope.managerOptions[i].employeeid;
                }
                /*if ($scope.hero.emp_pm && $scope.managerOptions[i].employeeid === $scope.hero.emp_pm) {
                  $scope.hero.emp_pm = $scope.managerOptions[i].employeeid;
                }*/

                if (i === $scope.managerOptions.length - 1) {
                  $scope.hero.emp_lm = $scope.hero.emp_lm ? $scope.hero.emp_lm : $scope.managerOptions[0].employeeid;
                  $scope.hero.emp_tag = $scope.hero.emp_tag ? $scope.hero.emp_tag : $scope.managerOptions[0].employeeid;
                  // $scope.hero.emp_pm = $scope.hero.emp_pm ? $scope.hero.emp_pm : $scope.managerOptions[0].employeeid;
                }
              }

              // for (let i = 0; i < $scope.departmentOptions.length; i++) {
              //   if ($scope.departmentOptions[i].dept_name === $scope.hero.emp_dept) {
              //     $scope.hero.emp_dept = $scope.departmentOptions[i].id;
              //   }
              // }

              for (let i = 0; i < $scope.designationOptions.length; i++) {
                if ($scope.designationOptions[i].desg_name === $scope.hero.emp_designation) {
                  $scope.hero.emp_designation = $scope.designationOptions[i].id;
                }
              }
              if ($scope.hero.emp_skills) {
                var skillSet = [];
                var splitSkills = [];
                // $scope.selectSkills = $scope.hero.emp_skills.indexOf(",") > -1 ? $scope.hero.emp_skills.split(",").map(o => { o = {text: o}; }) : [{text: $scope.hero.emp_skills}];
                if ($scope.hero.emp_skills.indexOf(",") > -1) {
                  splitSkills = $scope.hero.emp_skills.split(",");
                  splitSkills.forEach(i => {
                    skillSet.push({ text: i });
                  });
                  $scope.selectSkills = skillSet;
                }

              }
            }

          });
        }
        else {
          $scope.hero.emp_designation = $scope.designationOptions[0].id;
        }

      });
    });
    vServices.callApi("employee/allSkills", "GET", {}).then((res) => {
      if (res && res.length > 0) $scope.skillsOptions = res.map((o) => o.skl_name);
    });
    vServices.callApi("/account/all_revenue_centers", "GET", {}).then(function (res) {
      if (res && res.length > 0) $scope.revenueCenters = res;
    });
    vServices.callApi("/employee/allAssessmentGroups", "GET", {}).then(function (res) {
      if (res && res.length > 0) $scope.assessmentGroups = res;
    });
    $scope.emp_location = $scope.locationOptions[0].value;
    $scope.emp_status = $scope.gstatus[0].value;
    // $scope.emp_department = $scope.departmentOptions[4].dept_name;
  };
  init();

  $scope.openHeroProjectModel = (obj) => {
    vServices.callApi("allocation/listbyempid/" + obj.employeeid, "GET", {}).then(function (projects) {
      // projects.forEach(i=>{
      //   if(i.projectid != 116){
      //     i.proj_name = i.proj_name;
      //     i.projectid = i.projectid;
      //   }
      // });
      console.log(projects);
      if (!projects) {
        $scope.addHero();
      } else if (projects.length == 1) {
        $scope.addHero();
      } else {
        let modalInstance = $uibModal.open({
          animation: true,
          ariaLabelledBy: "modal-title",
          ariaDescribedBy: "modal-body",
          templateUrl: "HeroProject.html",
          controller: "HeroProjectCtrl",
          controllerAs: "$scope",
          size: "md",//sm md lg
          backdrop: "static",
          resolve: {
            data: () => {
              return {
                hero: obj,
                projects: projects
              };
            }
          }
        });
      }

    });
  };
  /* Model code end*/

}]).controller("HeroProjectCtrl", function ($uibModalInstance, data, $scope) {
  $scope.data = data;
  $scope.delHero = (d) => $uibModalInstance.close(d.hero);
  $scope.cancel = () => $uibModalInstance.dismiss("cancel");
});

