import { Component, OnInit, ViewChild, inject } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { SHARED_IMPORTS } from '@shared';
import { BaseService } from 'src/app/core/utils/base.service';
import { ColDef } from 'ag-grid-community'; // Column Definition Type Interface
import { SharedModule } from '@shared';

const addTitle = '新增字典信息';
const editTitle = '修改字典信息';

@Component({
  selector: 'app-sys-data-dict',
  standalone: true,
  imports: [SharedModule, ...SHARED_IMPORTS],
  templateUrl: './data-dict.component.html'
})
export class SysDataDictComponent implements OnInit {
  private readonly http = inject(_HttpClient);
  private readonly modal = inject(ModalHelper);
  private readonly baseService = inject(BaseService);
  private readonly fb = inject(FormBuilder);
  url = `/api/main/data-dict-type`;
  searchSchema: SFSchema = {
    properties: {
      filter: {
        type: 'string',
        title: '关键字过滤'
      }
    }
  };
  @ViewChild('st') private readonly st!: STComponent;
  columns: STColumn[] = [
    {
      title: '操作',
      buttons: [{ text: '查看', click: (item: any) => this.detl(item) }]
    },
    { title: '类型代码', index: 'dataDictTypeCode' },
    { title: '类型名称', index: 'dataDictTypeName' },
    { title: '排序号', index: 'sotNo' },
    { title: '分组', index: 'dataDictTypeModule' }
  ];

  dataTypeNodes: any = [];
  dataTypeNode: any; //当前所选字典类型
  dataDictionaryTypeList: any; //数据字典类别列表
  dataDictionaryList: any;
  editVisible = false;
  detailTitle = '';
  dataInfo: any;

  public editForm = this.fb.group({
    dataDictionaryTypeValue: [],
    dataDictionaryTypeLabel: [],
    value: [],
    label: [],
    sort: [],
    valid: []
  });

  ngOnInit(): void {}

  /**
   * ocean 2023-4-17
   * 显示字典分类分组数据
   */
  treeGroupArr(list: Array<any>, field: string, fieldName: string): Array<any> {
    var fieldList: Array<any> = [],
      att: any[] = [];
    list.forEach(e => {
      if (!fieldList.some((m: any) => m.id == e[field])) {
        fieldList.push({ id: e[field], name: e[fieldName] });
      }
    });

    for (let item of fieldList) {
      var arr = list.filter(e => {
        return e[field] == item.id;
      });

      att.push({
        key: item.id,
        title: item.name,
        children: arr.map(rr => {
          return {
            title: `${rr.dataDictTypeName}（${rr.dataDictTypeCode}）`,
            key: rr.dataDictTypeCode,
            isLeaf: true
          };
        })
      });
    }

    return att;
  }

  /**
   * ocean 2023-4-17
   * 字典类型选择
   */
  dataTypeChange(e: any) {
    if (e.node.level == 1) {
      this.dataTypeNode = e.node;
      this.getDataDictionaryList(this.dataTypeNode);
    } else {
      this.dataTypeNode = null;
    }
  }

  detl(data: any) {
    this.editVisible = true;
    this.detailTitle = data.dataDictTypeName + '字典';
    this.getDataDictionaryList(data.dataDictTypeCode);
  }

  /**
   * ocean 2023-4-17
   * 新建
   */
  add() {
    if (this.dataTypeNode) {
      this.editForm.reset();
      this.editForm.patchValue({
        dataDictionaryTypeValue: this.dataTypeNode.key
      });
      this.editVisible = true;
      this.detailTitle = addTitle;
      this.dataInfo = null;
    }
  }

  /**
   * ocean 2023-4-17
   * 修改
   */
  edit(data: any) {
    data.dataDictionaryTypeValue = this.dataTypeNode.key;
    this.editForm.patchValue(data);
    this.editVisible = true;
    this.detailTitle = editTitle;
    this.dataInfo = data;
  }

  delete(data: any) {}

  /**
   * ocean 2023-4-17
   * 保存
   */
  save() {
    if (this.baseService.hasError(this.editForm)) {
      return;
    }

    const url = '/api/main/data-dictionary';
    const formValue = this.editForm.getRawValue();

    if (this.detailTitle == addTitle) {
      // 新增
      this.http.post(url, formValue).subscribe(async res => {
        this.editVisible = false;
        this.editForm.reset();
        this.baseService.showMessage({ messageId: 'C0003' });
        //this.getDataDictionaryList();
      });
    } else {
      // 修改
      this.http.put(`${url}/${this.dataInfo.id}`, formValue).subscribe(async res => {
        this.editVisible = false;
        this.editForm.reset();
        this.baseService.showMessage({ messageId: 'C0003' });
        //this.getDataDictionaryList();
      });
    }
  }

  /**
   * ocean 2023-4-17
   * 获取字典列表
   */
  getDataDictionaryList(type: any) {
    var pars = {
      skipCount: 1,
      maxResultCount: 10,
      dataDictTypeValue: type
    };

    this.http.get(`/api/main/data-dict`, pars).subscribe(res => {
      this.dataDictionaryList = res.items;
    });
  }

  colDefs: ColDef[] = [
    {
      headerName: '字典编码',
      width: 120,
      field: 'dataDictCode'
    },
    {
      headerName: '字典名称',
      field: 'dataDictName'
    },
    {
      headerName: '排序号',
      field: 'srtNo'
    }
  ];

  close() {
    this.editVisible = false;
  }
}
