import { Component, EventEmitter, Input, Output, SimpleChanges, TemplateRef, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { getHazardMeasureStatusText, hazardMeasureStatusColor } from '../../../hazard.utils';
import { CommonNzModule } from './../../../../../../common.nz.module';
import { ApiService } from './../../../../../../services/api.service';
import { DataEmptyComponent } from './../../../../../../shared/data-empty/data-empty.component';

@Component({
  selector: 'hazard-measure-target',
  standalone: true,
  imports: [CommonNzModule, DataEmptyComponent],
  templateUrl: './measure-target.component.html',
  styleUrl: './measure-target.component.less',
})
export class MeasureTargetComponent {
  @ViewChild('fillTemplate') fillTemplate!: TemplateRef<HTMLDivElement>;
  @Input() data!: Hazard.HazardDto;
  @Output() update = new EventEmitter<number>();
  loading = false;
  comment = '';
  constructor(
    private modal: NzModalService,
    private message: NzMessageService,
    private api: ApiService
  ) {}
  validateForm = new FormGroup({
    measure: new FormControl('', [Validators.required]),
    target: new FormControl('', [Validators.required]),
    deadline: new FormControl('', [Validators.required]),
    executor: new FormControl('', [Validators.required]),
  });
  ngOnChanges(changes: SimpleChanges) {
    if (changes['data']) {
      this.validateForm.reset();
      if (this.data?.plan) {
        this.validateForm.patchValue({
          measure: this.data.plan.measure,
          target: this.data.plan.target,
          deadline: this.data.plan.endDate,
          executor: this.data.plan.userName,
        });
      }
    }
  }
  openFillModal() {
    this.modal.create({
      nzTitle: '治理方案',
      nzWidth: 600,
      nzContent: this.fillTemplate,
      nzClassName: 'precaution-modal',
      nzClosable: false,
      nzOnOk: () => this.onSubmit(),
    });
  }
  async onSubmit() {
    if (!this.validateForm.valid) {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
      return Promise.reject();
    } else {
      await this.handleSubmit();
    }
  }
  async handleSubmit() {
    const { measure, target, deadline, executor } = this.validateForm.value;
    this.loading = true;
    await this.api.hazard
      .updateHazardPlan(this.data.id, {
        measure: measure || '',
        target: target || '',
        endDate: deadline || '',
        userName: executor || '',
      })
      .finally(() => {
        this.loading = false;
      });
    this.update.emit(this.data.id);
    this.message.success('治理方案已提交');
  }
  async handlePass() {
    this.loading = true;
    await this.api.hazard.passHazardPlan(this.data.id, this.comment).then(async () => {
      this.update.emit(this.data.id);
      this.message.success('治理方案已通过');
      this.loading = false;
    });
  }
  async handleReject() {
    this.loading = true;
    await this.api.hazard
      .refuseHazardPlan(this.data.id, this.comment)
      .then(async () => {
        this.update.emit(this.data.id);
        this.message.success('治理方案已驳回');
        this.loading = false;
      })
      .finally(() => {});
  }
  get hazardMeasureStatusText() {
    if (this.stillEmpty) {
      return '未填写';
    }
    return getHazardMeasureStatusText(this.data.planStatus);
  }
  get stillEmpty() {
    return !this.data.plan.measure;
  }
  get auditable() {
    return this.data.planStatus === 0 && this.data.plan.measure;
  }
  get beingRejected() {
    return this.data.planStatus === 3;
  }
  get hazardMeasureStatusBgColor() {
    return this.hazardMeasureStatusColor ? this.hazardMeasureStatusColor + '28' : '';
  }
  get hazardMeasureStatusColor() {
    return hazardMeasureStatusColor[this.data.planStatus] ? hazardMeasureStatusColor[this.data.planStatus] : '';
  }
}
