import { ContentService } from './content.service';

import { Component, OnInit, TemplateRef } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { firstValueFrom } from 'rxjs';
import { NzModalService } from 'ng-zorro-antd/modal';


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

<nz-page-header nzTitle="{{title}}">
  <nz-page-header-extra>
    <button class="btn " *can="['create', 'any', 'translate']" (click)="openModal(translateAdd, modalTitle('translateAdd'))" i18n>添加翻译</button>
    <button class="btn " *can="['create', 'any', 'translate']" (click)="openModal(langConfig, modalTitle('langConfig'), 880)" i18n>配置语言</button>
    <button class="btn" (click)="onReset()" i18n>重置</button>
    <button class="btn" *can="['update', 'any', 'translate']" (click)="onSave()" i18n>保存</button>
    <button class="btn" *can="['update', 'any', 'translate']" (click)="onPublish()" i18n>发布</button>
  </nz-page-header-extra>
</nz-page-header>


<ng-template #langConfig let-modal="modalRef">
  <content-lang-config configId="translate" (onSuccess)="loadData();modal.close();"  ></content-lang-config>
</ng-template>

<ng-template #translateAdd let-modal="modalRef">
  <app-translate-add (onSuccess)="loadData(); modal.close();"></app-translate-add>
</ng-template>

<form *ngIf="table" [formGroup]="form" class="table-scroll">
  <nz-table nzSize="small" class="table table-hover table-sm  table-edit" [nzScroll]="{ x: '100%', y: '500px' }">
    <thead>
      <tr>
        <th nzWidth="250px">TAG</th>
        <th nzWidth="30px" i18n>可用</th>
        <ng-container *ngFor="let lang of table.langs; let i=index">
          <th *ngIf="lang=='zh-CN' || lang== 'en'">{{table.langHeaders[i]?.label}}</th>
          <th *ngIf="lang!='zh-CN' && lang!= 'en'">{{table.langHeaders[i]?.label}}</th>
        </ng-container>
      </tr>
    </thead>
    <tbody>
      <ng-container formArrayName="translates" *ngFor="let group of getFormData.controls; let i = index">
        <tr [formGroupName]="i">
          <td class="form-group align-middle">
            <input nz-input type="text" formControlName="tag" placeholder="">
          </td>
          <td class="form-group align-middle">
            <span class="toggle-checkbox checkbox-inline toggle-sm mrg-top-10">
              <!-- <input type="checkbox" formControlName="valid" id="check_{{i}}">
              <label for="check_{{i}}"></label> -->
              <i *ngIf="group['valid']" nz-icon [nzType]="'check-circle'" [nzTheme]="'twotone'" [nzTwotoneColor]="'#52c41a'"></i>
              <i *ngIf="!group['valid']" nz-icon [nzType]="'close-circle'" [nzTheme]="'twotone'" [nzTwotoneColor]="'#ff4500'"></i>
            </span>
          </td>
          <ng-container *ngFor="let lang of table.langs">
            <td *ngIf="lang == 'zh-CN' || lang=='en'" class="form-group align-middle"
              [ngClass]="{'is-changed' : group.get(lang).dirty}">
              <input nz-input type="text"
                [ngClass]="{ 'is-invalid':  group.get(lang).invalid, 'is-valid' : group.get(lang).valid }"
                [formControlName]="lang" placeholder="">
            </td>
            <td *ngIf="lang != 'zh-CN' && lang != 'en'" class="form-group align-middle"
              [ngClass]="{'is-changed' : group.get(lang).dirty}">
              <input nz-input type="text"
                [ngClass]="{ 'is-invalid':  group.get(lang).invalid, 'is-valid' : group.get(lang).valid }"
                [formControlName]="lang" placeholder="">
            </td>
          </ng-container>
        </tr>
      </ng-container>
    </tbody>
  </nz-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 TranslateComponent implements OnInit {

  title: string = $localize`多语翻译`;
  table: any;
  form: FormGroup;

  constructor(
    private contentService: ContentService,
    private modalService: NgbModal,
    private fb: FormBuilder,
    private message: NzMessageService,
    private modal: NzModalService,
  ) { }


  ngOnInit() {
    this.loadData();
  }

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

  createGroup(langs: any, tran: any) {
    let group = this.fb.group({});
    group.addControl('_id', this.fb.control(null, Validators.required));
    group.addControl('tag', this.fb.control(null, Validators.required));
    group.addControl('valid', this.fb.control({ value: null, disabled: true }, Validators.required));
    langs.forEach(lang => {
      group.addControl(lang, this.fb.control(null, Validators.required));
    })
    group.reset(tran);
    return group;
  }

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

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

  get dirty() {
    let controls: FormArray = <FormArray>this.form.get('translates');
    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.updateTranslate(data))
      .then(res => {
        this.loadData();
        this.message.success($localize`保存成功!`);
      }).catch(err => {
        this.message.error(err.error?.message || err.message);
      });
  }


  onPublish() {
    firstValueFrom(this.contentService.publishTranslate())
      .then(res => {
        this.message.success($localize`发布成功!`);
      }).catch(err => {
        this.message.error(err.error?.message || err.message);
      });
  }



  modalTitle(key: string) {
    let title = '';
    switch (key) {
      case 'translateAdd':
        title = $localize`添加翻译`;
        break;
      case 'langConfig':
        title = $localize`配置语言`;
        break;
      default:
        break;
    }
    return title;
  }
  openModal(content: TemplateRef<any>, title: string, width: number = 520) {
    this.modal.create({
      nzContent: content,
      nzTitle: title,
      nzFooter: null,
      nzWidth: width,
    })
  }

}
