import { Component, OnInit } from '@angular/core';
import { Platform, Events, MenuController } from '@ionic/angular';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';
import { AuthenticatedUser } from 'src/app/hmg-common/services/authentication/models/authenticated-user';
import { SharedDataService } from 'src/app/hmg-common/services/shared-data-service/shared-data.service';
import { MowadhafiService } from '../mowadhafi.service';
import { Location } from '@angular/common';
import { MenuResponse } from 'src/app/hmg-common/services/menu/models/menu-response';
import { LoginModel } from 'src/app/authentication/models/LoginModel';
import { SendActivationByType } from 'src/app/authentication/models/sendActivationByType';
import { FileUploader } from 'ng2-file-upload';
@Component({
  selector: 'app-hr-request-form',
  templateUrl: './hr-request-form.component.html',
  styleUrls: ['./hr-request-form.component.scss'],
})
export class HrRequestFormComponent implements OnInit {
  public EmpName: string;
  public EmpNum: string;
  public EmpGroup: string;
  public EmpMobile: string;
  public EmpJob: string;
  public EmpOrgName: string;
  public EmpPayrol: string;
  public EmpPosition: string;
  public EmpEmail: string;
  public EmpCatMeaning: string;
  public EmpGRADENAME: string;
  public EmpLocation: string;
  public EmpImg: string;
  public userImage: any = '../assets/imgs/profile.png';
  public loginData = new LoginModel();
  public searchKeySelect = 'Complaints';
  myColor: string = 'secondary';
  public showRequestDetails = false;
  public proID = "CS"
  public inquiry: string;
  public HR: string;
  public complaints: string;
  public Projectresult: any;
  public EmpRelations: any;
  public Hr: any;
  public Payroll: any;
  public GovRelation: any;
  public projName: any;
  public topicName: any;
  public departTypeList: any;
  public topicTypeList: any;
  public sectionTypeList: any;
  public projectDetial: any;
  public projectDep: any;
  public sectionDep: any;
  public projectCode;
  public SelectedServiceType: any;
  public depType: any ="";
  public secType: any ="";
  public topicType: any ="";
  indexLastObj: any;
  addAttachRequest: any = [];
  TransactionID: any;
  public teckitDetial: any;
  public teckitInfo: any;
  public Description: any;
  public selectedFile: any;
  filterAllowedType: any = [
    "application/pdf",
    "image/jpeg",
    "image/png",
    "text/plain",
    "image/jpg",
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  ];
  projctid:any;
  employeeNumber:any;
 ticketType: any =[];
  public direction: string;
  HRServices = '';
  Complaints='';
  Inquiry='';
  input = document.getElementById ("firstLabel");
  
 
 
  constructor(
    public ts: TranslatorService,
    public cs: CommonService,
    public authService: AuthenticationService,
    public sharedData: SharedDataService,
    public events: Events,
    public MowadhafiService: MowadhafiService,
    private location: Location,
    private menu: MenuController,


  ) {
    this.direction = TranslatorService.getCurrentLanguageName();
  }

  ngOnInit() {
    this.projectCode = this.cs.sharedService.getSharedData("projcet-code",false);
    this.getTicketTypes();
    this.getProject();

   
  }

  
  public isValidForm(): boolean {
    if (this.depType && this.SelectedServiceType && this.secType && this.topicType) {
        return false;
    }
    return true;
}


  onSelectChange(event, type) {
    const value = event.target.value;
    console.log(value);
    // this.topicTypeList =[];
    // this.sectionTypeList =[];
    if(type==1){
      this.depType = value;
      this.sectionTypeList =[];
      this.topicTypeList =[];
      this.getDepartmentSections(value);
     
    }else if(type==2){
      this.getSectionTopics(value);
       this.topicTypeList =[];
    }
    
 }

  onFileSelectedclick(event){
    event.target.value = '';
  }



  goback() {
    this.location.back();

  }

  showSelectedField() { }

  getTicketTypes() {
    const request = {
      EmployeeNumber: "",

    };
    this.MowadhafiService.getTicketTypes(request, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.handlegetTicketTypesResult(result);

    })
  }
  handlegetTicketTypesResult(result) {
    this.ticketType =result.Mohemm_Itg_TicketTypesList;
  
  }

  /////////////////////////////////////////////////

  getProject() {
    const request = {
      EmployeeNumber: "",
      ItgProjectCode: this.projectCode

    };
    this.MowadhafiService.getProject(request, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.handlegetProjectResult(result);

    })
  }
  handlegetProjectResult(result) {
    this.Projectresult = result.Mohemm_Itg_ProjectsList;
    this.projctid=this.Projectresult[0].projectId;
    this.getProjectDepartments();
  }

