import { Component, EventEmitter, Input, Output, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
import { AbstractControl, NonNullableFormBuilder, 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 { ApiService } from '../../../../../services/api.service';
import { BasicDataService } from '../../../../../services/basic.service';
import { KnowledgeService } from '../../../../../services/knowledge.service';
import { SettingService } from '../../../../../services/setting.service';
import { ImageUploadGroupComponent } from '../../../../../shared/image-upload-group/image-upload-group.component';
import { RiskItemDetailComponent } from '../../../risk/risk-bank/risk-item-detail/risk-item-detail.component';
import { hazardLevelOptions, hazardTypeOptions } from '../../hazard.utils';

export interface HazardFormComponentProps {
  data?: Hazard.HazardDto;
  visible: boolean;
}

@Component({
  selector: 'hazard-form',
  standalone: true,
  imports: [CommonNzModule, ImageUploadGroupComponent, RiskItemDetailComponent],
  templateUrl: './hazard-form.component.html',
  styleUrl: './hazard-form.component.less',
})
export class HazardFormComponent {
  @ViewChild('detailTpl') detailTpl!: TemplateRef<void>;
  @ViewChild('imageUploadGroup') imageUploadGroup!: ImageUploadGroupComponent;
  @Input() data?: Hazard.HazardDto;
  @Output() onClose = new EventEmitter<void>();
  validateForm = this.fb.group({
    name: this.fb.control<string>('', [Validators.required, Validators.maxLength(100)]),
    level: this.fb.control<string>('', [Validators.required]),
    type: this.fb.control<string>('', [Validators.required]),
    riskType: this.fb.control<number | null>(null, [Validators.required]),
    riskCategory: this.fb.control<number | null>(null, [Validators.required]),
    riskItem: this.fb.control<number>(0, [Validators.required]),
    description: this.fb.control<string>('', [Validators.required, Validators.maxLength(1500)]),
    position: this.fb.control<number | null>(null, [this.involvedValidator.bind(this)]),
    operation: this.fb.control<number | null>(null, [this.involvedValidator.bind(this)]),
    equipment: this.fb.control<number | null>(null, [this.involvedValidator.bind(this)]),
    department: this.fb.control<number | null>(null, []),
    responsible: this.fb.control<number | null>(null, []),
  });
  levels: Option[] = hazardLevelOptions.slice();
  types: Option[] = hazardTypeOptions.slice();
  categories: Option[] = [];
  departments: BasicData.Department[] = [];
  uploading = false;
  fileList: NzUploadFile[] = [
    {
      uid: '15',
      name: '现场照片',
      status: 'done',
      url: 'https://precaution-check2.stage.leadinvr.com/api/uploadFile/get?name=tZuzRmxRvku74ccb898b08bdcbe77a050b20863d1cc6.jpg',
      preview:
        'https://precaution-check2.stage.leadinvr.com/api/uploadFile/get?name=tZuzRmxRvku74ccb898b08bdcbe77a050b20863d1cc6.jpg',
    },
  ];
  constructor(
    private viewContainerRef: ViewContainerRef,
    private modal: NzModalService,
    private fb: NonNullableFormBuilder,
    private message: NzMessageService,
    private setting: SettingService,
    private api: ApiService,
    private knowledge: KnowledgeService,
    private basic: BasicDataService
  ) {
    setting.getUsersOfCurrentCompany();
  }
  involvedValidator(control: AbstractControl) {
    if (!this.validateForm) {
      return null;
    }
    const position = this.validateForm.get('position')?.value;
    const operation = this.validateForm.get('operation')?.value;
    const equipment = this.validateForm.get('equipment')?.value;
    if (!position && !operation && !equipment) {
      return { involved: true, error: true, required: true };
    }
    return null;
  }
  reset() {
    this.validateForm.reset();
    this.validateForm.markAsUntouched();
    this.validateForm.updateValueAndValidity();

    this.fileList = [];
    this.uploading = false;
  }
  onCancel() {
    this.onClose.emit();
  }
  onInvolvedChange() {
    this.validateForm.get('position')?.updateValueAndValidity();
    this.validateForm.get('operation')?.updateValueAndValidity();
    this.validateForm.get('equipment')?.updateValueAndValidity();
  }
  selectRiskItem(ev: Event) {
    ev.preventDefault();
    this.modal.create<TemplateRef<void>, {}>({
      nzContent: this.detailTpl,
      nzViewContainerRef: this.viewContainerRef,
      nzClassName: 'noop-modal',
      nzClosable: true,
      nzData: {},
      nzWidth: 'calc(100vw - 144px)',
      nzFooter: null,
    });
  }
  async submitForm() {
    if (!this.validateForm.valid) {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    } else {
      this.onSubmit();
    }
  }
  async onSubmit() {
    console.log(this.validateForm.value);
    console.log(this.imageUrls);
    this.onClose.emit();
  }
  changeRiskType(t: number) {
    // const { riskType } = this.validateForm.value;
    this.validateForm.get('riskCategory')?.reset();
    this.validateForm.get('department')?.reset();
    this.validateForm.get('responsible')?.reset();
    if (t) {
      this.categories = this.knowledge.getCategoryOptionsByType(t);
    } else {
      this.categories = [];
    }
  }
  changeRiskCategory(category: number) {
    this.validateForm.get('department')?.reset();
    this.validateForm.get('responsible')?.reset();
    this.departments = this.knowledge.getDepartmentOptionsByCategory(category);
  }
  handleSelectRiskItem(id: number) {
    this.validateForm.get('riskItem')?.setValue(id);
  }
  get positions() {
    return this.basic.positions;
  }
  get operations() {
    return this.basic.operations;
  }
  get equipments() {
    return this.basic.equipments;
  }
  get users() {
    const { department } = this.validateForm.value;
    if (!department) return [];
    return this.setting.usersOfCurrentCompany.filter(u => u.department === department);
  }
  get imageUrls() {
    return this.imageUploadGroup.fileList.map(file => file.url);
  }
  get riskTypes() {
    return this.knowledge.types().map(t => ({ label: t.value, value: t.id }));
  }
  get allRiskItems() {
    return this.knowledge.riskItems();
  }
  get selectRiskItemId() {
    return this.validateForm.get('riskItem')?.value;
  }
  get currentFilteredRiskItems() {
    const { riskType, riskCategory } = this.validateForm.value;
    if (!riskType || !riskCategory) return [];
    return this.allRiskItems.filter(r => {
      return r.category === riskCategory && r.type === riskType;
    });
  }
  get selectRiskItemDto() {
    return this.allRiskItems.find(r => r.id === this.selectRiskItemId);
  }
  get selectRiskItemDisabled() {
    const { riskType, riskCategory } = this.validateForm.value;
    if (!riskType || !riskCategory) return true;
    return false;
  }
}
