import { Component, TemplateRef, ViewChild, ViewContainerRef } 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';
import { KnowledgeService } from '../../../../../services/knowledge.service';
import { SettingService } from '../../../../../services/setting.service';
import { CustomDrawerComponent } from '../../../../../shared/custom-drawer/custom-drawer.component';
import { FilterButtonGroupComponent } from '../../../../../shared/filter-button-group/filter-button-group.component';
import { RiskItemDetailComponent } from '../risk-item-detail/risk-item-detail.component';
import { RiskItemFormComponent } from '../risk-item-form/risk-item-form.component';
import { RiskItemTableComponent } from '../risk-item-table/risk-item-table.component';

@Component({
  selector: 'risk-item-list',
  standalone: true,
  imports: [
    CommonNzModule,
    RiskItemTableComponent,
    CustomDrawerComponent,
    RiskItemFormComponent,
    FilterButtonGroupComponent,
    RiskItemDetailComponent,
  ],
  templateUrl: './risk-item-list.component.html',
  styleUrl: './risk-item-list.component.less',
})
export class RiskItemListComponent {
  @ViewChild('detailTpl') detailTpl!: TemplateRef<void>;

  importing = false;
  loading = false;
  loadingRecord = false;
  records: Knowledge.RiskItem[] = [];
  drawerConfig: {
    visible: boolean;
    data: Knowledge.RiskItem | null;
    type: 'add' | 'edit';
    title: string;
  } = {
    title: '创建风险条目',
    type: 'add',
    visible: false,
    data: null,
  };

  // types: Option<number>[] = [];
  levels: Option<string>[] = [];

  activeType: number | undefined = undefined;
  activeLevel: string | undefined = undefined;

  pageConfig: IPageConfig = {
    page: 0,
    total: 0,
    size: 10,
  };

  list: Knowledge.RiskItem[] = [];

  constructor(
    private viewContainerRef: ViewContainerRef,
    private setting: SettingService,
    private modal: NzModalService,
    private message: NzMessageService,
    private api: ApiService,
    private knowledge: KnowledgeService
  ) {}
  get types() {
    const types = this.knowledge.types().map(item => ({
      label: item.value,
      value: item.id,
    }));
    return [{ label: '全部', value: 0 }, ...types];
  }
  ngOnInit() {
    const levels = this.knowledge.levels().map(item => ({
      label: item.value,
      value: item.value,
    }));
    this.levels = [{ label: '全部', value: '' }, ...levels];
    this.activeType = 0;
    this.activeLevel = '';
    this.fetchRiskItem();
  }
  onPageConfigChange(config: IPageConfig) {
    this.pageConfig = config;
    this.fetchRiskItem();
  }

  changeCategory(value: number) {
    this.activeType = value;
    this.pageConfig.page = 0;
    this.fetchRiskItem();
  }

  changeLevel(value: string) {
    this.activeLevel = value;
    this.pageConfig.page = 0;
    this.fetchRiskItem();
  }

  getParams() {
    const params: Knowledge.GetRiskItemListParams = {
      company: this.company,
      page: this.pageConfig.page,
      size: this.pageConfig.size,
      type: this.activeType,
      level: this.activeLevel,
    };
    if (!this.activeType) delete params.type;
    if (!this.activeLevel) delete params.level;
    return params;
  }
  fetchRiskItem() {
    this.loading = true;
    this.api.knowledge
      .getRiskItems(this.getParams())
      .then(res => {
        this.list = res.items;
        this.pageConfig.total = res.total;
      })
      .finally(() => {
        this.loading = false;
      });
  }
  async fetchRecord(id: number) {
    this.loadingRecord = true;
    this.records = [];
    const res = await this.api.knowledge.getRiskItemHistory({
      company: this.company,
      page: 0,
      size: 100,
      riskPointId: id,
    });
    this.records = res.items;
    this.loadingRecord = false;
    return res;
  }
  createRiskItem() {
    this.drawerConfig = {
      visible: true,
      data: null,
      type: 'add',
      title: '创建风险条目',
    };
  }
  updateRiskItem(data: Knowledge.RiskItem) {
    this.drawerConfig = {
      visible: true,
      data: data,
      type: 'edit',
      title: '编辑风险条目',
    };
  }
  removeRiskItem(data: Knowledge.RiskItem) {
    this.modal.warning({
      nzClassName: 'precaution-modal',
      nzTitle: '删除风险项',
      nzContent: `确定要删除该风险项吗？`,
      nzOkText: '确定',
      nzOkDanger: true,
      nzOnOk: () => {
        this.api.knowledge.deleteRiskItem(data.id).then(res => {
          if (res.code === 0) {
            this.message.success('删除成功');
            this.fetchRiskItem();
          }
        });
      },
    });
  }
  async toRecord(data: Knowledge.RiskItem) {
    this.modal.create<TemplateRef<void>, {}>({
      nzContent: this.detailTpl,
      nzViewContainerRef: this.viewContainerRef,
      nzClassName: 'noop-modal',
      nzClosable: true,
      nzData: {
        id: null,
        data: this.records,
      },
      nzWidth: 'calc(100vw - 144px)',
      nzFooter: null,
    });
    await this.fetchRecord(data.id);
  }
  closeDrawer() {
    this.drawerConfig.visible = false;
    this.drawerConfig.data = null;
  }

  onSearch() {
    this.fetchRiskItem();
  }
  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.fetchRiskItem();
    } 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;
    }
  }
  get company() {
    return this.setting.userCompany;
  }
}
