import { Component, ElementRef, EventEmitter, Input, Output, signal, ViewChild } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicDataService } from '../../../services/basic.service';
import { CommonNzModule } from './../../../common.nz.module';
import { ApiService } from './../../../services/api.service';
import { AccidentModalComponent } from './accident-modal/accident-modal.component';
import { LeftPanelTopComponent } from './left-panel-top/left-panel-top.component';
import { MainMetroComponent } from './main-metro/main-metro.component';
import { RightPanelComponent } from './right-panel/right-panel.component';

@Component({
  selector: 'datav-digital-line',
  standalone: true,
  imports: [CommonNzModule, RightPanelComponent, LeftPanelTopComponent, MainMetroComponent],
  templateUrl: './digital-line.component.html',
  styleUrl: './digital-line.component.less',
})
export class DigitalLineComponent {
  @ViewChild(MainMetroComponent) metroRef!: ElementRef<MainMetroComponent>;

  @Output() serverTimeChange = new EventEmitter<string>();

  @Input() serverTime = '';
  currentLine = signal<number | null>(null);
  continueDays = signal<number>(0);
  zoom = 1;
  fixedWidth = 680;

  // accidentModal

  data?: Datav.BoardInfo;
  loading = false;

  constructor(
    private basic: BasicDataService,
    private modal: NzModalService,
    private api: ApiService
  ) {
    basic.$fetched.subscribe(() => {
      this.init();
    });
  }
  ngOnInit() {
    this.init();
  }
  init() {
    const airportLineId = this.basic.lines.find(line => line.value === '机场联络线')?.id;
    const firstLineId = this.basic.lines[0]?.id;
    if (airportLineId) {
      this.currentLine.set(airportLineId);
    } else if (firstLineId) {
      this.currentLine.set(firstLineId);
    }
    this.fetchBoardInfo();
  }
  fetchBoardInfo() {
    if (this.loading) return;
    this.loading = true;
    const lineId = this.currentLine();
    if (!lineId) {
      this.loading = false;
      return;
    }
    this.api.datav
      .getBoardInfo(lineId)
      .then(res => {
        this.continueDays.set(res.consecutiveSafeDays);
        this.serverTimeChange.emit(res.currentDate);
        this.data = res;
      })
      .finally(() => {
        this.loading = false;
      });
  }
  ngAfterViewInit() {
    const currentWidth = Math.min(document.body.clientWidth * 0.35417, this.fixedWidth);
    this.zoom = currentWidth / this.fixedWidth;
  }

  onCurrentLineChange(value: number) {
    this.currentLine.set(value);
    this.fetchBoardInfo();
  }

  onAccidentButtonClick() {
    this.modal.create<AccidentModalComponent>({
      nzClassName: 'accident-modal',
      nzMaskClosable: false,
      nzMask: false,
      nzContent: AccidentModalComponent,
      nzWidth: 1100,
      nzFooter: null,
      nzCentered: true,
    });
  }
  get lineName() {
    return this.basic.getLineName(this.currentLine() || 0) || '';
  }
}
