import { Component, Input, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
import { NonNullableFormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
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 { RiskItemDetailComponent } from '../../../../risk/risk-bank/risk-item-detail/risk-item-detail.component';

@Component({
  selector: 'assessment-form',
  standalone: true,
  imports: [CommonNzModule, RiskItemDetailComponent],
  templateUrl: './form.component.html',
  styleUrl: './form.component.less',
})
export class AssessmentFormComponent {
  @ViewChild('detailTpl') detailTpl!: TemplateRef<void>;
  @Input() riskItems: Knowledge.RiskItem[] = [];

  validateForm = this.fb.group({
    comment: this.fb.control<string>('', [Validators.required, Validators.maxLength(1000)]),
    result: this.fb.control<number>(0, [Validators.required]),
    riskLevel: this.fb.control<string | undefined>(undefined, [Validators.required]),
    riskType: this.fb.control<number>(0, [Validators.required]),
    riskCategory: this.fb.control<number>(0, [Validators.required]),
    riskItem: this.fb.control<number>(0, [Validators.required]),
    hazardLevel: this.fb.control<number>(0, [Validators.required]),
    hazardType: this.fb.control<number>(0, [Validators.required]),
    department: this.fb.control<string>('', [Validators.required]),
    responsible: this.fb.control<string>('', []),
  });

  resultOptions: Option[] = [
    { value: 0, label: '已有风险' },
    { value: 1, label: '新风险' },
    { value: 2, label: '确认隐患' },
    { value: 3, label: '判定无异常' },
    { value: 4, label: '暂时挂起' },
    { value: 5, label: '流传其他部门' },
  ];
  hazardLevels: Option[] = [
    { value: 0, label: '重大' },
    { value: 1, label: 'A类' },
    { value: 2, label: 'B类' },
    { value: 3, label: 'C类' },
  ];
  hazardTypes: Option[] = [
    { value: 0, label: '生产现场类隐患' },
    { value: 1, label: '基础管理类隐患' },
  ];

  riskCategories: Knowledge.RiskCategoryDto[] = [];

  constructor(
    private viewContainerRef: ViewContainerRef,
    private fb: NonNullableFormBuilder,
    private message: NzMessageService,
    private setting: SettingService,
    private modal: NzModalService,
    private api: ApiService,
    private basic: BasicDataService,
    private knowledge: KnowledgeService
  ) {}

  onRiskTypeChange(value: number) {
    this.validateForm.get('riskCategory')?.reset();
    this.validateForm.get('riskItem')?.reset();
    this.riskCategories = this.knowledge.getCategoriesByType(value);
  }
  onRiskCategoryChange(value: number) {
    this.validateForm.get('riskItem')?.reset();
  }
  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,
    });
  }
  handleSelectRiskItem(id: number) {
    this.validateForm.get('riskItem')?.setValue(id);
  }
  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);
  }

  get riskTypes() {
    return this.knowledge.types();
  }
  get riskLevels() {
    return this.knowledge.levels();
  }
  get allRiskItems() {
    return this.knowledge.riskItems();
  }
  get currentFilteredRiskItems() {
    const { riskType, riskCategory, riskLevel } = this.validateForm.value;
    if (!riskType || !riskCategory || !riskLevel) return [];
    return this.allRiskItems.filter(r => {
      return r.category === riskCategory && r.type === riskType && r.level === riskLevel;
    });
  }
  get departments() {
    return this.basic.departments;
  }
  get users() {
    return this.setting.usersOfCurrentCompany;
  }
  get isRisk() {
    return this.validateForm.get('result')?.value === 0;
  }
  get isHazard() {
    return this.validateForm.get('result')?.value === 2;
  }
  get isNext() {
    return this.validateForm.get('result')?.value === 5;
  }
  get selectRiskItemId() {
    return this.validateForm.get('riskItem')?.value;
  }
  get selectRiskItemDto() {
    return this.allRiskItems.find(r => r.id === this.selectRiskItemId);
  }
  get selectRiskItemDisabled() {
    const { riskType, riskCategory, riskLevel } = this.validateForm.value;
    if (!riskType || !riskCategory || !riskLevel) return true;
    return false;
  }
}
