import { Component, OnInit, ViewChild } from '@angular/core';
import { SFComponent, SFSchema, SFUISchema } from '@delon/form';
import { dateTimePickerUtil } from '@delon/util';
import { SystemService } from '../../services/system.service';

@Component({
  selector: 'app-basic-setting',
  templateUrl: './basic-setting.component.html',
  styleUrls: ['./basic-setting.component.less']
})
export class BasicSettingComponent implements OnInit {
  tabs: any[] = [];
  selectedTab: any = null;

  configList: any = [];

  constructor(public service: SystemService) {}

  ngOnInit() {
    this.getTypeList();
  }

  getTypeList() {
    this.service.request(this.service.$api_get_config_tree, { configFullKey: 'sys.config' }).subscribe((res: Array<any>) => {
      if (res?.length > 0) {
        const typeData = res.find(config => config.configFullKey === 'sys.config');
        if (typeData) {
          this.tabs = typeData.children;
          this.selectedTab = typeData.children[0];
          this.getConfigList(this.selectedTab.id);
        }
      }
    });
  }

  getConfigList(id: string) {
    this.service.request(this.service.$api_get_config_by_parent_id, { id }).subscribe((res: Array<any>) => {
      if (res?.length > 0) {
        res = res.map(item => ({
          ...item,
          remark: item.remark ? JSON.parse(item.remark) : null,
          extend: item.extend ? JSON.parse(item.extend) : [],
          itemValue: item.itemValue ? JSON.parse(item.itemValue) : item.itemValue
        }));
        this.configList = res;
      } else {
        this.configList = [];
      }
    });
  }

  changeType(type: any): void {
    this.selectedTab = type;
    this.getConfigList(this.selectedTab.id);
  }

  saveAction(params: any) {
    this.service.request(this.service.$api_update_config_batch, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('修改配置成功');
        this.getConfigList(this.selectedTab.id);
      }
    });
  }
}
