import { Component, ViewContainerRef } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Subscription } from 'rxjs';
import { CommonNzModule } from './../../../../../common.nz.module';
import { ApiService } from './../../../../../services/api.service';
import { BasicDataService } from './../../../../../services/basic.service';
import { PositionCategoryFormComponent, PositionCategoryFormModalData } from './cate-form/form.component';
import { PositionFormComponent, PositionFormModalData } from './form/form.component';
import { stationTypes } from './position.utils';

@Component({
  selector: 'poe-position',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './position.component.html',
  styleUrl: './position.component.less',
})
export class PositionComponent {
  loading = false;
  selectedCategory = 1;

  validateForm = this.fb.group({
    name: this.fb.control<string | undefined>(undefined),
    type: this.fb.control<string>(''),
    line: this.fb.control<number | undefined>(undefined),
  });
  inputFields = [{ label: '名称', key: 'name' }];
  tableWidth = '1450px';
  filteredList: BasicData.Position[] = [];
  stationTypes = stationTypes;
  pageConfig = {
    page: 0,
    total: 0,
  };
  subscription = new Subscription();
  constructor(
    private fb: FormBuilder,
    private modal: NzModalService,
    private basic: BasicDataService,
    private message: NzMessageService,
    private api: ApiService,
    private viewContainerRef: ViewContainerRef
  ) {
    this.subscription.add(
      basic.$fetched.subscribe(() => {
        this.setFirstCategory();
      })
    );
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
  ngAfterViewInit() {
    setTimeout(() => {
      this.tableWidth = `${this.viewContainerRef.element.nativeElement.offsetWidth - 144}px`;
    }, 100);
    this.loading = true;
    this.setFirstCategory();
  }
  setFirstCategory() {
    const firstCategory = this.categories[0];
    if (firstCategory) {
      this.selectedCategory = firstCategory.id;
      this.onSearch();
    }
  }
  onCurrentPageChange(page: number) {
    this.pageConfig.page = page;
  }
  searchFormChange(key: string) {
    this.onSearch();
  }
  changeCategory(category: number) {
    this.selectedCategory = category;
    this.onReset();
    this.onSearch();
  }
  onReset() {
    this.validateForm.reset();
  }

  handleAdd() {
    this.createModal('add');
  }

  async handleEdit(data: BasicData.Position) {
    this.createModal('edit', data);
  }
  getLineName(id: number) {
    return this.basic.getLineName(id);
  }
  handleDelete(data: BasicData.Position) {
    this.modal.confirm({
      nzClassName: 'precaution-modal',
      nzTitle: '删除' + this.typeLabel,
      nzContent: `确定要删除【${data.name}】吗？`,
      nzOkText: '确定',
      nzOkDanger: true,
      nzOnOk: async () => {
        await this.deletePosition(data.id);
        this.basic.fetchPositions().then(() => {
          this.message.success('删除成功');
          this.onSearch();
        });
      },
    });
  }
  createCategoryModal(type: 'add' | 'edit', data?: BasicData.PositionCategory): void {
    const title = type === 'add' ? `新增场所类型` : `编辑场所类型 - ` + data?.name;
    this.modal.create<PositionCategoryFormComponent, PositionCategoryFormModalData>({
      nzClassName: 'precaution-modal',
      nzTitle: title,
      nzOkText: type === 'add' ? '新增' : '修改',
      nzContent: PositionCategoryFormComponent,
      nzWidth: 500,
      nzViewContainerRef: this.viewContainerRef,
      nzData: {
        keyWord: '场所类型',
        type,
        params: {},
      },
      nzOnOk: async instance => {
        const res = await instance.submit();
        if (type === 'add') {
          delete res?.id;
          await this.onCategoryAdd(res!).finally(() => {
            instance.loading = false;
          });
          this.basic.fetchPositionCategories();
          this.basic.fetchPositions();
          instance.resetName();
          return Promise.reject();
        } else {
          await this.onCategoryEdit({
            ...data!,
            // ...res!,
          }).finally(() => {
            instance.loading = false;
          });
          this.onSearch();
        }
      },
    });
  }
  createModal(type: 'add' | 'edit', data?: BasicData.Position): void {
    const title = type === 'add' ? `新增${this.typeLabel}` : `编辑${this.typeLabel} - ` + data?.name;
    this.modal.create<PositionFormComponent, PositionFormModalData>({
      nzClassName: 'precaution-modal',
      nzTitle: title,
      nzOkText: type === 'add' ? '新增' : '修改',
      nzContent: PositionFormComponent,
      nzWidth: 500,
      nzMaskClosable: false,
      nzViewContainerRef: this.viewContainerRef,
      nzData: {
        keyWord: this.typeLabel,
        type,
        params: {
          ...data,
          lines: data?.stationLines || [],
          type: data?.stationType,
          category: data?.category || this.selectedCategory,
        },
      },
      nzOnOk: async instance => {
        const res = await instance.submit();
        if (type === 'add') {
          delete res?.id;
          await this.onAdd({
            name: res?.name!,
            stationType: res?.type!,
            category: res?.category!,
            stationLines: res?.lines!,
          }).finally(() => {
            instance.loading = false;
          });
          this.basic.fetchPositions().then(() => {
            this.message.success('新增成功');
            instance.resetName();
            this.onSearch();
          });
          return Promise.reject();
        } else {
          await this.onEdit({
            ...data!,
            name: res?.name!,
            stationType: res?.type!,
            category: res?.category!,
            stationLines: res?.lines!,
          }).finally(() => {
            instance.loading = false;
          });
          this.basic.fetchPositions().then(() => {
            this.message.success('修改成功');
            instance.resetName();
            this.onSearch();
          });
        }
      },
    });
  }
  handleAddCategory() {
    this.createCategoryModal('add');
  }

  handleEditCategory() {
    const data = this.currentCategory;
    if (!data) return;
    this.createCategoryModal('edit', data);
  }
  handleDeleteCategory() {
    const data = this.currentCategory;
    if (!data) return;
    this.modal.confirm({
      nzClassName: 'precaution-modal',
      nzTitle: '删除场所类型',
      nzContent: `确定要删除【${data.name}】吗？`,
      nzOkText: '确定',
      nzOkDanger: true,
      nzOnOk: async () => {
        await this.deleteCategory(data.id);
        this.basic.fetchPositionCategories();
      },
    });
  }
  async deleteCategory(id: number) {
    await this.api.basic.deletedPositionCategory(id);
  }
  async deletePosition(id: number) {
    await this.api.basic.deletedPosition(id);
  }
  async onAdd(data: Partial<BasicData.Position>) {
    await this.api.basic.addPosition(data);
  }
  async onCategoryAdd(data: Partial<BasicData.PositionCategory>) {
    await this.api.basic.addPositionCategory({
      ...data,
      canUpdate: 1,
    });
  }

  async onEdit(data: BasicData.Position) {
    await this.api.basic.updatePosition(data);
  }
  async onCategoryEdit(data: Partial<BasicData.PositionCategory>) {
    await this.api.basic.updatePositionCategory(data);
  }
  async onSearch() {
    const allPositions = this.basic.positions || [];
    let filteredList = allPositions.filter(p => p.category === this.selectedCategory);
    const { type, line, name } = this.validateForm.value;
    if (name) {
      filteredList = filteredList.filter(p => p.name.includes(name));
    }
    if (type) {
      filteredList = filteredList.filter(p => p.stationType === type);
    }
    if (line) {
      filteredList = filteredList.filter(p => p.stationLines.includes(line));
    }
    this.filteredList = filteredList;
    this.loading = false;
    // await this.api.basic.getPositionList();
  }
  get categories() {
    return this.basic.positionCategories || [];
  }
  get lines() {
    return this.basic.lines || [];
  }
  get currentCategory() {
    return this.categories.find(type => type.id === this.selectedCategory);
  }
  get typeLabel() {
    const typeDto = this.currentCategory;
    if (!typeDto) return '';
    return typeDto.name;
  }
  get isStation() {
    return this.typeLabel === '车站';
  }
}
