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 { NcOptionResource, NcTableField, NgCortexService } from '@ng-cortex/core';
import { getErrorMessage, isValid, validateForm } from '@ng-cortex/utils';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { NzFormatEmitEvent, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { Observable, of } from 'rxjs';
import { catchError, map, mergeMap, tap } from 'rxjs/operators';

/** 本地文件管理页面 */
@Component({
  selector: 'nc-local-file',
  templateUrl: './nc-local-file.page.html',
  styleUrls: ['./nc-local-file.page.less']
})
export class NcLocalFilePage implements OnInit, AfterViewInit {

  /** 时间模板 */
  @ViewChild('timeTemplate') _timeTemplate!: TemplateRef<{ $implicit: any; }>;
  /** 文件大小内容模板 */
  @ViewChild('sizeBodyTemplate') _sizeBodyTemplate!: TemplateRef<{ $implicit: number; }>;

  /** 本地文件列表 */
  _localFileList: any[] = [];
  /** 本地文件额外属性 */
  _localFileExtras: { [id: string]: any; } = {};
  /** 本地文件总数 */
  _localFileTotal: number = 0;
  /** 本地文件搜索表单 */
  _localFileSearchForm!: FormGroup;
  /** 本地文件参数 */
  _localFileParams = {
    folder: null! as string,
    page: 1,
    size: 20,
    sort: 'id,desc'
  };
  /** 本地文件加载状态 */
  _localFileLoading: boolean = false;
  /** 本地文件全部选中状态 */
  _localFileAllChecked: boolean = false;
  /** 本地文件模糊选中状态 */
  _localFileIndeterminate: boolean = false;
  /** 本地文件字段列表 */
  _localFileFieldList: NcTableField[] = [
    { key: 'entityGuid', name: '实体编码', width: '320px', sortKey: 'entityGuid' },
    { key: 'name', name: '文件名称', visible: true, width: '150px', sortKey: 'name' },
    { key: 'originalName', name: '源文件名称', width: '200px', sortKey: 'originalName' },
    { key: 'format', name: '文件格式', visible: true, width: '100px', sortKey: 'format' },
    { key: 'folder', name: '文件夹', visible: true, width: '200px', sortKey: 'folder' },
    { key: 'path', name: '文件路径', width: '320px', sortKey: 'path' },
    { key: 'size', name: '文件大小', visible: true, align: 'right', width: '100px', sortKey: 'size' },
    { key: 'uploadedBy', name: '上传人', visible: true, width: '120px', sortKey: 'uploadedBy' },
    { key: 'uploadedTime', name: '上传时间', visible: true, width: '160px', sortKey: 'uploadedTime' }
  ];
  /** 文件夹选项资源 */
  _folderOptionResource!: NcOptionResource;

  /** 取消获取本地文件列表 */
  private _cancelGetLocalFileListFn = () => { };

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

  /** 初始化后 */
  ngOnInit(): void {

    // 初始化本地文件字段列表
    this._localFileFieldList.forEach((field, index) => {
      field.defaultSequence = index + 1;
      field.defaultVisible = field.visible;
      field.defaultWidth = field.width;
    });

    // 构建本地文件搜索表单
    this._localFileSearchForm = this._formBuilder.group({
      keywords: [null],
      entityGuid: [null]
    });

    // 获取文件夹选项资源
    const folderOptionUrl = 'source::@' + this._ngCortexService.coreService + '/api/local-files/folders';
    this._folderOptionResource = this._ngCortexService.getOptionResource(folderOptionUrl, {
      map: this._generateFolderTreeNodeOptionList,
      error: error => this._nzNotificationService.error('获取文件夹列表失败', getErrorMessage(error))
    });

    // 初始化较验本地文件搜索表单
    validateForm(this._localFileSearchForm, true).subscribe(() => this._getLocalFileList().subscribe());
  }

  /** 初始次渲染后 */
  ngAfterViewInit(): void {
    this._localFileFieldList.forEach(field => {
      if (/^(uploadedTime)$/.test(field.key)) {
        field.bodyTemplate = this._timeTemplate;
      }
      if (/^(size)$/.test(field.key)) {
        field.bodyTemplate = this._sizeBodyTemplate;
      }
    });
  }

  /** 查询本地文件列表 */
  _queryLocalFileList(): void {
    validateForm(this._localFileSearchForm).subscribe(() => this._getLocalFileList().subscribe());
  }

  /** 重新查询本地文件列表 */
  _requeryLocalFileList(): void {
    this._localFileParams.page = 1;
    this._queryLocalFileList();
  }

  /** 重置本地文件搜索表单 */
  _resetLocalFileSearchForm(): void {
    this._localFileSearchForm.reset();
    this._queryLocalFileList();
  }

  /**
   * 拖拽本地文件字段列表
   * @param event 拖拽事件
   */
  _dropLocalFileFieldList(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this._localFileFieldList, event.previousIndex, event.currentIndex);
  }

  /** 重置本地文件字段列表 */
  _resetLocalFileFieldList(): void {
    this._localFileFieldList = this._localFileFieldList
      .map(field => {
        field.visible = field.defaultVisible!;
        field.width = field.defaultWidth;
        return field;
      })
      .sort((fieldA, fieldB) => fieldA.defaultSequence! - fieldB.defaultSequence!);
  }

  /**
   * 改变本地文件字段排序
   * @param field 字段
   */
  _changeLocalFileFieldSort(field: NcTableField): void {
    const targetField = field;
    this._localFileFieldList
      .filter(field => field !== targetField && field.sortOrder)
      .forEach(field => field.sortOrder = null);
    if (field.sortOrder) {
      this._localFileParams.sort = field.sortKey + ',' + field.sortOrder.slice(0, -3);
    } else {
      this._localFileParams.sort = 'id,desc';
    }
    this._requeryLocalFileList();
  }

  /**
   * 选中所有本地文件列表
   * @param checked 选中状态
   */
  _checkAllLocalFileList(checked: boolean): void {
    for (const id in this._localFileExtras) {
      this._localFileExtras[id].checked = checked;
    }
    this._localFileAllChecked = checked;
    this._localFileIndeterminate = false;
  }

  /** 更新本地文件选中状态 */
  _updateLocalFileCheckStatus(): void {
    const checkedLocalFileList = this._localFileList.filter(localFile => this._localFileExtras[localFile.id].checked);
    switch (checkedLocalFileList.length) {
      case 0:
        this._localFileAllChecked = false;
        this._localFileIndeterminate = false;
        break;
      case this._localFileList.length:
        this._localFileAllChecked = true;
        this._localFileIndeterminate = false;
        break;
      default:
        this._localFileAllChecked = false;
        this._localFileIndeterminate = true;
    }
  }

  /**
   * 改变本地文件文件夹
   * @param event 事件
   */
  _changeLocalFileFolder(event: NzFormatEmitEvent): void {
    this._localFileParams.folder = event.node!.isSelected ? event.node!.key : null!;
    this._requeryLocalFileList();
  }

  /**
   * 删除本地文件
   * @param localFile 本地文件
   */
  _deleteLocalFile(localFile: any): void {
    let cancelDeleteLocalFileFn = () => { };
    this._nzModalService.confirm({
      nzTitle: '删除确认',
      nzContent: '是否确认删除本地文件 “' + localFile.name + '”',
      nzOnOk: () => {
        return new Observable(subscriber => {
          const url = '@' + this._ngCortexService.coreService + '/api/local-files/' + localFile.id;
          const deleteLocalFileSubscription = this._httpClient.delete(url, { responseType: 'text' })
            .pipe(map(() => {
              this._queryLocalFileList();
              return true;
            }))
            .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
              this._nzNotificationService.error('删除本地文件失败', getErrorMessage(httpErrorResponse));
              return of(false);
            }))
            .subscribe(subscriber);
          cancelDeleteLocalFileFn = () => {
            deleteLocalFileSubscription.unsubscribe();
          };
        })
          .toPromise();
      },
      nzOnCancel: () => {
        cancelDeleteLocalFileFn();
      }
    });
  }

  /** 获取本地文件列表 */
  private _getLocalFileList(): Observable<HttpErrorResponse | Error | void> {
    this._cancelGetLocalFileListFn();
    return new Observable(subscriber => {
      if (this._localFileSearchForm.valid) {
        this._localFileLoading = true;
        const completeGetLocalFileListFn = () => {
          this._cancelGetLocalFileListFn = () => { };
          this._localFileLoading = false;
        };
        const url = '@' + this._ngCortexService.coreService + '/api/local-files';
        const params: any = {
          ...this._localFileSearchForm.getRawValue(),
          ...this._localFileParams
        };
        for (const key in params) {
          if (!isValid(params[key])) {
            delete params[key];
          }
        }
        params.page--;
        const getLocalFileListSubscription = this._httpClient.get<any[]>(url, { params: params, observe: 'response' })
          .pipe(mergeMap(httpResponse => {
            const localFileList = httpResponse.body!;
            const localFileTotal = Number(httpResponse.headers.get('X-Total-Count'));
            if (localFileList.length === 0 && localFileTotal > 0) {
              this._localFileParams.page = Math.ceil(localFileTotal / params.size);
              params.page = this._localFileParams.page - 1;
              return this._httpClient.get<any[]>(url, { params: params, observe: 'response' })
                .pipe(map(httpResponse => {
                  const localFileList = httpResponse.body!;
                  const localFileTotal = Number(httpResponse.headers.get('X-Total-Count'));
                  return { localFileList, localFileTotal };
                }));
            }
            return of({ localFileList, localFileTotal });
          }))
          .pipe(tap(() => subscriber.next(undefined)))
          .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
            this._nzNotificationService.error('获取本地文件列表失败', getErrorMessage(httpErrorResponse));
            subscriber.next(httpErrorResponse);
            return of({ localFileList: [], localFileTotal: 0 });
          }))
          .subscribe(({ localFileList, localFileTotal }) => {
            completeGetLocalFileListFn();
            const localFileExtras: { [id: string]: any; } = {};
            localFileList.forEach(localFile => {
              localFileExtras[localFile.id] = { checked: false };
            });
            this._localFileList = localFileList;
            this._localFileTotal = localFileTotal;
            this._localFileExtras = localFileExtras;
            this._localFileAllChecked = false;
            this._localFileIndeterminate = false;
            subscriber.complete();
          });
        this._cancelGetLocalFileListFn = () => {
          getLocalFileListSubscription.unsubscribe();
          completeGetLocalFileListFn();
          subscriber.next(new Error('取消获取本地文件列表'));
          subscriber.complete();
        };
      } else {
        subscriber.next(new Error('筛选本地文件不合法'));
        subscriber.complete();
      }
    });
  }

  /**
   * 生成文件夹树形节点列表
   * @param folderList 文件夹列表
   */
  private _generateFolderTreeNodeOptionList(folderList: string[]): NzTreeNodeOptions[] {
    const folderTreeNodeOptionList: NzTreeNodeOptions[] = [];
    const folderTreeNodeOptions: { [key: string]: NzTreeNodeOptions; } = {};
    const pathList: any[] = [];
    folderList.forEach(folder => {
      const segmentList = folder.split('/').filter(segment => segment);
      segmentList.forEach((segment, index) => {
        pathList.push({
          title: segment,
          key: '/' + segmentList.slice(0, index + 1).join('/'),
          parentKey: '/' + segmentList.slice(0, index).join('/'),
          expanded: true
        });
      });
    });
    pathList.forEach(path => {
      const folderTreeNodeOption = folderTreeNodeOptions[path.key] = folderTreeNodeOptions[path.key] || {};
      folderTreeNodeOption.key = path.key;
      folderTreeNodeOption.title = path.title;
      folderTreeNodeOption.expanded = path.expanded;
      if (path.parentKey !== '/') {
        const parentFolderTreeNodeOption = folderTreeNodeOptions[path.parentKey] = folderTreeNodeOptions[path.parentKey] || {};
        if (!parentFolderTreeNodeOption.children) {
          parentFolderTreeNodeOption.children = [];
        }
        parentFolderTreeNodeOption.children.push(folderTreeNodeOption);
      } else {
        folderTreeNodeOptionList.push(folderTreeNodeOption);
      }
    });
    return folderTreeNodeOptionList;
  }

}
