import { Component, EventEmitter, Input, Output } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzUploadChangeParam } from 'ng-zorro-antd/upload';
import { CommonNzModule } from '../../../../../common.nz.module';
import { ApiService } from '../../../../../services/api.service';

@Component({
  selector: 'doc-table',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './doc-table.component.html',
  styleUrl: './doc-table.component.less',
})
export class DocTableComponent {
  importing = false;
  loading = false;
  @Input() pageConfig: IPageConfig = {
    page: 0,
    total: 0,
    size: 10,
  };
  @Input() list: Knowledge.Doc[] = [];
  @Output() pageChange = new EventEmitter<number>();

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

  onCurrentPageChange(page: number) {
    this.pageConfig.page = page;
    this.pageChange.emit(page);
  }

  onRemove(data: Knowledge.Doc) {
    this.modal.confirm({
      nzClassName: 'precaution-modal',
      nzTitle: '删除文档',
      nzContent: `确定要删除【${data.name}】吗？`,
      nzOkText: '确定',
      nzOkDanger: true,
      nzOnOk: async () => {
        await this.api.knowledge
          .removeDoc(data.id)
          .then(() => {
            this.message.success('删除成功');
            this.pageChange.emit(this.pageConfig.page);
          })
          .catch(err => {
            this.message.error(err.message);
            throw err;
          });
      },
    });
  }

  handleImportStatusChange(event: NzUploadChangeParam) {
    if (event.type === 'start') {
      this.importing = true;
    }
    if (event.type === 'success') {
      if (event.file.response?.code !== 0) {
        this.message.error('更新失败: ' + event.file.response?.message);
        this.importing = false;
        return;
      }
      this.message.success('更新成功');
      this.importing = false;

      this.pageChange.emit(this.pageConfig.page);
    } else if (event.type === 'error') {
      if (event.file.error.error?.message) {
        this.message.error('更新失败: ' + event.file.error.error.message);
      } else {
        this.message.error('更新失败');
      }
      this.importing = false;
    }
  }

  onView(data: Knowledge.Doc) {
    window.open(data.url, '_blank');
  }
}