////////////////////////////////////////////////////
  getProjectDepartments() {
    const request = {
      EmployeeNumber: "",
      ItgProjectId: this.Projectresult[0].projectId,


    };
    this.MowadhafiService.getProjectDepartments(request, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.handlegetProjectDepartmentsResult(result);

    })
  }
  handlegetProjectDepartmentsResult(result) {
    this.departTypeList = result.Mohemm_ITG_ProjectDepartmentsList;
    //  this.getDepartmentSections();

  }
  //////////////////////////////////////////////////////

  getDepartmentSections(value) {
    const request = {
      EmployeeNumber: "",
      ItgProjectDepartmentId: value ?value : this.departTypeList.projectDepartmentId,


    };
    this.MowadhafiService.getDepartmentSections(request, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.handlegetDepartmentSectionsResult(result);

    })
  }
  handlegetDepartmentSectionsResult(result) {
    this.sectionTypeList = result.Mohemm_ITG_DepartmentSectionsList;
    //  this.getSectionTopics();
  }

  getSectionTopics(value=null) {
    const request = {
      EmployeeNumber: "",
      // ItgDepartmentSectionId: this.sectionTypeList.departmentSectionId,
      ItgDepartmentSectionId: value ?value : this.sectionTypeList.departmentSectionId,

    };
    this.MowadhafiService.getSectionTopics(request, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.handlegetSectionTopicsResult(result);

    })
  }
  handlegetSectionTopicsResult(result) {
    // this.topicName=result.Mohemm_ITG_SectionTopicsList[0].topicName
    this.topicTypeList = result.Mohemm_ITG_SectionTopicsList;


  }


 /*******************Create Ticket Function*************/

  CreateTicket() {
   
    var authUser =this.authService.getAuthenticatedRequest();
    this.cs.startLoading();
    var request = new FormData();
    request.append('ticketTypeId', this.SelectedServiceType);
    request.append('projectId', this.projctid);
    request.append('departmentId', this.depType);
    request.append('sectionId', this.secType);
    request.append('sectionTopicId', this.topicType);
    request.append('description', this.Description);
    console.log("TEST:______")
    console.log(this.selectedFile);
    if(this.selectedFile && this.selectedFile !== undefined){
      request.append('fileColl', this.selectedFile[0], this.selectedFile[0].name);
    }
    request.append('employeeNumber', authUser.P_USER_NAME);
    request.append('ticketStatus', 'new');
    request.append('channelId', '3');
    request.append('Channel', authUser.Channel.toString());
    request.append('LogInToken', authUser.LogInTokenID);
    request.append('Token', authUser.TokenID);
    request.append('EmployeeNumber', authUser.P_USER_NAME);
    request.append('MobileNo', authUser.MobileNumber);


    this.MowadhafiService.getCreateTicket(request, () => { }, this.ts.trPK('general', 'retry')).subscribe((result: any) => {
      if(this.cs.validResponse(result)){
        this.cs.stopLoading();
        this.checkERM('After Service Submission');
        this.cs.greenToastPK("general", "success-create");
        this.cs.openMyRequestPage();
      }else{
        this.cs.stopLoading();
        this.cs.redToastPK("general", "try-again");
      }


    })
  }





  public cancelRequest() {
    this.cs.openMyRequestPage();
    // this.menu.toggle();
  }


  /*******************Add attchement Functions*************/
  public uploader: FileUploader = new FileUploader({
    allowedMimeType: [
      "application/pdf",
      "image/jpeg",
      "image/png",
      "text/plain",
      "image/jpg",
      "application/vnd.ms-excel",
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    ],
    maxFileSize: 10 * 1024 * 1024,
    formatDataFunctionIsAsync: true,
    formatDataFunction: async item => {
      return new Promise((resolve, reject) => {
        resolve({
          name: item._file.name,
          length: item._file.size,
          contentType: item._file.type,
          date: new Date()
        });
      });
    }
  });




  onFileSelected(input) {
    if (!(this.filterAllowedType.indexOf(input.target.files[0].type) > -1)) {
      let msg: string = "";
      msg = this.ts.trPK("general", "noFileSelect");
      this.cs.presentAlert(msg);
      return;
    } // todo: show alert that you tried uploading wrong files
    else {
      const file = input.target.files[0];
      this.selectedFile = input.target.files;
     

      this.getBase64(file).then(data =>
        this.pushObject(data, file.name, file.type)
      );
    }
  }


  getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  pushObject(fileData, name, type) {
   
    this.indexLastObj++;
    try {
      let array = name.split(".");
      let attachType: string = array[array.length - 1];

      this.addAttachRequest.push({
        AttachmentID: this.indexLastObj,
        P_FILE_CONTENT_TYPE: attachType, //type.split('/')[1],
        P_FILE_DATA: fileData.split(",")[1],
        P_FILE_NAME: name, //.split('.')[0],
        P_TRANSACTION_ID: this.TransactionID
      });
    } catch (e) { }
  }

  removeFile(objectitem) {
    let objIndex1 = this.uploader.queue.findIndex(item => item == objectitem);
    this.uploader.queue.splice(objIndex1, 1);
    let objIndex = this.addAttachRequest.findIndex(
      item => item.AttachmentID == objectitem.AttachmentID
    );
    this.addAttachRequest.splice(objIndex, 1);
  }


  submitRequest() {

  }


  checkERM(status) {

    this.authService.checkAds({
      EmployeeNumber: '',
      ItgEnableAt: status, //After Service Submission
      ItgServiceName: "Ticket"
    }, () => { }, this.ts.trPK('general', 'ok')).subscribe(res => {

      var result = JSON.parse(res.Mohemm_ITG_ResponseItem).result.data;

      this.cs.sharedService.setSharedData(
        result,
        AuthenticationService.SERVEY_DATA
      )
      if (!CommonService.SKIP && result) {
        if (result.notificationType == 'Survey') {
          this.cs.navigateForward('/erm-channel/survey');
        } else {
          this.authService.adsDetails({
            "ItgNotificationMasterId": result['notificationMasterId']
          },
            () => { }, this.ts.trPK('general', 'ok')
          ).subscribe((result) => {
            var data = result.Mohemm_ITG_ResponseItem;
            if (data) {
              this.cs.sharedService.setSharedData(
                JSON.parse(data),
                AuthenticationService.ADS_DATA
              );
              this.cs.navigateForward('/erm-channel/home');
            }

          })
        }
      }
    })

  }

}
