import { Component, inject } from '@angular/core';
import { NZ_MODAL_DATA, NzModalService } from 'ng-zorro-antd/modal';
import { CommonNzModule } from '../../../../../../common.nz.module';
import { ApiService } from '../../../../../../services/api.service';
import { SettingService } from '../../../../../../services/setting.service';

export interface KnowledgeRiskTypeFormData {
  data: Knowledge.RiskTypeDto[];
}

const getRandomId = (): number => Number(`${Math.random().toString().slice(-10, -1)}`);

@Component({
  selector: 'risk-type-form',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './knowledge-type-form.component.html',
  styleUrl: './knowledge-type-form.component.less',
})
export class KnowledgeTypeFormComponent {
  readonly nzModalData: KnowledgeRiskTypeFormData = inject(NZ_MODAL_DATA);

  loading = false;
  copyData: Knowledge.RiskTypeDto[] = [];
  editType: Knowledge.RiskTypeDto | null = null;
  editTypeValue: string = '';
  editCategory: Knowledge.RiskCategoryDto | null = null;
  editCategoryValue: string = '';
  suspendId = -1;

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

  async createRiskType(type: Partial<Knowledge.RiskTypeDto>) {
    this.loading = true;
    return await this.api.knowledge
      .createRiskType({
        value: this.editTypeValue,
        company: this.setting.userCompany,
      })
      .finally(() => {
        this.loading = false;
      });
  }
  async updateRiskType(type: Knowledge.RiskTypeDto) {
    this.loading = true;
    await this.api.knowledge
      .updateRiskType({
        value: this.editTypeValue,
        company: this.setting.userCompany,
        id: type.id,
      })
      .finally(() => {
        this.loading = false;
      });
  }
  async createRiskCategory(category: Partial<Knowledge.RiskCategoryDto>) {
    this.loading = true;
    return await this.api.knowledge
      .createRiskCategory({
        value: this.editCategoryValue,
        company: this.setting.userCompany,
        type: this.editType?.id,
      })
      .finally(() => {
        this.loading = false;
      });
  }
  async updateRiskCategory(category: Knowledge.RiskCategoryDto) {
    this.loading = true;
    await this.api.knowledge
      .updateRiskCategory({
        value: this.editCategoryValue,
        company: this.setting.userCompany,
        id: category.id,
        type: this.editType?.id,
      })
      .finally(() => {
        this.loading = false;
      });
  }

  ngOnInit() {
    this.copyData = this.nzModalData.data;
  }
  onTypeEdit(type: Knowledge.RiskTypeDto) {
    this.removeSuspense();
    this.editCategory && this.onCategoryEditCancel(this.editCategory);
    this.editType = type;
    this.editTypeValue = type.value;
  }
  onTypeDelete(type: Knowledge.RiskTypeDto) {
    this.modal.confirm({
      nzTitle: `确定删除风险类型【${type.value}】吗？`,
      nzClassName: 'precaution-modal',
      nzOnOk: async () => {
        await this.api.knowledge.deleteRiskType(type.id).finally(() => {
          this.copyData = this.copyData.filter(t => t.value !== type.value);
        });
        this.editType = null;
      },
    });
  }

  async onTypeEditConfirm(type: Knowledge.RiskTypeDto) {
    if (this.editType) {
      if (this.editType.id === this.suspendId) {
        const res = await this.createRiskType(type);
        this.editType.value = this.editTypeValue;
        if (res.id) this.editType.id = res.id;
        this.editType = null;
      } else {
        await this.updateRiskType(type);
        this.editType.value = this.editTypeValue;
        this.editType = null;
      }
    }
  }
  onTypeEditCancel(type: Knowledge.RiskTypeDto) {
    this.removeSuspense();
    this.editType = null;
  }
  onTypeAdd() {
    this.removeSuspense();
    const id = getRandomId();
    this.suspendId = id;
    this.editType = {
      id,
      value: '',
      categories: [],
      company: this.setting.userCompany,
      status: 0,
      isDelete: 0,
    };
    this.editTypeValue = '';
    if (!this.copyData) {
      this.copyData = [this.editType];
    } else {
      this.copyData.push(this.editType);
    }
  }
  onCategoryEdit(category: Knowledge.RiskCategoryDto, type: Knowledge.RiskTypeDto) {
    this.editCategory = category;
    this.editCategoryValue = category.value;
    this.editType = type;
  }
  onCategoryDelete(category: Knowledge.RiskCategoryDto, type: Knowledge.RiskTypeDto) {
    this.modal.confirm({
      nzTitle: `确定删除风险项【${category.value}】吗？`,
      nzClassName: 'precaution-modal',
      nzOnOk: async () => {
        await this.api.knowledge.deleteRiskCategory(category.id).finally(() => {
          if (type?.categories) {
            type.categories = type.categories.filter(c => c.id !== category.id);
          }
        });
        this.editType = null;
        this.editCategory = null;
      },
    });
  }
  async onCategoryEditConfirm(category: Knowledge.RiskCategoryDto) {
    // this.editCategory = null;
    // this.editType = null;
    if (this.editCategory) {
      if (this.editCategory.id === this.suspendId) {
        const res = await this.createRiskCategory(category);
        this.editCategory.value = this.editCategoryValue;
        if (res.id) this.editCategory.id = res.id;
        this.editCategory = null;
        this.editType = null;
      } else {
        await this.updateRiskCategory(category);
        this.editCategory.value = this.editCategoryValue;
        this.editCategory = null;
        this.editType = null;
      }
    }
  }
  onCategoryEditCancel(category?: Knowledge.RiskCategoryDto) {
    this.removeSuspense();
    this.editCategory = null;
  }
  onCategoryAdd(type: Knowledge.RiskTypeDto) {
    this.removeSuspense();
    const id = getRandomId();
    this.suspendId = id;
    const category: Knowledge.RiskCategoryDto = {
      id,
      value: '',
      company: this.setting.userCompany,
      departments: [],
      status: 0,
      isDelete: 0,
    };
    type.categories.push(category);
    this.editCategory = category;
    this.editType = type;
    this.editCategoryValue = '';
  }
  removeSuspense() {
    if (this.suspendId !== -1) {
      if (this.editCategory?.id === this.suspendId) {
        this.editCategory = null;
        if (this.editType?.categories) {
          this.editType.categories = this.editType.categories.filter(c => c.id !== this.suspendId);
          this.editType = null;
        }
      }
      if (this.editType?.id === this.suspendId) {
        this.editType = null;
        this.copyData = this.copyData.filter(t => t.id !== this.suspendId);
      }
    }
    this.suspendId = -1;
  }
}
