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

import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { CategoryAddComponent } from './category-add.component';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
import { LangConfigComponent } from './lang-config.component';
import { NzMessageService } from 'ng-zorro-antd/message';
import { firstValueFrom } from 'rxjs';
import { NzModalCloseComponent, NzModalService } from 'ng-zorro-antd/modal';


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

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


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

<ng-template #categoryAdd let-modal="modalRef">
  <content-category-add (onSuccess)="loadData(); modal.close();"></content-category-add>
</ng-template>

<form *ngIf="table" [formGroup]="form" class="table-scroll">
  <table class="table table-hover table-sm  table-edit">
    <thead>
      <tr>
        <th>TAG</th>
        <th i18n>启用</th>
        <th i18n>是否固定</th>
        <th 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>
          <td *ngIf="lang!='zh-CN' && lang!= 'en'">{{table.langHeaders[i]?.label}}</td>
        </ng-container>
      </tr>
    </thead>
    <tbody>
      <ng-container formArrayName="categories" *ngFor="let group of getFormData.controls; let i = index">
        <tr [formGroupName]="i">
          <th class="form-group align-middle">
            <input nz-input type="text" formControlName="tag" placeholder="">
          </th>
          <th class="form-group align-middle">
            <span class="toggle-checkbox checkbox-inline toggle-sm mrg-top-10">
              <input type="checkbox" formControlName="enabled" id="check_{{i}}">
              <label for="check_{{i}}"></label>
            </span>
          </th>
          <th class="form-group align-middle">
            <span class="toggle-checkbox checkbox-inline toggle-sm mrg-top-10">
              <input type="checkbox" formControlName="fixed" id="check_fixed_{{i}}">
              <label for="check_fixed_{{i}}"></label>
            </span>
          </th>
          <th class="form-group align-middle">
            <input nz-input type="number" formControlName="order" placeholder="">
          </th>

          <ng-container *ngFor="let lang of table.langs">
            <th *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="">
            </th>
            <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>
  </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 CategoryComponent 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.categoryTable()).then((table: any) => {
      this.table = table;
      this.table.categories.forEach(cate => {
        controls.push(this.createGroup(table.langs, cate));
      })
    })
    this.form = this.fb.group({
      categories: controls,
    });
  }

  createGroup(langs: any, cate: any) {
    let group = this.fb.group({});
    group.addControl('_id', this.fb.control(null, Validators.required));
    group.addControl('order', this.fb.control(null, Validators.required));
    group.addControl('enabled', this.fb.control(null, Validators.required));
    group.addControl('tag', this.fb.control(null, Validators.required));
    group.addControl('fixed', this.fb.control(null, Validators.required));
    langs.forEach(lang => {
      group.addControl(lang, this.fb.control(null, Validators.required))
    })
    group.reset(cate);
    return group;
  }

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

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

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


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


  modalTitle(key: string) {
    let title = '';
    switch(key) {
    case 'categoryAdd':
      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,
    })
  }

}
