import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { PreventiveMaintenanceService } from 'src/app/services/preventive-maintenance.service';

interface EquipmentInfo{
  CODIGO: string;
  DENOMI: string;
  FAMILI: string;
  SUBFAM: string;
  ESTADO: string;
}
const EQUIPMENT_TMP: EquipmentInfo[] = [
  {
    CODIGO: '01.110.P01-15001.CAM_TCG.CTV.I.HICDE-X3G21-000001',
    DENOMI: 'Hickvision Cámara IP DOMO IR para Exteriores',
    FAMILI: 'Sistema de Telecomunicaciones',
    SUBFAM: 'Videovigilante',
    ESTADO: 'Instalado'
  },
  {
    CODIGO: '01.502.P01-09001.DIS_TN.FRN.I.PAFRE-XXOEM-000001',
    DENOMI: 'Pastillas de Freno',
    FAMILI: 'Tren Nuevo',
    SUBFAM: 'Sistema de Frenos',
    ESTADO: 'Instalado'
  },
  {
    CODIGO: '01.PCC.P01-13001.R42.B4-01_TC.RMS.I.ENCIS-NCC500-000002',
    DENOMI: 'Enrutador CISCO',
    FAMILI: 'Telecomunicaciones',
    SUBFAM: 'Red Multiservicios',
    ESTADO: 'Instalado'
  },
  {
    CODIGO: '01.PCC.P01-13001.R42.H7-06_TC.RMS.I.PAPCI-XXX96F-000001',
    DENOMI: 'Patch Panel Cisco',
    FAMILI: 'Telecomunicaciones',
    SUBFAM: 'Red Multiservicios',
    ESTADO: 'Instalado'
  },
  {
    CODIGO: '01.302.P01-14002.DVR.10,02:315.P01.14002-DVR.16,02_TCG.CTV.T.HICTU-HIM1-000020',
    DENOMI: 'Hickivision DVR de 16 Canales Turbo HD',
    FAMILI: 'Sistema de Telecomunicaciones',
    SUBFAM: 'Videovigilancia',
    ESTADO: 'Traslado'
  },
  {
    CODIGO: '01.110.S01-14001.UDF.17,08:160.UDF.S01-14001.18,08_V1.014.I.CALIG-XGB6KG-000100',
    DENOMI: 'Carril Ligero',
    FAMILI: 'Sistema de Vías',
    SUBFAM: 'Distribución de Durmientes',
    ESTADO: 'Instalado'
  },
  {
    CODIGO: '01.160.S01-03010.VEN.00010:110.P02-03010.VEN.00020_MEP.ACC.I.DUVEN-XXTDC-000002',
    DENOMI: 'Cable de Red',
    FAMILI: 'Telecomunicaciones',
    SUBFAM: 'Red Multiservicios',
    ESTADO: 'Instalado'
  }
];
interface TeamInfo{
  ID: string;
  NOMB: string;
  ESP: string;
}
const TEAMS_TMP: TeamInfo[] = [
  {ID: 'P1', NOMB: 'José Luis Brito Nava', ESP: 'Mécánica'},
  {ID: 'P2', NOMB: 'Jean Jairo Benitez Meza', ESP: 'Electrónica'},
  {ID: 'P3', NOMB: 'José Ángel Herrera', ESP: 'Electricidad'},
  {ID: 'P4', NOMB: 'Omar Antunez Escobar', ESP: 'Neumática'},
  {ID: 'P5', NOMB: 'Edgar Alegría Zarco', ESP: 'Hidráulica'},
  {ID: 'P6', NOMB: 'Fernanda Zavala', ESP: 'Control'},
];
interface ToolInfo{
  ID: string;
  NOMB: string;
  MODE: string;
  CANTDISP: number;
  TYPE: string;
  UNIT: string;
}
const TOOLS_TMP: ToolInfo[] = [
  {ID: 'H1', NOMB: 'Pinzas eléctricas', MODE: 'PE-862', CANTDISP: 35, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H2', NOMB: 'Pinzas mecánicas', MODE: 'M985', CANTDISP: 27, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H3', NOMB: 'Pinzas de presión', MODE: 'RG-12', CANTDISP: 30, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H4', NOMB: 'Juego de llaves Allen', MODE: 'ALL88', CANTDISP: 75, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H5', NOMB: 'Extractor de rodamientos', MODE: 'EX-ROD-1500', CANTDISP: 3, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H6', NOMB: 'Kit llaves inglesas', MODE: '5530S', CANTDISP: 7, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H7', NOMB: 'Kit llaves españolas', MODE: '964F', CANTDISP: 8, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H8', NOMB: 'Juego de llaves Torx', MODE: 'TORX3423W', CANTDISP: 42, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H9', NOMB: 'Cautín de lápiz 33W', MODE: '33WCL', CANTDISP: 15, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H10', NOMB: 'Juego de dados milimétricos', MODE: 'DMM450', CANTDISP: 6, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H11', NOMB: 'Juego de dados pulgadas', MODE: 'DIN865', CANTDISP: 9, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H12', NOMB: 'Probador de corriente', MODE: '569', CANTDISP: 33, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H13', NOMB: 'Multímetro', MODE: 'TGH885', CANTDISP: 17, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H14', NOMB: 'Planta generadora para soldadura', MODE: 'PLAGEN-589', CANTDISP: 1, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H15', NOMB: 'Amperímetro de gancho', MODE: 'A0032', CANTDISP: 4, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H16', NOMB: 'Rotomartillo', MODE: '551', CANTDISP: 2, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H17', NOMB: 'Kit taladro inalámbrico', MODE: 'FP581', CANTDISP: 12, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H18', NOMB: 'Kit taládro alámbrico', MODE: 'HG862', CANTDISP: 10, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H19', NOMB: 'Juego de desarmadores', MODE: '8913-KSOA', CANTDISP: 5, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H20', NOMB: 'Martillo', MODE: 'TS438', CANTDISP: 23, TYPE: 'Herramienta', UNIT: 'Pieza'},
];
const SPARE_PARTS_TMP: ToolInfo[] = [
  {ID: 'S1', NOMB: 'Neumático para NM-16', MODE: 'NM16NEU235', CANTDISP: 45, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S2', NOMB: 'Neumático para NM-22', MODE: 'NM22NEU652', CANTDISP: 51, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S3', NOMB: 'Rodamiento cónico', MODE: 'RC-4265', CANTDISP: 84, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S4', NOMB: 'Rodamiento axial', MODE: 'RA-5130', CANTDISP: 96, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S5', NOMB: 'Rodamiento angular', MODE: 'RN-3541', CANTDISP: 79, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S6', NOMB: 'Grasa 1-310', MODE: 'G1.310', CANTDISP: 9, TYPE: 'Refaccción', UNIT: 'Kilogramo'},
  {ID: 'S7', NOMB: 'Aceite 10W-40', MODE: 'A10W40', CANTDISP: 16, TYPE: 'Refaccción', UNIT: 'Litro'},
  {ID: 'S8', NOMB: 'Soldadura de estaño', MODE: 'LDA-913', CANTDISP: 39, TYPE: 'Refaccción', UNIT: 'Metro'},
  {ID: 'S9', NOMB: 'Soldadura de plata', MODE: 'BDA-516', CANTDISP: 21, TYPE: 'Refaccción', UNIT: 'Metro'},
  {ID: 'S10', NOMB: 'Pastilla de frenado', MODE: '754SSV', CANTDISP: 25, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S11', NOMB: 'Cable de cobre calibre 0', MODE: 'CC0-884', CANTDISP: 120, TYPE: 'Refaccción', UNIT: 'Metro'},
  {ID: 'S12', NOMB: 'Rosetas de cable Ethernet', MODE: '165-BFS', CANTDISP: 12, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S13', NOMB: 'Pintura', MODE: '53469', CANTDISP: 250, TYPE: 'Refaccción', UNIT: 'Litro'},
  {ID: 'S14', NOMB: 'Solvente de pintura', MODE: '2516', CANTDISP: 310, TYPE: 'Refaccción', UNIT: 'Litro'},
  {ID: 'S15', NOMB: 'Lámina galvanizada', MODE: 'SFAS-320', CANTDISP: 38, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S16', NOMB: 'Botón de freno de emergencia', MODE: 'B-51321', CANTDISP: 14, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S17', NOMB: 'Disco duro de estado sólido 512GB', MODE: 'SSD-512', CANTDISP: 22, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S18', NOMB: 'Mouse óptico', MODE: 'MO1165', CANTDISP: 26, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S19', NOMB: 'Teclado para PC', MODE: '5413', CANTDISP: 24, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S20', NOMB: 'Cable HDMI 2m', MODE: 'ASD-181', CANTDISP: 6, TYPE: 'Refaccción', UNIT: 'Pieza'},
];
@Component({
  selector: 'app-new-visit',
  templateUrl: './new-visit.component.html',
  styleUrls: ['./new-visit.component.css']
})
export class NewVisitComponent implements OnInit {
  public btnSmall: boolean;

  equipmentDataSource?: MatTableDataSource<EquipmentInfo>;
  personalDataSource?: MatTableDataSource<any>;
  toolsDataSource?: MatTableDataSource<any>;

  equipmentDisplayedColumns = ['CODIGO', 'DENOMI', 'FAMILI', 'SUBFAM', 'ESTADO', 'ACCIONES'];
  personalDisplayedColumns = ['EMPLEADO', 'ESPECIALIDAD'];
  toolsDisplayedColumns = ['ITEM', 'TIPO', 'CANTDISP', 'CANTNEC', 'CANTRES'];

  equipments: EquipmentInfo[];
  teams: TeamInfo[];
  tools: ToolInfo[];
  toolsParts: ToolInfo[];
  spareParts: ToolInfo[];

  formGroup: FormGroup = new FormGroup({
    equipmentControl: new FormControl('', Validators.required),
    personalControl: new FormControl([], Validators.required),
    toolsControl: new FormControl([], Validators.required),
    sparePartsControl: new FormControl([], Validators.required),
    comments: new FormControl('', [Validators.required, Validators.minLength(35)]),
  });

  isSaving: boolean;

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _snackBar: MatSnackBar,
    private _prevMaintService: PreventiveMaintenanceService,
  ) { 
    this.btnSmall = window.innerWidth <= 1405;
    this.equipments = EQUIPMENT_TMP;
    this.teams = TEAMS_TMP;
    this.tools = TOOLS_TMP;
    this.spareParts = SPARE_PARTS_TMP;
    this.equipmentDataSource = new MatTableDataSource();
    this.personalDataSource = new MatTableDataSource();
    this.toolsDataSource = new MatTableDataSource();
    this.toolsParts = [];
    this.isSaving = false;
  }

  ngOnInit(): void {
  }

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }
  
  goBack(){
    window.history.back();
  }

  changeEquipmentTable(equimpentCode: string){
    let equipment = this.equipments.filter(item => item.CODIGO == equimpentCode);
    this.equipmentDataSource = new MatTableDataSource(equipment);
  }

  changeTeamsTable(teams: string[]){
    let teamsArr: TeamInfo[] = [];
    teams.forEach(item => {
      let team = this.teams.filter(item2 => item2.ID == item)[0];
      teamsArr.push(team);
    });

    this.personalDataSource = new MatTableDataSource(teamsArr);
  }

  toolsChange(toolsValue: string[], partsValue: string[]){
    this.toolsDataSource = new MatTableDataSource();
    this.toolsParts = [];

    let toolsAux: ToolInfo[] = [];
    if(toolsValue != undefined && !toolsValue.includes('SH')){
      toolsValue.forEach(item => {
        let tool = this.tools.filter(item2 => item == item2.ID)[0];
        toolsAux.push(tool);
      });
    }else if(toolsValue.includes('SH')){
      this.formGroup.controls['toolsControl'].setValue(['SH']);
    }

    let partsAux: ToolInfo[] = [];
    if(partsValue != undefined && !partsValue.includes('SH')){
      partsValue.forEach(item => {
        let part = this.spareParts.filter(item2 => item == item2.ID)[0];
        partsAux.push(part);
      });
    }else if(partsValue.includes('SH')){
      this.formGroup.controls['sparePartsControl'].setValue(['SH']);
    }

    toolsAux.forEach(item => this.toolsParts.push(item));
    partsAux.forEach(item => this.toolsParts.push(item));

    this.toolsDataSource = new MatTableDataSource(this.toolsParts);
  }

  changeReq(action: string, id: string){
    let input = this._document.getElementById(`cant-req-${id}`) as HTMLInputElement;
    let val = parseInt(input.value);
    if(action == 'add'){
      val++;
      input.value = `${val}`;
    }else if(val > 1){
      val--;
      input.value = `${val}`;
    }else{
      input.value = '1';
    }
  }

  validateCant(value: string, id: string){
    let input = this._document.getElementById(`cant-req-${id}`) as HTMLInputElement;
    if(value == ""){
      input.value = '1';
    }else if(value == '0'){
      input.value = '1';
    }else{
      let validString = "";
      let valueArr = value.split('');
      let numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

      valueArr.forEach(char => {
        if(numbers.includes(char)){
          validString += char;
        }
      });

      input.value = validString;
    }
  }

  isPositive(calcDisp: string, id: string): boolean{
    let input = this._document.getElementById(`cant-req-${id}`) as HTMLInputElement;
    let cd = parseInt(calcDisp);
    let cr = parseInt(input.value);
    
    return cd - cr > 0;
  }

  calcRest(calcDisp: string, id: string): string{
    let input = this._document.getElementById(`cant-req-${id}`) as HTMLInputElement;
    let cd = parseInt(calcDisp);
    let cr = parseInt(input.value);
    
    return `${cd - cr}`;
  }

  async registerVisit(){
    try{
      this.isSaving = true;

      let formValue = this.formGroup.getRawValue();
      let selectedTools = formValue.toolsControl;
      let selectedSpareParts = formValue.sparePartsControl;
      let toolsConf: any[] = [];
      let validTools = true;

      selectedTools.forEach((item: string) => {
        if(item == 'SH'){
          toolsConf.push({
            ID: 'SH',
            REQ: '-',
            TYPE: 'T'
          });
        }else{
          let input = this._document.getElementById(`cant-req-${item}`) as HTMLInputElement;
          let tool = this.tools.filter(item2 => item2.ID == item)[0];
          if(input.value == ''){
            this.openSnackBar(`La cantidad requerida no se ha configurado para la herramienta ${tool.NOMB}`);

            validTools = false;
          }else{
            toolsConf.push({
              ID: tool.ID,
              REQ: input.value,
              TYPE: 'T'
            });
          }
        }
      });

      selectedSpareParts.forEach((item: string) => {
        if(item == 'SH'){
          toolsConf.push({
            ID: 'SH',
            REQ: '-',
            TYPE: 'S'
          });
        }else{
          let input = this._document.getElementById(`cant-req-${item}`) as HTMLInputElement;
          let part = this.spareParts.filter(item2 => item2.ID == item)[0];
          if(input.value == ''){
            this.openSnackBar(`La cantidad requerida no se ha configurado para la herramienta ${part.NOMB}`);

            validTools = false;
          }else{
            toolsConf.push({
              ID: part.ID,
              REQ: input.value,
              TYPE: 'S'
            });
          }
        }
      });

      if(validTools){
        let formData = new FormData();
        let idUser = localStorage.getItem('idusuario');

        formData.append('id_user', idUser!);
        formData.append('linea', '1');
        formData.append('equipment', formValue.equipmentControl);
        formData.append('teams', JSON.stringify(formValue.personalControl));
        formData.append('resources', JSON.stringify(toolsConf));
        formData.append('comments', formValue.comments);

        await lastValueFrom(this._prevMaintService.newUnprogrammedOrder(formData));

        this.isSaving = false;
        this.openSnackBar('La visita se registró correctamente');
        window.history.back();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
      this.isSaving = false;
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500
    });
  }
}
