import { Component, inject, Input, ViewContainerRef } from '@angular/core';
import { FormGroup, NonNullableFormBuilder } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzTableSortOrder } from 'ng-zorro-antd/table';
import { CommonNzModule } from '../../common.nz.module';
import { ApiService } from '../../services/api.service';
import { BasicDataService } from '../../services/basic.service';
import { KnowledgeService } from '../../services/knowledge.service';
import { SettingService } from '../../services/setting.service';
import { FormComponent, SimpleFormModalData } from './form/form.component';

export interface Column {
  sortOrder?: NzTableSortOrder | null;
  sortable?: boolean;
  type?: string;
  label: string;
  key: string;
  width?: string;
  getter?: (data: any) => any;
}

@Component({
  selector: 'simple-form-page',
  standalone: true,
  imports: [CommonNzModule, FormComponent],
  templateUrl: './simple-form-page.component.html',
  styleUrl: './simple-form-page.component.less',
})
export class SimpleFormPageComponent<T = BasicData.Predefine> {
  list: T[] = [];
  sortDirections: NzTableSortOrder[] = ['ascend', 'descend', null];
  @Input() keyWord = '';
  @Input() showSearchForm = true;
  @Input() editable = true;
  @Input() key: string = 'title';
  @Input() columns: Column[] = [{ label: '编号', key: 'id' }];
  detailVisible = false;
  pageConfig = {
    total: 0,
    page: 0,
    size: 10,
    current: 0,
  };
  detailData: { key: string; value: string }[] = [];
  currentOperateData: T | null = null;

  readonly api = inject(ApiService);
  readonly fb = inject(NonNullableFormBuilder);
  readonly modal = inject(NzModalService);
  readonly basic = inject(BasicDataService);
  readonly message = inject(NzMessageService);
  readonly setting = inject(SettingService);
  readonly knowledgeService = inject(KnowledgeService);
  readonly viewContainerRef = inject(ViewContainerRef);

  validateForm: FormGroup<any> = this.fb.group({});
  @Input() inputFields = [{ label: '编号', key: 'id', initValue: '' }];

  ngOnInit() {
    this.inputFields.forEach(f => {
      this.validateForm.addControl(f.key, this.fb.control(f.initValue));
    });
    this.fetchList();
  }
  onSearch() {
    this.pageConfig.page = 0;
    this.fetchList();
  }
  onReset() {
    this.validateForm.reset();
    this.onSearch();
  }
  handleSort(col: Column, ev: string | null) {
    col.sortOrder = ev as NzTableSortOrder;
    this.fetchList();
  }
  getIdOrderSequence() {
    const idColumn = this.columns.find(c => c.key === 'id');
    if (!idColumn || idColumn.sortOrder === undefined) {
      return undefined;
    }
    return {
      prop: 'id',
      order: idColumn.sortOrder === 'descend' ? 'descending' : 'ascending',
    };
  }
  getParams() {
    const v = Object.entries(this.validateForm.value).reduce(
      (acc, [key, value]) => {
        if (value) {
          acc[key] = value;
        }
        return acc;
      },
      {} as Record<string, any>
    );
    return {
      page: this.pageConfig.page,
      current: this.pageConfig.current,
      sequence: this.getIdOrderSequence(),
      ...v,
    };
  }
  getValue(row: T, key: string) {
    return (row as any)[key];
  }
  onCurrentPageChange(current: number) {
    this.pageConfig.current = current;
    this.fetchList();
  }
  async fetchList() {
    throw new Error('not implement');
  }
  handleEdit(data: T) {
    this.currentOperateData = data;
    this.createModal('edit', data);
  }
  handleAdd() {
    this.currentOperateData = null;
    this.createModal('add');
  }
  handleDelete(data: T) {
    this.currentOperateData = data;
    const name = data ? this.getValue(data, this.key) : '';
    this.modal.confirm({
      nzClassName: 'precaution-modal',
      nzTitle: `删除${this.keyWord}`,
      nzContent: `确定要删除【${name}】吗？`,
      nzOkText: '确定',
      nzOkDanger: true,
      nzOnOk: async () => {
        await this.onDelete(data);
        this.currentOperateData = null;
        this.fetchList();
      },
    });
  }
  createModal(type: 'add' | 'edit', data?: T): void {
    const name = data ? this.getValue(data, this.key) : '';
    this.modal.create<FormComponent, SimpleFormModalData>({
      nzClassName: 'precaution-modal',
      nzTitle: type === 'add' ? '新增' + this.keyWord : '编辑' + this.keyWord + ' - ' + name,
      nzOkText: type === 'add' ? '新增' : '修改',
      nzContent: FormComponent,
      nzWidth: 500,
      nzViewContainerRef: this.viewContainerRef,
      nzData: {
        keyWord: this.keyWord,
        type,
        name,
        id: data ? this.getValue(data, 'id') : undefined,
      },
      nzOnOk: async instance => {
        const res = await instance.submit();
        if (type === 'add') {
          await this.onAdd(res).finally(() => {
            instance.loading = false;
          });
          this.currentOperateData = null;
          this.fetchList();
          return Promise.reject();
        } else {
          await this.onEdit({
            ...data!,
            ...res,
          }).finally(() => {
            instance.loading = false;
          });
          this.currentOperateData = null;
          this.onSearch();
        }
      },
    });
  }
  handleOk() {
    this.detailVisible = false;
    this.currentOperateData = null;
  }
  async onEdit(data: T) {
    throw new Error('not implement');
  }
  async onAdd(data: any) {
    throw new Error('not implement');
  }
  async onDelete(data: T) {
    throw new Error('not implement');
  }
}
