import { Component, ViewContainerRef } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonNzModule } from '../../../../common.nz.module';
import { ApiService } from '../../../../services/api.service';
import { SettingService } from '../../../../services/setting.service';
import { FilterButtonGroupComponent } from '../../../../shared/filter-button-group/filter-button-group.component';
import { DocImportComponent, DocImportModalData } from './doc-import/doc-import.component';
import { DocTableComponent } from './doc-table/doc-table.component';
import { docCategories, docLevels } from './risk-doc.utils';

@Component({
  selector: 'knowledge-doc',
  standalone: true,
  imports: [CommonNzModule, FilterButtonGroupComponent, DocTableComponent],
  templateUrl: './risk-doc.component.html',
  styleUrl: './risk-doc.component.less',
})
export class RiskDocComponent {
  docCategories = docCategories;
  docLevels = docLevels;
  category = '';
  level = '';

  pageConfig: IPageConfig = {
    page: 0,
    total: 0,
    size: 10,
  };
  list: Knowledge.Doc[] = [];

  constructor(
    private modal: NzModalService,
    private viewContainerRef: ViewContainerRef,
    private api: ApiService,
    private setting: SettingService
  ) {}

  ngOnInit() {
    this.fetchList();
  }

  changeCategory(value: number | string) {
    this.category = value as string;
    this.pageConfig.page = 0;
    this.fetchList();
  }
  changeLevel(value: number | string) {
    this.level = value as string;
    this.pageConfig.page = 0;
    this.fetchList();
  }

  onPageChange(page: number) {
    this.pageConfig.page = page;
    this.fetchList();
  }

  onImport() {
    this.modal.create<DocImportComponent, DocImportModalData>({
      nzClassName: 'precaution-modal',
      nzTitle: '文档 - 导入',
      nzContent: DocImportComponent,
      nzWidth: 500,
      nzBodyStyle: { paddingBottom: '0px' },
      nzViewContainerRef: this.viewContainerRef,
      nzData: {
        categories: this.docCategories.filter(e => e.value !== ''),
        levels: this.docLevels.filter(e => e.value !== ''),
        category: this.category,
        level: this.level,
        onImportSuccess: () => {
          this.onSearch();
        },
      },
      nzFooter: null,
    });
  }

  onSearch() {
    this.fetchList();
  }
  getParams() {
    const p: Knowledge.GetDocListParams = {
      company: this.company,
      page: this.pageConfig.page,
      size: this.pageConfig.size,
    };
    if (this.category) p.category = this.category;
    if (this.level) p.level = this.level;
    return p;
  }
  async fetchList() {
    const result = await this.api.knowledge.getDocList(this.getParams());
    this.list = result.items;
    this.pageConfig.total = result.total;
  }

  get company() {
    return this.setting.userCompany;
  }
}
