import { Location } from '@angular/common';
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { AngularUtils } from 'src/app/lib/utils/angular-utils';
import { FormUtils } from 'src/app/lib/utils/form-utils';
import { SysService } from './sys.service';

@Component({
  selector: 'sys-user-edit',
  template: `

  <nz-spin [nzSpinning]="isLoading">

    <form [@.disabled]="true" nz-form  [formGroup]="form" (ngSubmit)="submit()"  autocomplete="off" >

      <ng-template #errorTpl let-control>
        <ng-container *ngIf="control.hasError('error')">{{control.getError('error')}}</ng-container>
      </ng-template>
    

      <nz-form-item>
        <nz-form-control>
          <nz-input-group nzPrefixIcon="user">
            <input nz-input  formControlName="username" i18n-placeholder placeholder="用户名">
          </nz-input-group>
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-control>
          <nz-input-group nzPrefixIcon="idcard">
            <input nz-input formControlName="name" i18n-placeholder placeholder="姓名">
          </nz-input-group>
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-control  [nzErrorTip]="errorTpl">
          <nz-input-group nzPrefixIcon="phone">
            <input nz-input formControlName="phone" i18n-placeholder placeholder="电话">
          </nz-input-group>
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-control [nzErrorTip]="errorTpl">
          <nz-input-group nzPrefixIcon="mail" >
            <input nz-input formControlName="email" i18n-placeholder placeholder="邮箱">
          </nz-input-group>
        </nz-form-control>
      </nz-form-item>


      <nz-form-item>
        <nz-form-control>
          <nz-select formControlName="roles" nzMode="multiple" [nzOptions]="roleOptions" i18n-nzPlaceHolder nzPlaceHolder="角色(可选)" nzAllowClear>
          </nz-select>
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-control>
          <nz-select formControlName="epgs" nzMode="multiple" [nzOptions]="epgOptions" i18n-nzPlaceHolder nzPlaceHolder="epg(可选)" nzAllowClear>
          </nz-select>
        </nz-form-control>
      </nz-form-item>

      <div>
        <button nz-button nzType="primary" nzBlock type="submit" [disabled]="!form.dirty" i18n>保存</button>
      </div>

    </form>
  </nz-spin>

  <!--
  <p>dirty: {{dirty | json}}</p>
  <p>form.dirty : {{form.dirty}}</p>
  <p>{{form.value|json}}</p>
  <p>valid?:{{ form.valid }}</p>
  <p>invalid?:{{ form.invalid }}</p>
  -->


  `,
  styles: [
  ]
})
export class UserEditComponent implements OnInit {

  form: FormGroup;
  roleOptions: any[] = [];
  epgOptions: any[] = [];
  private _isLoading: boolean = false;
  public get isLoading(): boolean {
    return this._isLoading;
  }
  public set isLoading(value: boolean) {
    this._isLoading = value;
    value ? this.form.disable() : this.form.enable();
    this.form.controls['username'].disable();
  }

  @Output() onSuccess = new EventEmitter<any>();
  @Output() onError = new EventEmitter<any>();

  private _id: string;
  public get id(): string {
    return this._id;
  }
  @Input() set id(val: string) {
    this._id = val;


    this.form = this.fb.group({
      username: [null, [Validators.required],],
      name: [null, [Validators.required]],
      email: [null, [Validators.required, Validators.email], this.sys.validateEmail(this.id).bind(this.sys)],
      phone: [null, [Validators.required, Validators.pattern(/^[\s]*1[\d]{10}[\s]*$/)], this.sys.validatePhone(this.id).bind(this.sys)],
      roles: [[]],
      epgs: [[]],
    });


    this.isLoading = true;

    this.sys.getUser(val)
      .then(resp => {
        this.form.reset(resp);
        this.isLoading = false;
      })
      .catch(err => this.message.error(err.error?.message || err.message))

  }



  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private modal: NzModalService,
    private sys: SysService,
    private loc: Location,
  ) {
    this.sys.roleOptions()
      .then(res => { 
        this.roleOptions = res; 
      })
      .catch(err => this.message.error(err.error?.message || err.message))

    this.sys.epgOptions()
      .then(res => {
        this.epgOptions = res;
      })
      .catch(err => this.message.error(err.error?.message || err.message))
  }


  submit() {
    if (!this.form.valid) {
      FormUtils.markAsDirty(this.form);
      return;
    }

    this.isLoading = true;
    this.sys.updateUser(this.id, this.form.value)
      .subscribe({
        next: () => {
          this.message.success($localize`修改成功`);
          this.onSuccess.emit(this.form.value);
          this.isLoading = false;
        },
        error: err => {
          this.message.error(err.error?.message || err.message);
          this.onError.emit(err);
          this.isLoading = false;
        },
      })
  }


  get dirty() { return FormUtils.getDirtyValues(this.form) }



  ngOnInit(): void {
    console.log('control', this.form.controls['username']);
    this.form.controls['username'].disable();
  }

}
