import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { AfterViewInit, Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { isValid, validateForm } from '@ng-cortex/utils';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { Observable, of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { NcUserEditorComponent } from '../nc-user-editor/nc-user-editor.component';

/** 字段接口 */
interface Field {
  /** 名称 */
  name: string;
  /** 描述 */
  description?: string;
  /** 可见状态 */
  visible?: boolean;
  /** 对齐 */
  align?: 'left' | 'right' | 'center';
  /** 宽度 */
  width?: string;
  /** 排序键 */
  sortKey?: string;
  /** 排序状态 */
  sortOrder?: string | null;
  /** 默认排序 */
  defaultSequence?: number;
  /** 默认可见状态 */
  defaultVisible?: boolean;
  /** 默认宽度 */
  defaultWidth?: string;
  /** 标题模板 */
  titleTemplate?: TemplateRef<any>;
  /** 内容模板 */
  contentTemplate?: TemplateRef<{ $implicit?: any; source?: any; extra?: any; }>;
}

/** 用户管理页面 */
@Component({
  selector: 'nc-user',
  templateUrl: './nc-user.page.html',
  styleUrls: ['./nc-user.page.scss']
})
export class NcUserPage implements OnInit, AfterViewInit {

  /** 启用模板 */
  @ViewChild('enabledTemplate') _enabledTemplate!: TemplateRef<{ $implicit: boolean; }>;
  /** 角色列表模板 */
  @ViewChild('roleListTemplate') _roleListTemplate!: TemplateRef<{ $implicit: any[]; }>;
  /** 时间模板 */
  @ViewChild('timeTemplate') _timeTemplate!: TemplateRef<{ $implicit: string; }>;

  /** 机构列表 */
  _organizationList: any[] = [];
  /** 机构树形选项列表 */
  _organizationTreeNodeOptionList: any[] = [];
  /** 机构加载状态 */
  _organizationLoading: boolean = false;
  /** 用户列表 */
  _userList: any[] = [];
  /** 用户额外属性 */
  _userExtras: any = {};
  /** 用户总数 */
  _userTotal: number = 0;
  /** 用户搜索表单 */
  _userSearchForm!: FormGroup;
  /** 用户参数 */
  _userParams = {
    page: 1,
    size: 20,
    sort: 'id,desc'
  };
  /** 用户加载状态 */
  _userLoading: boolean = false;
  /** 用户全部选中状态 */
  _userAllChecked: boolean = false;
  /** 用户模糊选中状态 */
  _userIndeterminate: boolean = false;
  /** 用户字段列表 */
  _userFieldList: Field[] = [
    { name: 'account', description: '账号', visible: true, width: '200px', sortKey: 'account' },
    { name: 'name', description: '姓名', visible: true, width: '200px', sortKey: 'name' },
    { name: 'mobileNumber', description: '手机号', visible: true, width: '200px', sortKey: 'mobileNumber' },
    { name: 'identityCardNumber', description: '身份证号', width: '200px', sortKey: 'identityCardNumber' },
    { name: 'gender', description: '性别', width: '200px', sortKey: 'gender' },
    { name: 'email', description: '邮箱', visible: true, width: '200px', sortKey: 'email' },
    { name: 'wechatUnionId', description: '微信unionId', width: '200px', sortKey: 'wechatUnionId' },
    { name: 'avatarUrl', description: '头像地址', width: '200px', sortKey: 'avatarUrl' },
    { name: 'enabled', description: '有效状态', visible: true, width: '200px', sortKey: 'enabled' },
    { name: 'roles', description: '角色', visible: true, width: '320px' },
    { name: 'createdBy', description: '创建人', width: '200px', sortKey: 'createdBy' },
    { name: 'createdTime', description: '创建时间', width: '200px', sortKey: 'createdTime' },
    { name: 'lastModifiedBy', description: '最后更新人', width: '200px', sortKey: 'lastModifiedBy' },
    { name: 'lastModifiedTime', description: '最后更新时间', width: '200px', sortKey: 'lastModifiedTime' }
  ];

  /** 取消获取用户列表 */
  private _cancelGetUserListFn = () => { };

  constructor(
    private _formBuilder: FormBuilder,
    private _httpClient: HttpClient,
    private _nzModalService: NzModalService,
    private _nzNotificationService: NzNotificationService) { }

  /** 初始化后 */
  ngOnInit(): void {
    this._userFieldList.forEach((field, index) => {
      field.defaultSequence = index + 1;
      field.defaultVisible = field.visible;
      field.defaultWidth = field.width;
    });
    this._userSearchForm = this._formBuilder.group({
      organizationId: [null],
      keywords: [null]
    });
    validateForm(this._userSearchForm, true).subscribe(() => {
      this._getUserList();
      this._getOrganizationList();
    });
  }

  /** 初始次渲染后 */
  ngAfterViewInit(): void {
    this._userFieldList.forEach(field => {
      if (/^enabled$/.test(field.name)) {
        field.contentTemplate = this._enabledTemplate;
      }
      if (/^roles$/.test(field.name)) {
        field.contentTemplate = this._roleListTemplate;
      }
      if (/^(createdTime|lastModifiedTime)$/.test(field.name)) {
        field.contentTemplate = this._timeTemplate;
      }
    });
  }

  /** 查询用户列表 */
  _queryUserList(): void {
    validateForm(this._userSearchForm).subscribe(() => this._getUserList());
  }

  /** 重新查询用户列表 */
  _requeryUserList(): void {
    this._userParams.page = 1;
    this._queryUserList();
  }

  /** 重置用户搜索表单 */
  _resetUserSearchForm(): void {
    this._userSearchForm.reset();
    this._queryUserList();
  }

  /**
   * 拖拽用户字段列表
   * @param event 拖拽事件
   */
  _dropUserFieldList(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this._userFieldList, event.previousIndex, event.currentIndex);
  }

  /** 重置用户字段列表 */
  _resetUserFieldList(): void {
    this._userFieldList = this._userFieldList
      .map(field => {
        field.visible = field.defaultVisible!;
        field.width = field.defaultWidth;
        return field;
      })
      .sort((fieldA, fieldB) => fieldA.defaultSequence! - fieldB.defaultSequence!);
  }

  /**
   * 改变用户字段排序
   * @param field 字段
   */
  _changeUserFieldSort(field: Field): void {
    const targetField = field;
    this._userFieldList
      .filter(field => field !== targetField && field.sortOrder)
      .forEach(field => field.sortOrder = null);
    if (field.sortOrder) {
      this._userParams.sort = field.sortKey + ',' + field.sortOrder.slice(0, -3);
    } else {
      this._userParams.sort = 'id,desc';
    }
    this._requeryUserList();
  }

  /**
   * 选中所有用户列表
   * @param checked 选中状态
   */
  _checkAllUserList(checked: boolean): void {
    for (const id in this._userExtras) {
      this._userExtras[id].checked = checked;
    }
    this._userAllChecked = checked;
    this._userIndeterminate = false;
  }

  /** 更新用户选中状态 */
  _updateUserCheckStatus(): void {
    const checkedUserList = this._userList.filter(user => this._userExtras[user.id].checked);
    switch (checkedUserList.length) {
      case 0:
        this._userAllChecked = false;
        this._userIndeterminate = false;
        break;
      case this._userList.length:
        this._userAllChecked = true;
        this._userIndeterminate = false;
        break;
      default:
        this._userAllChecked = false;
        this._userIndeterminate = true;
    }
  }

  /** 新增用户 */
  _createUser(): void {
    this._nzModalService.create({
      nzTitle: '新增用户',
      nzContent: NcUserEditorComponent,
      nzWidth: 520,
      nzOnOk: userEditor => {
        return userEditor.submit()
          .pipe(map(({ success, updated }) => {
            if (updated) {
              this._queryUserList();
            }
            return success;
          }))
          .toPromise();
      }
    });
  }

  /**
   * 编辑用户
   * @param user 用户
   */
  _updateUser(user: any): void {
    this._nzModalService.create({
      nzTitle: '编辑用户',
      nzContent: NcUserEditorComponent,
      nzComponentParams: {
        user: user
      },
      nzWidth: 520,
      nzOnOk: userEditor => {
        return userEditor.submit()
          .pipe(map(({ success, updated }) => {
            if (updated) {
              this._queryUserList();
            }
            return success;
          }))
          .toPromise();
      }
    });
  }

  /**
   * 删除用户
   * @param user 用户
   */
  _deleteUser(user: any): void {
    let cancelDeleteUserFn = () => { };
    this._nzModalService.confirm({
      nzTitle: '删除确认',
      nzContent: '是否确认删除用户 “' + user.name + '”',
      nzOnOk: () => {
        return new Observable(subscriber => {
          const url = '@<%= getSeparatorCase(serviceName) %>/api/users/' + user.id;
          const deleteUserSubscription = this._httpClient.delete(url, { responseType: 'text' })
            .pipe(map(() => {
              this._queryUserList();
              return true;
            }))
            .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
              this._nzNotificationService.error('删除用户失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
              return of(false);
            }))
            .subscribe(subscriber);
          cancelDeleteUserFn = () => {
            deleteUserSubscription.unsubscribe();
          };
        })
          .toPromise();
      },
      nzOnCancel: () => {
        cancelDeleteUserFn();
      }
    });
  }

  /** 获取机构列表 */
  private _getOrganizationList(): void {
    this._organizationLoading = true;
    const url = '@<%= getSeparatorCase(serviceName) %>/api/organizations';
    this._httpClient.get<any[]>(url)
      .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
        this._nzNotificationService.error('获取机构列表失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        return of([]);
      }))
      .subscribe(organizationList => {
        this._organizationList = organizationList.sort((organization1, organization2) => organization1.sequence - organization2.sequence);
        this._organizationLoading = false;
        this._generateOrganizationTreeNodeList();
      });
  }

  /** 生成机构树形选项列表 */
  private _generateOrganizationTreeNodeList(): void {
    const organizationTreeNodeOptionList: NzTreeNodeOptions[] = [];
    const organizationTreeNodeOptions: any = {};
    this._organizationList.forEach(organization => {
      const organizationTreeNodeOption: NzTreeNodeOptions = organizationTreeNodeOptions[organization.id] = organizationTreeNodeOptions[organization.id] || {};
      organizationTreeNodeOption.key = organization.id.toString();
      organizationTreeNodeOption.title = organization.name;
      if (!organizationTreeNodeOption.children) {
        organizationTreeNodeOption.isLeaf = true;
      }
      if (organization.parentId) {
        const parentOrganizationTreeNodeOption: NzTreeNodeOptions = organizationTreeNodeOptions[organization.parentId] = organizationTreeNodeOptions[organization.parentId] || {};
        if (!parentOrganizationTreeNodeOption.children) {
          delete parentOrganizationTreeNodeOption.isLeaf;
          parentOrganizationTreeNodeOption.children = [];
        }
        parentOrganizationTreeNodeOption.children.push(organizationTreeNodeOption);
      } else {
        organizationTreeNodeOptionList.push(organizationTreeNodeOption);
      }
    });
    this._organizationTreeNodeOptionList = organizationTreeNodeOptionList;
  }

  /** 获取用户列表 */
  private _getUserList(): void {
    this._cancelGetUserListFn();
    if (this._userSearchForm.valid) {
      this._userLoading = true;
      const completeGetUserListFn = () => {
        this._cancelGetUserListFn = () => { };
        this._userLoading = false;
      };
      const url = '@<%= getSeparatorCase(serviceName) %>/api/users';
      const params: any = {
        ...this._userSearchForm.getRawValue(),
        ...this._userParams
      };
      for (const key in params) {
        if (!isValid(params[key])) {
          delete params[key];
        }
      }
      params.page--;
      const getUserListSubscription = this._httpClient.get<any[]>(url, { params: params, observe: 'response' })
        .pipe(mergeMap(httpResponse => {
          const userList = httpResponse.body!;
          const userTotal = Number(httpResponse.headers.get('X-Total-Count'));
          if (userList.length === 0 && userTotal > 0) {
            this._userParams.page = Math.ceil(userTotal / params.size);
            params.page = this._userParams.page - 1;
            return this._httpClient.get<any[]>(url, { params: params, observe: 'response' })
              .pipe(map(httpResponse => {
                const userList = httpResponse.body!;
                const userTotal = Number(httpResponse.headers.get('X-Total-Count'));
                return { userList, userTotal };
              }));
          }
          return of({ userList, userTotal });
        }))
        .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.error('获取用户列表失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
          return of({ userList: [], userTotal: 0 });
        }))
        .subscribe(({ userList, userTotal }) => {
          completeGetUserListFn();
          const userExtras: any = {};
          userList.forEach(user => {
            userExtras[user.id] = { checked: false };
          });
          this._userList = userList;
          this._userTotal = userTotal;
          this._userExtras = userExtras;
          this._userAllChecked = false;
          this._userIndeterminate = false;
        });
      this._cancelGetUserListFn = () => {
        getUserListSubscription.unsubscribe();
        completeGetUserListFn();
      };
    } else {
      this._userList = [];
      this._userTotal = 0;
      this._userExtras = {};
      this._userAllChecked = false;
      this._userIndeterminate = false;
    }
  }

}
