import { Location } from '@angular/common';
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FilterItem, FilterType } from 'src/app/lib/pager/pager-filter.component';
import { AngularUtils } from 'src/app/lib/utils/angular-utils';
import { SysService } from './sys.service';

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


  
  <ng-template #userCreate let-modal="modalRef">
    <sys-user-create (onSuccess)="modal.close(); refresh();" ></sys-user-create>
  </ng-template>


  <nz-page-header i18n-nzTitle nzTitle="用户管理">
    <nz-page-header-extra>
      <button *can="['create', 'own', 'user']" class="btn" (click)="openModal(userCreate, modalTitle('userCreate'))">
        <i class="fal fa-user-plus"></i>
        <ng-container i18n>创建账号</ng-container></button>
    </nz-page-header-extra>
  </nz-page-header>



  <cg-pager 
    remoteHeaderUrl="/napi/web/user/pager/headers"
    remoteUrl="/napi/web/user/pager"
    [listTemplate]="listTpl"
    [filterConfig]="filterConfigs"
    [inputSort]="sort"
    [debug]="false"
    [showOrder]="false"
    [refresh]="refreshTrigger"
    defaultOrderBy="username"
  ></cg-pager>

  <ng-template #listTpl let-list="list" let-headers="headers" >
    <cg-pager-table  [headers]="headers" [list]="list?.data" [cellRenders]="{roles, epgs, createBy, tableOperations, disabled}" (onSort)="sort=$event" > </cg-pager-table> 
  </ng-template>

  <ng-template #roles let-item="item" >
    <nz-tag nzColor="default" *ngFor="let role of item.roles" >{{role.name}}</nz-tag>
  </ng-template>

  <ng-template #epgs let-item="item" >
    <nz-tag nzColor="default" *ngFor="let epg of item.epgs" >{{epg}}</nz-tag>
  </ng-template>

  <ng-template #createBy let-item="item" >
    {{item.createBy?.username}}
  </ng-template>

  <ng-template #disabled let-item="item" >
    <span *ngIf="item.disabled" class="badge bg-warning text-dark" i18n>停用</span>
    <span *ngIf="!item.disabled" class="badge bg-success" i18n>正常</span>
  </ng-template>


  <ng-template #tableOperations let-item="item" >
    &nbsp;
    <ng-container *can="['update', 'own', 'user', item.isOwner]" >
      <button class="btn  btn-sm me-1"  (click)="openModal(userEdit, modalTitle('userEdit'))" i18n>编辑</button>
      <button class="btn  btn-sm me-1" cgOpButton i18n-confirmContent confirmContent="确定要重置{{item.username}}的密码? 用户将需要重新登录, 新的登录信息会自动复制到剪贴板" [operation]="sys.resetPassword(item._id)" (onSuccess)="onPasswordReset($event)" >
        <i class="fal fa-sync"></i><ng-container i18n>重置密码</ng-container></button>
    </ng-container>

    <ng-container *can="['delete', 'own', 'user', item.isOwner]" >
      <button *ngIf="!item.disabled" class="btn  btn-sm me-1" cgOpButton  i18n-confirmContent confirmContent="确定要停用{{item.username}}这个账户?" [operation]="sys.disableUser(item.id)" (onSuccess)="refresh()"  >
        <i class="fal fa-user-slash"></i><ng-container i18n>停用</ng-container> </button>
      <button *ngIf="item.disabled" class="btn  btn-sm me-1" cgOpButton  i18n-confirmContent confirmContent="确定要启用{{item.username}}这个账户?" [operation]="sys.enableUser(item.id)" (onSuccess)="refresh()"  >
        <i class="fal fa-redo"></i><ng-container i18n>启用</ng-container> </button>
    </ng-container>

    <ng-template #userEdit let-modal="modalRef">
      <sys-user-edit [id]="item._id" (onSuccess)="modal.close(); refresh();" ></sys-user-edit>
    </ng-template>

  </ng-template>


  `,
  styles: [
    `
    :host {
      padding:10px;
      display:block;
    }

    `
  ]
})
export class UsersComponent implements OnInit {

  sort: any;
  refreshTrigger: any;

  refresh() {
    this.refreshTrigger = Math.random();
  }

  constructor(
    private router: Router,
    private modal: NzModalService,
    private message: NzMessageService,
    public sys: SysService,
    private loc: Location,
  ) { }

  filterConfigs: FilterItem[] = [
    {
      data: 'roles',
      filterType: FilterType.select,
      mode: 'multiple',
      title: $localize`角色`,
      optionsUrl: '/napi/web/role/options',
      span: 3,
      fullWidth: true,
    },
    {
      data: 'dateSignup',
      filterType: FilterType.dateRange,
      title: $localize`创建时间`,
      span: 2,
    },
    {
      data: 'disabled',
      filterType: FilterType.select,
      options: [
        { label: $localize`停用`, value: true },
        { label: $localize`正常`, value: false },
      ],
      title: $localize`状态`,
      span: 2,
    }



  ];

  modalTitle(key: string) {
    let title = '';
    switch(key) {
    case 'userCreate':
      title = $localize`创建账号`;
      break;
    case 'userEdit':
      title = $localize`修改信息`;
      break;
    default:
      break;
    }
    return title;
  }

  openModal(content: TemplateRef<any>, title: string) {
    this.modal.create({
      nzContent: content,
      nzTitle: title,
      nzFooter: null,
      nzMaskClosable: false,
    });
  }

  onPasswordReset(resp) {
    //console.log('onPasswordReset:', resp);
    this.copyToClipboard(resp);
  }

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



  ngOnInit() {
  }
}

