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 { 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';
import { HandleAcceptanceComponent } from './../handle-acceptance/handle-acceptance.component';

@Component({
  selector: 'hazard-handle-progress',
  standalone: true,
  imports: [CommonNzModule, ScrollImagesComponent, ImageUploadGroupComponent, HandleAcceptanceComponent],
  templateUrl: './handle-progress.component.html',
  styleUrl: './handle-progress.component.less',
})
export class HandleProgressComponent {
  @ViewChild('fillTemplate') fillTemplate!: TemplateRef<HTMLDivElement>;
  @ViewChild('imageUploadGroup') imageUploadGroup!: ImageUploadGroupComponent;
  @Input() empty = false;
  @Input({ required: true }) hazard!: Hazard.HazardDto;
  @Input() data?: Hazard.Resolve;
  @Output() update = new EventEmitter<number>();

  loading = false;
  validateForm = new FormGroup({
    description: new FormControl<string>('', [Validators.required]),
    images: new FormControl<string[]>([]),
    handleTime: new FormControl<string>('', [Validators.required]),
    handleUser: new FormControl<string>('', [Validators.required]),
    complete: new FormControl<boolean>(false),
  });
  fileList: NzUploadFile[] = [];
  disabledDate = (date: Date) => {
    return date.getTime() >= Date.now();
  };
  // data = [
  //   {
  //     description: '隐患整改',
  //     time: '2024-01-01 12:00',
  //     status: '已完成',
  //     creator: '张三',
  //     images: Array.from({ length: 11 }).map(() => `https://loremflickr.com/260/150?q=${Math.random()}`),
  //   },

  //   {
  //     description:
  //       '事故隐患分为一般事故隐患和重大事故隐患。一般事故隐患，是指危害和整改难度较小，发现后能够立即整改排除的隐患。重大事故隐患，是指危害和整改难度较大，应当全部或者局部停产停业，并经过一定时间整改治理方能排除的隐患，或者因外部因素影响致使生产经营单位自身难以排除的隐患。',
  //     time: '2024-11-23 17:40',
  //     status: '已完成',
  //     creator: '李酒鸿',
  //     images: Array.from({ length: 11 }).map(() => `https://loremflickr.com/260/150?q=${Math.random()}`),
  //   },
  // ];
  constructor(
    private modal: NzModalService,
    private api: ApiService,
    private message: NzMessageService
  ) {}

  openFillModal() {
    this.validateForm.reset();
    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, images, handleTime, handleUser, complete } = this.validateForm.value;
    await this.api.hazard
      .createHazardProgress({
        content: description || '',
        images: this.imageUploadGroup.urls || [],
        resolveDate: handleTime || '',
        userId: handleUser || '',
        status: complete ? 1 : 0,
        troubleId: this.hazard.id,
      })
      .finally(() => {
        this.loading = false;
      })
      .then(() => {
        this.update.emit(this.hazard.id);
        this.message.success('治理进度已提交');
      })
      .catch(err => {
        this.message.error(err.message || '治理进度提交失败');
      });
  }
}
