import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { ApiService } from './api.service';

@Injectable({
  providedIn: 'root',
})
export class BasicDataService {
  lines: BasicData.Predefine[] = [];
  types: BasicData.Predefine[] = [];
  jobs: BasicData.Job[] = [];
  // units: BasicData.Unit[] = [];
  positions: BasicData.Position[] = [];
  consequences: BasicData.Predefine[] = [];
  equipments: BasicData.Equipment[] = [];
  operations: BasicData.Operation[] = [];
  departments: BasicData.Department[] = [];
  private _initialized = false;
  $fetched = new Subject<void>();
  constructor(private readonly api: ApiService) {}
  async fetchBasicData() {
    return Promise.all([
      this.fetchLines(),
      this.fetchTypes(),
      this.fetchJobs(),
      // this.fetchUnits(),
      this.fetchPositions(),
      this.fetchConsequences(),
      this.fetchEquipments(),
      this.fetchOperations(),
      this.fetchDepartments(),
    ]).then(() => {
      setTimeout(() => {
        this.$fetched.next();
      }, 100);
    });
  }
  // async fetchUnits() {
  //   this.units = await this.api.basic.getUnitList();
  // }
  async fetchPositions() {
    this.positions = await this.api.basic.getPositionList();
  }
  async fetchConsequences() {
    this.consequences = await this.api.basic.getPredefineList('consequence');
  }
  async fetchEquipments() {
    this.equipments = await this.api.basic.getEquipmentList();
  }
  async fetchOperations() {
    this.operations = await this.api.basic.getOperationList();
  }
  async fetchLines() {
    this.lines = await this.api.basic.getPredefineList('line');
  }
  async fetchTypes() {
    this.types = await this.api.basic.getPredefineList('product');
  }
  async fetchJobs() {
    this.jobs = await this.api.basic.getJobList();
  }
  async fetchDepartments() {
    this.departments = await this.api.basic.getDepartmentList();
  }
  clear() {
    this._initialized = false;
    this.lines = [];
    this.types = [];
    this.jobs = [];
    // this.units = [];
    this.positions = [];
    this.consequences = [];
    this.equipments = [];
    this.operations = [];
    this.departments = [];
  }
  refresh() {
    this.fetchBasicData();
  }

  async init(): Promise<boolean> {
    if (this._initialized) {
      return true;
    }
    return this.onInit().catch(err => {
      console.error('init error', err);
      return false;
    });
  }

  getOperationName(operationId: number) {
    return this.operations.find(op => op.id === operationId)?.name;
  }
  // getPositionName(positionId: number) {
  //   return this.units.find(unit => unit.id === positionId)?.name;
  // }
  getPositionName(positionId: number) {
    return this.positions.find(pos => pos.id === positionId)?.name;
  }
  getEquipmentName(equipmentId: number) {
    return this.equipments.find(eq => eq.id === equipmentId)?.name;
  }
  getDepartmentName(departmentId: number) {
    return this.departments.find(eq => eq.id === departmentId)?.name;
  }
  getJobName(jobId: number) {
    const jobDto = this.jobs.find(job => job.id === jobId);
    if (!jobDto) return '';
    const departmentId = jobDto?.department;
    const departmentName = this.getDepartmentName(departmentId);
    if (!departmentName) return jobDto.name;
    return `${jobDto.name}(${departmentName})`;
  }
  getConsequenceName(consequenceId: number) {
    return this.consequences.find(con => con.id === consequenceId)?.value;
  }

  private async onInit() {
    await this.fetchBasicData();
    this._initialized = true;
    return true;
  }
}
