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 { 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';
import { BasicDataService } from './../../../../../services/basic.service';
import { FilterButtonGroupWithCountComponent } from './../../../../../shared/filter-button-group-with-count/filter-button-group-with-count.component';
import { RiskItemSearchComponent, RiskItemSearchConfig } from './risk-item-search/risk-item-search.component';

@Component({
  selector: 'risk-item-list',
  standalone: true,
  imports: [
    CommonNzModule,
    RiskItemTableComponent,
    CustomDrawerComponent,
    RiskItemFormComponent,
    RiskItemSearchComponent,
    FilterButtonGroupWithCountComponent,
    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,
  };
  searchDrawerConfig: RiskItemSearchConfig = {
    title: '创建风险条目',
    type: 'job',
    involveType: 'position',
    visible: false,
    value: undefined,
  };
  types: OptionWithCount<number>[] = [];
  levels: OptionWithCount<string>[] = [];
  searchInvolveType: string = 'position';
  searchInvolveValue?: number;
  searchJobValue?: number;

  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 basic: BasicDataService,
    private modal: NzModalService,
    private message: NzMessageService,
    private api: ApiService,
    private knowledge: KnowledgeService
  ) {}
  // get types(): OptionWithCount<number>[] {
  //   const riskItems = this.knowledge.riskItems();
  //   const types = this.knowledge.types().map(item => ({
  //     label: item.value,
  //     value: item.id,
  //     count: riskItems.filter(r => r.type === item.id).length,
  //   }));
  //   return [{ label: '全部', value: 0, count: riskItems.length }, ...types];
  // }
  // get levels(): OptionWithCount<string>[] {
  //   let riskItems = this.knowledge.riskItems();
  //   if (this.activeType) {
  //     riskItems = riskItems.filter(r => r.type === this.activeType);
  //   }
  //   const levels = this.knowledge.levels().map(item => ({
  //     label: item.value,
  //     value: item.value,
  //     count: riskItems.filter(r => r.level === item.value).length,
  //   }));
  //   return [{ label: '全部', value: '', count: riskItems.length }, ...levels];
  // }

  ngOnInit() {
    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;
    if (this.searchJobValue) {
      params.responsiblePositions = this.searchJobValue;
    }
    if (this.searchInvolveValue) {
      switch (this.searchInvolveType) {
        case 'position':
          params.involvedPositions = this.searchInvolveValue;
          break;
        case 'operation':
          params.involvedOperations = this.searchInvolveValue;
          break;
        case 'equipment':
          params.involvedEquipments = this.searchInvolveValue;
          break;
        default:
          break;
      }
    }
    return params;
  }
  fetchRiskItem() {
    this.loading = true;
    this.api.knowledge
      .getRiskItems(this.getParams())
      .then(res => {
        this.list = res.items;
        this.pageConfig.total = res.total;
        this.setTypeOptions(res.riskTypeNumberMap);
        this.setLevelOptions(res.levelNumberMap);
      })
      .finally(() => {
        this.loading = false;
      });
  }
  setTypeOptions(map: Record<number, number>) {
    const types = this.knowledge.types();
    const result: OptionWithCount<number>[] = [];
    Object.entries(map).map(([id, count]) => {
      const type = types.find(t => t.id === +id);
      if (type) {
        result.push({
          label: type.value,
          value: type.id,
          count,
        });
      } else if (id === '0') {
        result.push({
          label: '全部',
          value: 0,
          count,
        });
      }
    });
    this.types = result;
  }
  setLevelOptions(map: Record<string, number>) {
    const levels = this.knowledge.levels();
    const result: OptionWithCount<string>[] = [];
    Object.entries(map).map(([level, count]) => {
      const levelItem = levels.find(l => l.value === level);
      if (levelItem) {
        result.push({
          label: levelItem.value,
          value: levelItem.value,
          count,
        });
      } else if (level === '全部') {
        result.push({
          label: '全部',
          value: '',
          count,
        });
      }
    });
    this.levels = result;
  }
  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;
  }
  handleSearchJob() {
    this.searchDrawerConfig = {
      title: '责任岗位',
      type: 'job',
      involveType: this.searchInvolveType || 'position',
      visible: true,
      value: this.searchJobValue,
    };
  }
  handleSearchInvolve() {
    this.searchDrawerConfig = {
      title: '涉及场所/作业/设备',
      type: 'involve',
      involveType: this.searchInvolveType || 'job',
      visible: true,
      value: this.searchInvolveValue,
    };
  }
  handleSearchChange({ type, value }: { type: string; value: number }) {
    if (type === 'job') {
      this.searchJobValue = value;
    } else {
      this.searchInvolveType = type;
      this.searchInvolveValue = value;
    }
    this.searchDrawerConfig.involveType = type;
    this.fetchRiskItem();
  }
  clearSearchInvolve(ev: Event) {
    ev.preventDefault();
    ev.stopPropagation();
    this.searchInvolveValue = undefined;
    this.fetchRiskItem();
  }
  clearSearchJob(ev: Event) {
    ev.preventDefault();
    ev.stopPropagation();
    this.searchJobValue = undefined;
    this.fetchRiskItem();
  }
  closeSearchDrawer() {
    this.searchDrawerConfig.visible = false;
  }
  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;
  }
  get searchInvolveText() {
    const v = this.searchInvolveValue;
    if (v && this.searchInvolveType) {
      switch (this.searchInvolveType) {
        case 'position':
          return '场所：' + this.basic.positions.find(p => p.id === v)?.name;
        case 'operation':
          return '作业：' + this.basic.operations.find(p => p.id === v)?.name;
        case 'equipment':
          return '设备：' + this.basic.equipments.find(p => p.id === v)?.name;
        default:
          return '';
      }
    }
    return '';
  }
  get searchJobText() {
    const v = this.searchJobValue;
    if (v) {
      return this.basic.getJobNameWithDepartment(v);
    }
    return '';
  }
}
