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 { NzUploadFile } from 'ng-zorro-antd/upload';
import { CommonNzModule } from '../../../../../../common.nz.module';
import { ScrollImagesComponent } from '../../../../../../shared/scroll-images/scroll-images.component';
import { ApiService } from './../../../../../../services/api.service';
import { ImageUploadGroupComponent } from './../../../../../../shared/image-upload-group/image-upload-group.component';

@Component({
  selector: 'hazard-handle-acceptance',
  standalone: true,
  imports: [CommonNzModule, ScrollImagesComponent, ImageUploadGroupComponent],
  templateUrl: './handle-acceptance.component.html',
  styleUrl: './handle-acceptance.component.less',
})
export class HandleAcceptanceComponent {
  @ViewChild('fillTemplate') fillTemplate!: TemplateRef<HTMLDivElement>;
  @ViewChild('imageUploadGroup') imageUploadGroup!: ImageUploadGroupComponent;
  @Input({ required: true }) hazard!: Hazard.HazardDto;
  @Input({ required: true }) data!: Hazard.Resolve;
  validateForm = new FormGroup({
    description: new FormControl<string>('', [Validators.required]),
    images: new FormControl<string[]>([]),
    result: new FormControl<boolean>(true),
  });
  fileList: NzUploadFile[] = [];
  @Input() empty = false;
  @Output() update = new EventEmitter<number>();

  loading = false;
  info = {
    description: '',
    time: '',
    result: 'pass',
    status: 'pending', // pending, completed
    creator: '',
    images: [] as string[],
  };
  constructor(
    private modal: NzModalService,
    private api: ApiService,
    private message: NzMessageService
  ) {}

  ngOnChanges(changes: SimpleChanges) {
    if (changes['data']) {
      if (this.data) {
        this.info = {
          description: this.data.checkRemark,
          time: this.data.checkDate,
          result: this.data.status === 2 ? 'fail' : 'pass',
          status: this.data.status ? 'completed' : 'pending',
          creator: this.data.checkUserName,
          images: this.data.images,
        };
      }
    }
  }
  openFillModal() {
    this.validateForm.reset();
    this.validateForm.patchValue({
      result: true,
    });
    this.fileList = [];
    this.modal.create({
      nzTitle: '治理验收',
      nzWidth: 800,
      nzContent: this.fillTemplate,
      nzClassName: 'precaution-modal',
      nzClosable: false,
      nzOnOk: async () => await 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 { description, result } = this.validateForm.value;
    await this.api.hazard
      .checkHazard({
        checkRemark: description || '',
        images: this.imageUploadGroup.urls || [],
        // checkDate: time || '',
        // checkUserId: creator || '',
        status: result ? 1 : 2,
        troubleId: this.hazard.id,
      })
      .then(() => {
        this.update.emit(this.hazard.id);
        this.message.success('验收结果已提交');
      })
      .catch(err => {
        this.message.error(err.message || '验收结果提交失败');
      })
      .finally(() => {
        this.loading = false;
      });
  }

  get resultText() {
    return {
      fail: '不合格',
      pass: '合格',
    }[this.info.result];
  }
  get isStepProgressEnd() {
    if (this.data.handles.length === 0) {
      return false;
    } else {
      return this.data.handles[this.data.handles.length - 1].status === 1;
    }
  }
  get headerBgColor() {
    return this.info.result === 'fail' ? 'rgba(255, 77, 79, 0.06)' : 'rgba(47, 194, 91, 0.06)';
  }
}
