import { Component, EventEmitter, Input, Output, TemplateRef, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { horizontalInOut, horizontalInOutReverse } from '../../../../../common.animation';
import { CommonNzModule } from './../../../../../common.nz.module';
import { ApiService } from './../../../../../services/api.service';
import { BasicDataService } from './../../../../../services/basic.service';

@Component({
  selector: 'accident-form',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './accident-form.component.html',
  styleUrl: './accident-form.component.less',
  animations: [horizontalInOut, horizontalInOutReverse],
})
export class AccidentFormComponent {
  @ViewChild('confirmModal') confirmModal!: TemplateRef<void>;
  @Input() action = 'new';
  @Input() data?: Datav.Accident;
  @Output() closeModal = new EventEmitter<void>();
  @Output() reset = new EventEmitter<void>();
  @Output() refresh = new EventEmitter<void>();
  @Output() toRecord = new EventEmitter<void>();
  loading = false;
  confirmModalRef: NzModalRef | null = null;
  scenes: Option<string>[] = [
    { label: '站点', value: 'station' },
    { label: '路线区间', value: 'line' },
    { label: '其他场景', value: 'other' },
  ];
  textAreas = [
    { label: '事故详情描述', name: 'content' },
    { label: '造成后果', name: 'consequence' },
    { label: '处置结果', name: 'disposalResult' },
  ];
  lineOptions: Option<number>[] = [];
  stationOptions: Option<number>[] = [];
  accidentForm = new FormGroup({
    title: new FormControl('', [Validators.required]),
    accidentDate: new FormControl('', [Validators.required]),
    positionType: new FormControl('', [Validators.required]),
    content: new FormControl('', [Validators.required]),
    consequence: new FormControl('', [Validators.required]),
    disposalResult: new FormControl('', [Validators.required]),
    line: new FormControl<number | undefined>(undefined, []),
    position: new FormControl<number | undefined>(undefined, []),
    positionNext: new FormControl<number | undefined>(undefined, []),
    positionOther: new FormControl<string>('', []),
  });

  constructor(
    private basic: BasicDataService,
    private modal: NzModalService,
    private message: NzMessageService,
    private api: ApiService
  ) {}

  ngOnInit() {
    this.init();
  }
  // ngOnChanges(changes: SimpleChanges) {
  //   if (changes['data']) {
  //     if (this.data) {
  //       this.patchForm();
  //       this.resetSceneValidators(this.data.positionType!);
  //       this.onLineChange(this.data.line!);
  //     }
  //   }
  // }
  init() {
    if (this.data) {
      this.patchForm();
      this.resetSceneValidators(this.data.positionType!);
      this.onLineChange(this.data.line!);
    } else {
      this.accidentForm.get('positionType')?.setValue('station');
      this.resetSceneValidators('station');
    }
    this.initLineOptions();
  }
  initLineOptions() {
    this.lineOptions = this.basic.lines.map(item => ({ label: item.value, value: item.id }));
  }
  patchForm() {
    this.accidentForm.patchValue({
      title: this.data?.title,
      accidentDate: this.data?.accidentDate,
      positionType: this.data?.positionType,
      line: this.data?.line,
      position: this.data?.position,
      positionNext: this.data?.positionNext,
      positionOther: this.data?.positionOther,
      content: this.data?.content,
      consequence: this.data?.consequence,
      disposalResult: this.data?.disposalResult,
    });
  }
  onLineChange(value: number) {
    this.stationOptions = this.basic.positions
      .filter(item => item.stationLines.includes(value))
      .map(item => ({ label: item.name, value: item.id }));
  }
  onSceneChange(value: string) {
    if (this.readonly) return;
    this.accidentForm.get('positionType')?.setValue(value);
    this.resetSceneValidators(value);
    this.resetScene();
  }
  resetSceneValidators(value: string) {
    switch (value) {
      case 'station':
        this.line?.setValidators([Validators.required]);
        this.position?.setValidators([Validators.required]);
        this.positionNext?.clearValidators();
        this.positionOther?.clearValidators();
        break;
      case 'line':
        this.line?.setValidators([Validators.required]);
        this.position?.setValidators([Validators.required]);
        this.positionNext?.setValidators([Validators.required]);
        this.positionOther?.clearValidators();
        break;
      case 'other':
        this.line?.clearValidators();
        this.position?.clearValidators();
        this.positionNext?.clearValidators();
        this.positionOther?.setValidators([Validators.required]);
        break;
    }
  }
  resetScene() {
    this.line?.reset();
    this.position?.reset();
    this.positionNext?.reset();
    this.positionOther?.reset();
  }
  onCancel() {
    this.closeModal.emit();
  }
  confirm() {
    this.confirmModalRef = this.modal.confirm({
      nzTitle: '确定要提交吗？',
      nzContent: this.confirmModal,
      nzOkText: null,
      nzCancelText: null,
      nzMask: false,
      nzClassName: 'noop-modal',
      nzCentered: true,
    });
  }
  onCancelConfirm() {
    this.confirmModalRef?.destroy();
  }
  onSubmit() {
    this.confirmModalRef?.destroy();
    if (this.action === 'new') {
      this.onAdd();
    } else if (this.action === 'edit') {
      this.onEdit();
    }
  }

  async onConfirm() {
    if (!this.accidentForm.valid) {
      Object.values(this.accidentForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
      return Promise.reject();
    } else {
      this.confirm();
    }
  }
  async handleSubmit() {
    if (this.action === 'new') {
      await this.onAdd();
    } else if (this.action === 'edit') {
      await this.onEdit();
    }
  }
  getParams(): Omit<Datav.Accident, 'id'> {
    const value = this.accidentForm.value;
    return {
      title: value.title!,
      accidentDate: value.accidentDate!,
      positionType: value.positionType!,
      line: value.line!,
      position: value.position!,
      positionNext: value.positionNext!,
      positionOther: value.positionOther!,
      content: value.content!,
      consequence: value.consequence!,
      disposalResult: value.disposalResult!,
    };
  }
  async onAdd() {
    this.loading = true;
    const res = await this.api.datav.addAccident(this.getParams()).finally(() => {
      this.loading = false;
    });
    this.message.success('添加成功');
    this.reset.emit(); // 新增后 重置 历史列表
    this.toRecord.emit();
  }
  async onEdit() {
    this.loading = true;
    const res = await this.api.datav.updateAccident(this.data!.id, this.getParams()).finally(() => {
      this.loading = false;
    });
    this.message.success('编辑成功');
    this.refresh.emit(); // 编辑后 刷新 历史列表
    this.toRecord.emit();
  }
  get line() {
    return this.accidentForm.get('line');
  }
  get position() {
    return this.accidentForm.get('position');
  }
  get positionNext() {
    return this.accidentForm.get('positionNext');
  }
  get positionOther() {
    return this.accidentForm.get('positionOther');
  }

  get positionTypeValue() {
    return this.accidentForm.get('positionType')?.value;
  }
  get readonly() {
    return this.action === 'view';
  }
}
