import { Component, OnInit, ViewChild } from '@angular/core';
import { SFComponent, SFSchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { SystemService } from '../../services/system.service';
@Component({
  selector: 'app-agreement-config-components-base',
  styleUrls: ['./agreement-config.component.less'],
  templateUrl: './agreement-config.component.html'
})
export class AgreementConfigComponentsBaseComponent implements OnInit {
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  schema1!: SFSchema;
  isUpdate = false;
  tabItem: any = {};
  tabs: any[] = [];

  constructor(private service: SystemService) {}

  ngOnInit() {
    this.loadAgreement();
    this.initSF();
  }

  initSF(data?: any) {
    this.schema1 = {
      properties: {
        content: {
          type: 'string',
          title: '',
          ui: {
            widget: 'tinymce',
            loadingTip: 'loading...',
            config: {
              height: 650
            }
          },
          default: data?.agreementContent || ''
        }
      }
    };
  }

  changeType(item: any): void {
    this.isUpdate = false;
    this.tabItem = item;
  }

  loadAgreement(type?: number) {
    this.service.request(`${this.service.$api_get_agreement_page}`, { pageIndex: 1, pageSize: 99 }).subscribe(res => {
      if (res) {
        res.records = res.records.map((item: any) => ({ ...item, agreementContent: decodeURIComponent(item.agreementContent) }));
        this.tabs = res.records;
        if (type) {
          this.tabItem = res.records.find((i: any) => i.type === type);
        } else {
          this.tabItem = res.records?.[0];
        }
      }
    });
  }

  update() {
    this.isUpdate = true;
    this.initSF(this.tabItem);
  }
  save() {
    const params = {
      id: this.tabItem.id,
      agreementContent: encodeURIComponent(this.sf?.value.content),
      type: this.tabItem.type,
      agreementName: this.tabItem.agreementName
    };
    this.isUpdate = false;
    this.service.request(`${this.service.$api_update_agreement}`, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('保存成功');
        this.isUpdate = false;
        this.loadAgreement(this.tabItem.type);
      }
    });
  }

  cancel() {
    this.isUpdate = false;
  }
}
