import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { firstValueFrom } from 'rxjs';
import { ContentService } from './content.service';

@Component({
  selector: 'app-i18n',
  template: `

<nz-page-header nzTitle="{{title}}">
  <nz-page-header-extra>
    <button class="btn" (click)="onReset()" i18n>重置</button>
    <button class="btn" *can="['update', 'any', 'i18n']" (click)="onSave()" i18n>保存</button>
  </nz-page-header-extra>
</nz-page-header>


<form *ngIf="table" [formGroup]="form" class="table-scroll">
  <table class="table table-hover table-sm  table-edit">
    <thead>
      <tr>
        <th>zh</th>
        <th>en</th>
      </tr>
    </thead>
    <tbody>
      <ng-container formArrayName="translations" *ngFor="let group of getFormData.controls; let i = index">
        <tr [formGroupName]="i">
          <th class="form-group align-middle">
            <input nz-input type="text" formControlName="zh" placeholder="" readonly>
          </th>
          <th class="form-group align-middle" [ngClass]="{'is-changed' : group.get('en').dirty}">
            <input nz-input type="text" formControlName="en" placeholder="">
          </th>
        </tr>
      </ng-container>
    </tbody>
  </table>
</form>

  `,
  styles: [
  `
.is-changed input{
  color: darkcyan;
}

.table th,
.table td{
  background: white;
}

.table td{
  width:150px;
}


.table-scroll {
  position: relative;
  width:100%;
  z-index: 1;
  margin: auto;
  overflow: auto;
}
.table-scroll table {
  width: 100%;
  min-width: 1280px;
  margin: auto;
  border-collapse: collapse;
  border-spacing: 0;
}
.table-wrap {
  position: relative;
}
.table-scroll th,
.table-scroll td {
  vertical-align: center;
}
.table-scroll thead th {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}
/* safari and ios need the tfoot itself to be position:sticky also */
.table-scroll tfoot,
.table-scroll tfoot th,
.table-scroll tfoot td {
  position: -webkit-sticky;
  position: sticky;
  bottom: 0;
  z-index:4;
}

a:focus {
  background: red;
} /* testing links*/

th,
th:first-child {
  position: -webkit-sticky;
  position: sticky;
  left: 0;
  z-index: 2;
}
th,
thead th:first-child,
tfoot th:first-child {
  z-index: 5;
}

input{
  min-width: 100px;
}
  `
  ]
})
export class I18nComponent implements OnInit {

  title: string = 'I18N';
  table: any;
  form: FormGroup;

  constructor(
    private contentService: ContentService,
    private fb: FormBuilder,
    private message: NzMessageService,
  ) { }
  
  
  ngOnInit() {
    this.loadData();
  }

  loadData() {
    const controls = this.fb.array([]);
    firstValueFrom(this.contentService.i18nTable()).then((table: any) => {
      this.table = table;
      this.table.forEach(tran => {
        controls.push(this.createGroup(tran));
      })
    })
    this.form = this.fb.group({
      translations: controls,
    });
  }

  createGroup(tran: any) {
    let group = this.fb.group({});
    group.addControl('_id', this.fb.control(null, Validators.required));
    group.addControl('zh', this.fb.control(null, Validators.required));
    group.addControl('en', this.fb.control(null, Validators.required));
    group.reset(tran);
    return group;
  }

  get getFormData(): FormArray {
    return <FormArray>this.form.get('translations');
  }

  onReset() {
    let groups = <FormArray>this.form.get('translations');
    for (var i = 0; i < groups.controls.length; i++) {
      groups.controls[i].reset(this.table[i]);
    }
  }

  get dirty() {
    let controls: FormArray = <FormArray>this.form.get('translations');
    let dirty = [];
    for (var i = 0; i < controls.length; i++) {
      let group: FormGroup = <FormGroup>controls.at(i);
      if (group.dirty) {
        let dirtyValues: any = {};
        dirtyValues._id = group.value._id;
        Object.keys(group.controls).forEach(key => {
          let control = group.controls[key];
          if (control.dirty) {
            dirtyValues[key] = control.value;
          }
        })
        dirty.push(dirtyValues);
      }
    }
    return dirty;
  }

  onSave() {
    let data = this.dirty;
    if (!data || data.length == 0) {
      this.message.info($localize`没有更新`);
      return;
    }
    firstValueFrom(this.contentService.updateI18n(data))
      .then(res => {
        this.loadData();
        this.message.success($localize`保存成功!`);
      }).catch(err => {
        this.message.error(err.error?.message || err.message);
      });
  }


}
