import { Location } from '@angular/common';
import { Component, EventEmitter, 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-create',
  template: `

  <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 [nzErrorTip]="errorTpl">
        <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="lock" [nzSuffix]="suffix">
          <input nz-input formControlName="password"  autocomplete="new-password"  i18n-placeholder placeholder="密码">
          <ng-template #suffix>
            <button nz-button nzSize="small" [disabled]="isLoading" type="button" (click)="form.controls['password'].setValue(randomPassword())" i18n>随机密码</button>
          </ng-template>
        </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>

    <div>
      <button nz-button nzType="primary" nzBlock type="submit" i18n>创建</button>
    </div>

  </form>

  <!--
  <p>{{form.value|json}}</p>
  <p>valid?:{{ form.valid }}</p>
  <p>invalid?:{{ form.invalid }}</p>
-->
  `,
  styles: [
  ]
})
export class UserCreateComponent implements OnInit {

  form: FormGroup;
  roleOptions: 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();
  }

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


  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private modal: NzModalService,
    private sys: SysService,
    private loc: Location,
  ) {
    this.form = this.fb.group({
      username: [null, [Validators.required, Validators.minLength(5)], this.sys.validateUsername().bind(this.sys)],
      name: [null, [Validators.required]],
      email: [null, [Validators.required, Validators.email], this.sys.validateEmail().bind(this.sys)],
      phone: [null, [Validators.required, Validators.pattern(/^[\s]*1[\d]{10}[\s]*$/)], this.sys.validatePhone().bind(this.sys) ],
      roles: [[]],
      password: [null, [Validators.required, Validators.minLength(8)]],
    });

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


  randomPassword() {
    let wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$';
    let pass = Array(20).fill(0).map(i => {
      return wishlist.charAt(Math.floor(Math.random() * wishlist.length))
    }).join('');
    console.log('pass', pass);
    return pass;
  }


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

    this.isLoading = true;
    this.sys.createUser(this.form.value)
      .then(() => {
        this.message.success($localize`用户创建成功`);
        this.copyToClipboard();
        this.onSuccess.emit(this.form.value);
      })
      .catch(err => {
        this.message.error(err.error?.message || err.message);
        this.onError.emit(err);
      })
      .then(() => this.isLoading = false);
  }


  copyToClipboard() {
    const { name, username, password } = this.form.value;
    const appUrl = AngularUtils.getAppUrl(this.loc);
    let info = $localize`${name}的登录信息 \n用户名: ${username} \n密码: ${password} \n地址: ${appUrl}`;
    window.navigator.clipboard.writeText(info);
    this.message.success($localize`登陆信息已经复制到剪贴板!`);
  }

  

  ngOnInit(): void {
  }

}
