import { Component, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonNzModule } from '../../../../../common.nz.module';
import { ApiService } from '../../../../../services/api.service';
import { KnowledgeService } from '../../../../../services/knowledge.service';
import { SettingService } from '../../../../../services/setting.service';
import { RiskItemDetailComponent } from '../risk-item-detail/risk-item-detail.component';

@Component({
  selector: 'risk-update-record',
  standalone: true,
  imports: [CommonNzModule, RiskItemDetailComponent],
  templateUrl: './update-record.component.html',
  styleUrl: './update-record.component.less',
})
export class UpdateRecordComponent {
  @ViewChild('detailTpl') detailTpl!: TemplateRef<void>;
  pageConfig: IPageConfig = {
    page: 0,
    total: 0,
    size: 10,
  };
  list: Knowledge.RiskItem[] = [];
  constructor(
    private viewContainerRef: ViewContainerRef,
    private modal: NzModalService,
    private readonly api: ApiService,
    private readonly setting: SettingService,
    private readonly knowledge: KnowledgeService
  ) {}
  ngOnInit() {
    this.fetchRecordList();
  }
  async fetchRecordList() {
    const res = await this.api.knowledge.getRiskItemHistory({
      company: this.setting.userCompany,
      page: this.pageConfig.page,
      size: this.pageConfig.size,
    });
    this.list = res.items;
    this.pageConfig.total = res.total;
  }
  onCurrentPageChange(page: number) {
    this.pageConfig.page = page;
    this.fetchRecordList();
  }
  getTypeText(item: Knowledge.RiskItem) {
    return this.knowledge.getTypeName(item.type);
  }
  getCategoryText(item: Knowledge.RiskItem) {
    return this.knowledge.getCategoryName(item.category, item.type);
  }

  recordData: Knowledge.RiskItem[] = [];
  loadingRecord = false;
  async fetchRecordData(riskPointId: number, id: number) {
    this.loadingRecord = true;
    const res = await this.api.knowledge.getRiskItemHistoryDetail(riskPointId, id).finally(() => {
      this.loadingRecord = false;
    });
    this.recordData = res.items;
  }
  showDetail(data: Knowledge.RiskItem) {
    this.modal.create<TemplateRef<void>, {}>({
      nzContent: this.detailTpl,
      nzViewContainerRef: this.viewContainerRef,
      nzClassName: 'noop-modal',
      nzClosable: true,
      nzData: {
        id: null,
        data,
      },
      nzWidth: 'calc(100vw - 144px)',
      nzFooter: null,
    });
    this.fetchRecordData(data.riskPointId!, data.id);
  }
}
