<div class="items-container animated fadeIn prevent-select" (window:resize)="onResize()">
  <div id="navigation" class="mb-8">
    <div class="prev-page prevent-select raised-button-background mat-elevation-z8" (click)="goBack(1)" matRipple>
      <mat-icon style="color: white;">arrow_back</mat-icon>
      <div class="page-name ml-4">Planes de mantenimiento correctivo</div>
    </div>
  </div>
  <mat-card class="override-elevation-z8" style="width: 100%; height: 100%;">
    <mat-card-title style="text-align: center; margin: 15px 0;">{{ action }} plan de mantenimiento correctivo</mat-card-title>
    <mat-card-content>
      <div class="form-order-container" *ngIf="isLoading">
        <div class="is-loading animated fadeIn fast">
          <mat-spinner align="center"></mat-spinner>
          <h3>Cargando datos ...</h3>
        </div>
      </div>

      <div class="form-order-container" *ngIf="!isLoading && hasError">
        <div class="has-error animated fadeIn fast">
          <mat-icon class="red_primary_font mb-40" >error</mat-icon>
          <h3>{{ errorStr }}</h3>
        </div>
      </div>

      <div class="form-order-container" *ngIf="!isLoading && !hasError">
        <div class="form-column" [formGroup]="plainFormGroup">
          <div class="form-row mt-4" *ngIf="!isNew">
            <div class="form-cell C03">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>ID plan de mantenimiento</mat-label>
                <input matInput formControlName="idPlanControl">
              </mat-form-field>
            </div>
          </div>
          <div class="section-divider">Configuración del equipamiento</div>
          <div class="form-row">
            <div class="form-cell C06">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Equipamiento involucrado</mat-label>
                <input matInput formControlName="equipmentControl" [matAutocomplete]="autocompleteEquipment" #equipment 
                (blur)="validateEquipment(equipment.value, 'BLU')">
                <mat-autocomplete autoActiveFirstOption #autocompleteEquipment>
                  <mat-option *ngFor="let option of filteredEquipments | async" [value]="option" (onSelectionChange)="validateEquipment($event, 'SEL')">
                    {{ option }}
                  </mat-option>
                </mat-autocomplete>
                <mat-error *ngIf="plainFormGroup.controls['equipmentControl'].hasError('required')">
                  Este campo es obligatorio.
                </mat-error>
              </mat-form-field>
            </div>
            <div class="form-cell C06">
              <mat-progress-bar mode="indeterminate" *ngIf="searchingLRU" class="mb-20 animated fadeIn"></mat-progress-bar>
              <mat-form-field class="w-100 animated fadeIn" appearance="outline" *ngIf="!searchingLRU">
                <mat-label>LRU involucrado</mat-label>
                <input matInput formControlName="lruControl" [matAutocomplete]="autocompleteLRU" #lru 
                (blur)="verifyLRU(lru.value, 'BLU')">
                <mat-autocomplete autoActiveFirstOption #autocompleteLRU>
                  <mat-option *ngFor="let option of filteredLRU | async" [value]="option" (onSelectionChange)="verifyLRU($event, 'SEL')">
                    {{ option }}
                  </mat-option>
                </mat-autocomplete>
              </mat-form-field>
            </div>
          </div>
          <div class="section-divider">Configuración del estado durante la ejecución del plan</div>
          <div class="form-row">
            <div class="form-cell C06">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Estado del funcionamiento del equipamiento</mat-label>
                <mat-select formControlName="equipmentStatusControl">
                  <mat-option value="DE">Detenido</mat-option>
                  <mat-option value="DP" *ngIf="plainFormGroup.controls['lruControl'].value != null && plainFormGroup.controls['lruControl'].value != undefined 
                  && plainFormGroup.controls['lruControl'].value != ''">
                    Detenido parcialmente
                  </mat-option>
                  <mat-option value="EF">No detenido</mat-option>
                </mat-select>
                <mat-error *ngIf="plainFormGroup.controls['equipmentStatusControl'].hasError('required')">
                  Este campo es obligatorio.
                </mat-error>
              </mat-form-field>
            </div>
            <div class="form-cell C06">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Estado del funcionamiento del LRU</mat-label>
                <mat-select formControlName="lruStatusControl" (selectionChange)="lruStatusChange($event)">
                  <mat-option value="DE">Detenido</mat-option>
                  <mat-option value="EF">No detenido</mat-option>
                </mat-select>
              </mat-form-field>
            </div>
          </div>
          <div class="section-divider">Configuración del plan de mantenimiento</div>
          <div class="form-row">
            <div class="form-cell C12">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Descripción de la intervención</mat-label>
                <textarea matInput style="resize: none;" rows="5" formControlName="descriptionControl" 
                (input)="plainFormGroup.controls['descriptionControl'].markAsTouched()"></textarea>
                <mat-error *ngIf="plainFormGroup.controls['descriptionControl'].hasError('required')">
                  Este campo es obligatorio.
                </mat-error>
                <mat-error *ngIf="plainFormGroup.controls['descriptionControl'].hasError('minlength')">
                  Este campo debe contener al menos 15 caracteres.
                </mat-error>
              </mat-form-field>
            </div>
            <div class="form-cell C03">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Tiempo de inmovilización estimado</mat-label>
                <input matInput formControlName="inmTimeControl" #inmTime (input)="validateNumber(inmTime.value, 'INP', 'inmTimeControl')" 
                (blur)="validateNumber(inmTime.value, 'BLU', 'inmTimeControl')">
                <mat-hint>Tiempo expresado en horas*</mat-hint>
                <mat-error *ngIf="plainFormGroup.controls['inmTimeControl'].hasError('required')">
                  Este campo es obligatorio.
                </mat-error>
              </mat-form-field>
            </div>
            <div class="form-cell C03">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Prioridad</mat-label>
                <mat-select formControlName="priorityControl">
                  <mat-option *ngFor="let priority of priorities" [value]="priority.value">
                    <span style="font-weight: 500;" [style.color]="priority.color">
                      {{ priority.label }}
                    </span>
                  </mat-option>
                </mat-select>
                <mat-error *ngIf="plainFormGroup.controls['priorityControl'].hasError('required')">
                  Este campo es obligatorio.
                </mat-error>
                <mat-hint *ngIf="!isNew">{{ activatorLabel }}</mat-hint>
              </mat-form-field>
            </div>
            <div class="form-cell C03">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Duración total de la intervención</mat-label>
                <input matInput formControlName="totalDurationControl" #totalDuration (input)="validateNumber(totalDuration.value, 'INP', 'totalDurationControl')" 
                (blur)="validateNumber(totalDuration.value, 'BLU', 'totalDurationControl')">
                <mat-hint>Tiempo expresado en horas*</mat-hint>
                <mat-error *ngIf="plainFormGroup.controls['totalDurationControl'].hasError('required')">
                  Este campo es obligatorio.
                </mat-error>
              </mat-form-field>
            </div>
            <div class="form-cell C03">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Clasificación</mat-label>
                <input matInput formControlName="classificationControl" [matAutocomplete]="classificationAutocomplete">
                <mat-autocomplete autoActiveFirstOption #classificationAutocomplete>
                  <mat-option *ngFor="let option of filteredClassifications | async" [value]="option">
                    {{ option }}
                  </mat-option>
                </mat-autocomplete>
                <mat-error *ngIf="plainFormGroup.controls['classificationControl'].hasError('required')">
                  Este campo es obligatorio.
                </mat-error>
              </mat-form-field>
            </div>
            <div class="form-cell C06">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>SCADA relacionado</mat-label>
                <mat-select formControlName="scadaControl">
                  <mat-option *ngFor="let scada of scadas" [value]="scada.IDSCADA">
                    {{ scada.NOMBRESCADA }}
                  </mat-option>
                </mat-select>
                <mat-error *ngIf="plainFormGroup.controls['scadaControl'].hasError('required')">
                  Este campo es obligatorio.
                </mat-error>
                <mat-hint *ngIf="!isNew">{{ counterLabel }}</mat-hint>
              </mat-form-field>
            </div>
            <div class="form-cell C06">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Síntoma detonador</mat-label>
                <mat-select formControlName="symptomControl" #symptom>
                  <mat-option *ngFor="let symptom of symptoms" [value]="symptom.ID_SINTOMA">
                    {{ symptom.NOMBRE_SINTOMA }}
                  </mat-option>
                </mat-select>
                <mat-error *ngIf="plainFormGroup.controls['symptomControl'].hasError('required')">
                  Este campo es obligatorio.
                </mat-error>
                <mat-hint align="end" *ngIf="isNew">
                  <a style="color: rgb(35, 95, 172);"  [ngClass]="{ hint_button_disabled: plainFormGroup.controls['symptomControl'].value == '', 
                  hint_button: plainFormGroup.controls['symptomControl'].value != '' }" (click)="openSymptomDetails(symptom.value)">
                    Ver detalles
                  </a>
                </mat-hint>
                <mat-hint *ngIf="!isNew">{{ activatorLabel }}</mat-hint>
              </mat-form-field>
            </div>
            <div class="form-cell C12">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Especialidades requeridas</mat-label>
                <mat-select multiple formControlName="specialtiesControl" #specialtiesC (selectionChange)="updateSpecialtiesTable(specialtiesC.value)">
                  <!--<mat-option *ngFor="let specialty of specialties" [value]="specialty.value" [disabled]="processingSpecialties">
                    {{ specialty.label }}
                  </mat-option>-->
                  <mat-option value="OTR">Otra...</mat-option>
                </mat-select>
                <mat-hint *ngIf="customSpecialties != ''">Otras especialidades: {{ customSpecialties }}</mat-hint>
                <mat-error *ngIf="plainFormGroup.controls['specialtiesControl'].hasError('required')">
                  Este campo es obligatorio.
                </mat-error>
              </mat-form-field>
            </div>
            <div class="form-cell C12">
              <table mat-table [dataSource]="specialtiesDataSource!">
                <ng-container matColumnDef="ESPE">
                  <th mat-header-cell *matHeaderCellDef>Especialidad</th>
                  <td mat-cell *matCellDef="let row">{{ row }}</td>
                </ng-container>

                <ng-container matColumnDef="OPERARIOS">
                  <th mat-header-cell *matHeaderCellDef>Operarios</th>
                  <td mat-cell *matCellDef="let row">
                    <mat-form-field appearance="outline" style="width: 192px;">
                      <button mat-icon-button matPrefix [disabled]="oper.value == '0'" (click)="changeOperators('remove', row)">
                        <mat-icon>remove</mat-icon>
                      </button>
                      <input matInput disabled value="0" [id]="row + '-OPER'" #oper style="text-align: center;">
                      <button mat-icon-button matSuffix (click)="changeOperators('add', row)">
                        <mat-icon>add</mat-icon>
                      </button>
                    </mat-form-field>
                  </td>
                </ng-container>

                <tr mat-header-row *matHeaderRowDef="specialtiesDisplayedColumns"></tr>
                <tr mat-row *matRowDef="let row; columns: specialtiesDisplayedColumns"></tr>
      
                <tr class="mat-row" *matNoDataRow>
                  <td class="mat-cell p-8 centre" colspan="100%">
                    <p style="font-weight: 500;">Aún no se ha seleccionado ninguna especialidad.</p>
                  </td>
                </tr>
              </table>
            </div>
            <div class="form-cell C12">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Comentarios</mat-label>
                <textarea matInput style="resize: none;" rows="5" formControlName="commentsControl"
                (input)="plainFormGroup.controls['commentsControl'].markAsTouched()"></textarea>
                <mat-error *ngIf="plainFormGroup.controls['commentsControl'].hasError('minlength')">
                  Este campo debe contener al menos 15 caracteres.
                </mat-error>
              </mat-form-field>
            </div>
            <div class="form-cell C12">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Refacciones y herramientas necesarias</mat-label>
                <mat-select multiple formControlName="resourcesControl" #resourcesSel (valueChange)="spareAndToolsChange(resourcesSel.value)">
                  <mat-option value="N">--Ninguna--</mat-option>
                  <mat-optgroup label="Refacciones">
                    <mat-option *ngFor="let sparePart of spareParts" [value]="sparePart.ID + '-R'" [disabled]="resourcesSel.value.includes('N')">
                      {{ sparePart.NOMB }} - {{ sparePart.MODE }}
                    </mat-option>
                  </mat-optgroup>
                  <mat-optgroup label="Herramientas">
                    <mat-option *ngFor="let tool of tools" [value]="tool.ID + '-H'" [disabled]="resourcesSel.value.includes('N')">
                      {{ tool.NOMB }} - {{ tool.MODE }}
                    </mat-option>
                  </mat-optgroup>
                </mat-select>
                <mat-error *ngIf="plainFormGroup.controls['resourcesControl'].hasError('required')">
                  Este campo es requerido.
                </mat-error>
              </mat-form-field>
            </div>
            <div class="form-cell C12 mb-20">
              <table mat-table [dataSource]="resourcesDataSource" class="animated fadeIn">
                <ng-container matColumnDef="ID">
                  <th mat-header-cell *matHeaderCellDef>#</th>
                  <td mat-cell *matCellDef="let row">{{ row.ID }}</td>
                </ng-container>
                
                <ng-container matColumnDef="NOMB">
                  <th mat-header-cell *matHeaderCellDef>Nombre</th>
                  <td mat-cell *matCellDef="let row">{{ row.NOMB }}</td>
                </ng-container>
                
                <ng-container matColumnDef="MODE">
                  <th mat-header-cell *matHeaderCellDef>Modelo</th>
                  <td mat-cell *matCellDef="let row">{{ row.MODE }}</td>
                </ng-container>
                
                <ng-container matColumnDef="TYPE">
                  <th mat-header-cell *matHeaderCellDef>Tipo</th>
                  <td mat-cell *matCellDef="let row">{{ row.TYPE }}</td>
                </ng-container>
                
                <ng-container matColumnDef="CANTDISP">
                  <th mat-header-cell *matHeaderCellDef>Cantidad disponible</th>
                  <td mat-cell *matCellDef="let row">{{ row.CANTDISP }} {{ row.UNIT }}(s)</td>
                </ng-container>
                
                <ng-container matColumnDef="CANTREC">
                  <th mat-header-cell *matHeaderCellDef>Cantidad requerida</th>
                  <td mat-cell *matCellDef="let row">
                    <input type="hidden" [id]="'cant-req-' + row.ID" value="1" #cantReq>
                    <div class="required-resource">
                      <button mat-icon-button [disabled]="cantReq.value == '1'" (click)="changeCantReq('remove', row.ID, row.CANTDISP)">
                        <mat-icon>remove</mat-icon>
                      </button>
                      <p matRipple (click)="openSpecificRequiredNumber(row.ID, row.CANTDISP)">{{ cantReq.value }}</p>
                      <button mat-icon-button (click)="changeCantReq('add', row.ID, row.CANTDISP)">
                        <mat-icon>add</mat-icon>
                      </button>
                    </div>
                  </td>
                </ng-container>
                
                <ng-container matColumnDef="CANTREST">
                  <th mat-header-cell *matHeaderCellDef>Cantidad restante</th>
                  <td mat-cell *matCellDef="let row">
                    <input type="hidden" [id]="'cant-rest-' + row.ID" value="1" #cantRest>
                    <p style="font-weight: 500;" [ngClass]="{green_primary_font: intval(cantRest.value) > 0, amber_primary_font: intval(cantRest.value) == 0,
                    red_primary_font: intval(cantRest.value) < 0}">
                      {{ cantRest.value }} {{ row.UNIT }}(s)
                    </p>
                  </td>
                </ng-container>
                  
                <tr mat-header-row *matHeaderRowDef="resourcesDisplayedColumns"></tr>
                <tr mat-row *matRowDef="let row; columns: resourcesDisplayedColumns;"></tr>
        
                <tr class="mat-row" *matNoDataRow>
                  <td class="mat-cell centre" colspan="100%">
                    No se ha seleccionado ninguna herramiento o refacción.
                  </td>
                </tr>
              </table>
            </div>
            <div class="form-cell C12">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Detalles adicionales</mat-label>
                <textarea matInput style="resize: none;" rows="5" formControlName="extraDetailsControl" 
                (input)="plainFormGroup.controls['extraDetailsControl'].markAsTouched()"></textarea>
                <mat-error *ngIf="plainFormGroup.controls['extraDetailsControl'].hasError('minlength')">
                  Este campo debe contener al menos 15 caracteres.
                </mat-error>
              </mat-form-field>
            </div>
          </div>
          <div class="section-divider">Carga de documentación</div>
          <div class="form-row">
            <input type="file" name="file" id="file" #file class="hidden" (change)="checkFile($event, documentType.value)">
            <a target="_blank" id="download"></a>
            <div class="form-cell C06">
              <mat-form-field class="w-100" appearance="outline">
                <mat-label>Tipo de documento</mat-label>
                <mat-select #documentType value="">
                  <mat-option value="">--Seleccionar un tipo--</mat-option>
                  <mat-option value="FSPQ">Ficha de seguridad de productos químicos</mat-option>
                  <mat-option value="FITE">Ficha técnica</mat-option>
                  <mat-option value="FODI">Fotografías o diagramas</mat-option>
                  <mat-option value="DAPR">Datos del proveedor</mat-option>
                  <mat-option value="MAOP">Manual de operación</mat-option>
                  <mat-option value="MMCO">Manual de mantenimiento correctivo</mat-option>
                  <mat-option value="DOAD">Dcoumentos adicionales</mat-option>
                </mat-select>
              </mat-form-field>
            </div>
            <div class="form-cell C06">
              <button mat-stroked-button class="w-100 mb-20 animated fadeIn" [disabled]="documentType.value == ''" (click)="openFileUploader()" 
              *ngIf="!isUploading">
                Agregar archivo
              </button>
              <mat-progress-bar mode="buffer" class="w-100 mb-20 animated fadeIn" *ngIf="isUploading"></mat-progress-bar>
            </div>
            <div class="form-cell C12">
              <table mat-table [dataSource]="relatedDocumentsDataSource!">
                <ng-container matColumnDef="NOMBRE">
                  <th mat-header-cell *matHeaderCellDef>Documento</th>
                  <td mat-cell *matCellDef="let row">{{ row.name }}</td>
                </ng-container>
                
                <ng-container matColumnDef="TIPO">
                  <th mat-header-cell *matHeaderCellDef>Tipo</th>
                  <td mat-cell *matCellDef="let row">{{ row.type }}</td>
                </ng-container>
                
                <ng-container matColumnDef="PESO">
                  <th mat-header-cell *matHeaderCellDef>Tamaño</th>
                  <td mat-cell *matCellDef="let row">{{ row.size }}</td>
                </ng-container>
                
                <ng-container matColumnDef="ACCIONES">
                  <th mat-header-cell *matHeaderCellDef>Acciones</th>
                  <td mat-cell *matCellDef="let row">
                    <button mat-mini-fab class="override_no_shadow mr-4 white_font green_primary_background" [ngClass]="{ green_primary_background: !deleteFilesDisabled }" 
                    (click)="downloadFile(row.id)" [disabled]="deleteFilesDisabled" *ngIf="row.isFinalFile">
                      <mat-icon>download</mat-icon>
                    </button>
                    <button mat-mini-fab color="warn" class="override_no_shadow white_font red_primary_background" (click)="openDeleteFileAlert(row.id)" 
                    [disabled]="deleteFilesDisabled">
                      <mat-icon>delete</mat-icon>
                    </button>
                  </td>
                </ng-container>

                <tr mat-header-row *matHeaderRowDef="relatedDocumentsDisplayedColumns"></tr>
                <tr mat-row *matRowDef="let row; columns: relatedDocumentsDisplayedColumns"></tr>
      
                <tr class="mat-row" *matNoDataRow>
                  <td class="mat-cell p-8 centre" colspan="100%">
                    <p style="font-weight: 500;">Aún no se ha adjuntado ningún documento.</p>
                  </td>
                </tr>
              </table>
            </div>
          </div>
        </div>
      </div>
    </mat-card-content>
    <mat-card-actions align="end">
      <button mat-button (click)="saveMaintenancePlan()">
        Guardar plan de mantenimiento
      </button>
    </mat-card-actions>
  </mat-card>
</div>