import { Component, EventEmitter, Input, Output, QueryList, SimpleChanges, ViewChildren } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { horizontalInOut } from '../../../../../../../common.animation';
import { Round } from '../task-rounds/task-rounds.component';
import { CommonNzModule } from './../../../../../../../common.nz.module';
import { ApiService } from './../../../../../../../services/api.service';
import { DataEmptyComponent } from './../../../../../../../shared/data-empty/data-empty.component';
import { TaskFormComponent } from './task-form/task-form.component';

interface ComposeRow extends Hazard.InspectionPlanHandleDto {
  isEditing: boolean;
  isNew: boolean;
  submitting: boolean;
}

@Component({
  selector: 'plan-round-edit-form',
  standalone: true,
  imports: [CommonNzModule, TaskFormComponent, DataEmptyComponent],
  templateUrl: './round-edit-form.component.html',
  styleUrl: './round-edit-form.component.less',
  animations: [horizontalInOut],
})
export class RoundEditFormComponent {
  @ViewChildren(TaskFormComponent) taskForms!: QueryList<TaskFormComponent>;

  @Input() plan!: Hazard.InspectionPlan;
  @Input() round!: Round;
  @Input() list: Hazard.InspectionPlanHandleDto[] = [];
  @Input() departmentId?: number;
  @Input() times: number = -1;

  @Output() fetchDetail = new EventEmitter<void>();

  existList: ComposeRow[] = [];
  // newList: ComposeRow[] = [];

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

  ngOnInit(): void {
    // this.setExistList();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['list']) {
      // this.clearNewList();
      this.setExistList();
    }
  }
  // clearNewList() {
  //   this.newList = [];
  // }
  setExistList() {
    this.existList = this.list.map(item => ({
      ...item,
      isEditing: false,
      submitting: false,
      isNew: false,
    }));
  }
  getRandomId(): number {
    return Math.random() * 1000000;
  }
  addNewItem() {
    const newIndex = this.existList.findIndex(item => item.isNew);
    if (newIndex !== -1) {
      // this.message.warning('移除当前新增项');
      this.existList.splice(newIndex, 1);
    }
    const fakeId = this.getRandomId();
    this.existList.unshift({
      id: fakeId,
      line: 0,
      position: 0,
      positionNext: 0,
      positionOther: '',
      positionType: '',
      targets: [],
      peopleNumber: 1,
      leaderUserName: '',
      leaderUserId: '',
      times: this.times,
      troubleshootPlan: this.round?.meta.id,
      // status: '',
      isEditing: true,
      submitting: false,
      isNew: true,
      teams: [],
      checkAbnormal: 0,
      checkWorkSituation: '',
    });
    setTimeout(() => {
      this.taskForms.get(fakeId)?.focus();
    });
  }
  onCancel(id: number, isNew?: boolean) {
    if (isNew) {
      this.existList = this.existList.filter(item => item.id !== id);
    } else {
      this.taskForms.get(id)?.revert();
      const currentItem = this.existList.find(item => item.id === id)!;
      currentItem.isEditing = false;
    }
  }
  onDelete(item: ComposeRow) {
    // this.existList = this.existList.filter(item => item.id !== item.id);
    this.modal.confirm({
      nzClassName: 'precaution-modal',
      nzTitle: '删除',
      nzContent: `确定要删除吗？`,
      nzOkText: '确定',
      nzOkDanger: true,
      nzOnOk: async () => {
        await this.api.hazard.removePlanHandle(item.id);
        this.message.success('删除成功');
        this.fetchDetail.emit();
      },
    });
  }
  onCopy(item: ComposeRow) {
    const newIndex = this.existList.findIndex(item => item.isNew);
    if (newIndex !== -1) {
      // this.message.warning('移除当前新增项');
      this.existList.splice(newIndex, 1);
    }
    this.existList.unshift({
      id: 0,
      line: item.line,
      position: item.position,
      positionNext: item.positionNext,
      positionOther: item.positionOther,
      positionType: item.positionType,
      targets: item.targets,
      peopleNumber: item.peopleNumber,
      leaderUserName: item.leaderUserName,
      leaderUserId: item.leaderUserId,
      times: item.times,
      troubleshootPlan: item.troubleshootPlan,
      // status: item.status,
      isEditing: true,
      submitting: false,
      isNew: true,
      teams: item.teams,
      checkAbnormal: 0,
      checkWorkSituation: '',
    });
    setTimeout(() => {
      this.taskForms.get(0)?.focus();
    });
  }
  async onAdd(index: number) {
    const currentItem = this.existList.find(item => item.id === index)!;
    currentItem.submitting = true;
    const form = this.taskForms.find(item => item.index === index);
    await form
      ?.add()
      .then(res => {
        Object.assign(currentItem, res);
        currentItem.isNew = false;
        currentItem.isEditing = false;
        this.fetchDetail.emit();
      })
      .finally(() => {
        currentItem.submitting = false;
      });
  }
  async onSave(index: number) {
    const currentItem = this.existList.find(item => item.id === index)!;
    currentItem.submitting = true;
    const form = this.taskForms.find(item => item.index === index);
    await form
      ?.save()
      .then(res => {
        Object.assign(currentItem, res);
        currentItem.isEditing = false;
        this.fetchDetail.emit();
      })
      .finally(() => {
        currentItem.submitting = false;
      });
  }

  forwardItem(item: ComposeRow) {
    return item;
  }
}
