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 { NzDrawerService } from 'ng-zorro-antd/drawer';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { Observable, of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { NcDictDetailComponent } from '../nc-dict-detail/nc-dict-detail.component';
import { NcDictEditorComponent } from '../nc-dict-editor/nc-dict-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-dict',
  templateUrl: './nc-dict.page.html',
  styleUrls: ['./nc-dict.page.scss']
})
export class NcDictPage implements OnInit, AfterViewInit {

  /** 系统内置模板 */
  @ViewChild('systemBuiltinTemplate') _systemBuiltinTemplate!: TemplateRef<{ $implicit?: any; source: any; extra: any; }>;
  /** 时间模板 */
  @ViewChild('timeTemplate') _timeTemplate!: TemplateRef<{ $implicit?: any; source: any; extra: any; }>;

  /** 数据字典列表 */
  _dictList: any[] = [];
  /** 数据字典额外属性 */
  _dictExtras: any = {};
  /** 数据字典总数 */
  _dictTotal: number = 0;
  /** 数据字典搜索表单 */
  _dictSearchForm!: FormGroup;
  /** 数据字典参数 */
  _dictParams = {
    page: 1,
    size: 20,
    sort: 'id,desc'
  };
  /** 数据字典加载状态 */
  _dictLoading: boolean = false;
  /** 数据字典全部选中状态 */
  _dictAllChecked: boolean = false;
  /** 数据字典模糊选中状态 */
  _dictIndeterminate: boolean = false;
  /** 数据字典字段列表 */
  _dictFieldList: Field[] = [
    { name: 'name', description: '字典名称', visible: true, width: '200px', sortKey: 'name' },
    { name: 'code', description: '字典代码', visible: true, width: '200px', sortKey: 'code' },
    { name: 'description', description: '描述', visible: true, width: '200px', sortKey: 'description' },
    { name: 'systemBuiltin', description: '系统内置', visible: true, width: '200px', sortKey: 'systemBuiltin' },
    { 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 _cancelGetDictListFn = () => { };

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

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

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

  /** 查询数据字典列表 */
  _queryDictList(): void {
    validateForm(this._dictSearchForm).subscribe(() => this._getDictList());
  }

  /** 重新查询数据字典列表 */
  _requeryDictList(): void {
    this._dictParams.page = 1;
    this._queryDictList();
  }

  /** 重置数据字典搜索表单 */
  _resetDictSearchForm(): void {
    this._dictSearchForm.reset();
    this._queryDictList();
  }

  /**
   * 拖拽数据字典字段列表
   * @param event 拖拽事件
   */
  _dropDictFieldList(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this._dictFieldList, event.previousIndex, event.currentIndex);
  }

  /** 重置数据字典字段列表 */
  _resetDictFieldList(): void {
    this._dictFieldList = this._dictFieldList
      .map(field => {
        field.visible = field.defaultVisible!;
        field.width = field.defaultWidth;
        return field;
      })
      .sort((fieldA, fieldB) => fieldA.defaultSequence! - fieldB.defaultSequence!);
  }

  /**
   * 改变数据字典字段排序
   * @param field 字段
   */
  _changeDictFieldSort(field: Field): void {
    const targetField = field;
    this._dictFieldList
      .filter(field => field !== targetField && field.sortOrder)
      .forEach(field => field.sortOrder = null);
    if (field.sortOrder) {
      this._dictParams.sort = field.sortKey + ',' + field.sortOrder.slice(0, -3);
    } else {
      this._dictParams.sort = 'id,desc';
    }
    this._requeryDictList();
  }

  /**
   * 选中所有数据字典列表
   * @param checked 选中状态
   */
  _checkAllDictList(checked: boolean): void {
    for (const id in this._dictExtras) {
      this._dictExtras[id].checked = checked;
    }
    this._dictAllChecked = checked;
    this._dictIndeterminate = false;
  }

  /** 更新数据字典选中状态 */
  _updateDictCheckStatus(): void {
    const checkedDictList = this._dictList.filter(dict => this._dictExtras[dict.id].checked);
    switch (checkedDictList.length) {
      case 0:
        this._dictAllChecked = false;
        this._dictIndeterminate = false;
        break;
      case this._dictList.length:
        this._dictAllChecked = true;
        this._dictIndeterminate = false;
        break;
      default:
        this._dictAllChecked = false;
        this._dictIndeterminate = true;
    }
  }

  /** 新增数据字典 */
  _createDict(): void {
    this._nzModalService.create({
      nzTitle: '新增数据字典',
      nzContent: NcDictEditorComponent,
      nzWidth: 520,
      nzOnOk: dictEditor => {
        return dictEditor.submit()
          .pipe(map(({ success, updated }) => {
            if (updated) {
              this._queryDictList();
            }
            return success;
          }))
          .toPromise();
      }
    });
  }

  /**
   * 编辑数据字典
   * @param dict 数据字典
   */
  _updateDict(dict: any): void {
    this._nzModalService.create({
      nzTitle: '编辑数据字典',
      nzContent: NcDictEditorComponent,
      nzComponentParams: {
        dict: dict
      },
      nzWidth: 520,
      nzOnOk: dictEditor => {
        return dictEditor.submit()
          .pipe(map(({ success, updated }) => {
            if (updated) {
              this._queryDictList();
            }
            return success;
          }))
          .toPromise();
      }
    });
  }

  /**
   * 删除数据字典
   * @param dict 数据字典
   */
  _deleteDict(dict: any): void {
    let cancelDeleteDictFn = () => { };
    this._nzModalService.confirm({
      nzTitle: '删除确认',
      nzContent: '是否确认删除数据字典 “' + dict.name + '”',
      nzOnOk: () => {
        return new Observable(subscriber => {
          const url = '@<%= getSeparatorCase(serviceName) %>/api/dicts/' + dict.id;
          const deleteDictSubscription = this._httpClient.delete(url, { responseType: 'text' })
            .pipe(map(() => {
              this._queryDictList();
              return true;
            }))
            .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
              this._nzNotificationService.error('删除数据字典失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
              return of(false);
            }))
            .subscribe(subscriber);
          cancelDeleteDictFn = () => {
            deleteDictSubscription.unsubscribe();
          };
        })
          .toPromise();
      },
      nzOnCancel: () => {
        cancelDeleteDictFn();
      }
    });
  }

  /**
   * 查看数据字典项目
   * @param dict 数据字典
   */
  _viewDictItem(dict: any): void {
    this._nzDrawerService.create({
      nzTitle: dict.name,
      nzContent: NcDictDetailComponent,
      nzContentParams: { dict },
      nzWidth: 750,
      nzBodyStyle: { padding: '0' }
    });
  }

  /** 获取数据字典列表 */
  private _getDictList(): void {
    this._cancelGetDictListFn();
    if (this._dictSearchForm.valid) {
      this._dictLoading = true;
      const completeGetDictListFn = () => {
        this._cancelGetDictListFn = () => { };
        this._dictLoading = false;
      };
      const url = '@<%= getSeparatorCase(serviceName) %>/api/dicts';
      const params: any = {
        ...this._dictSearchForm.getRawValue(),
        ...this._dictParams
      };
      for (const key in params) {
        if (!isValid(params[key])) {
          delete params[key];
        }
      }
      params.page--;
      const getDictListSubscription = this._httpClient.get<any[]>(url, { params: params, observe: 'response' })
        .pipe(mergeMap(httpResponse => {
          const dictList = httpResponse.body!;
          const dictTotal = Number(httpResponse.headers.get('X-Total-Count'));
          if (dictList.length === 0 && dictTotal > 0) {
            this._dictParams.page = Math.ceil(dictTotal / params.size);
            params.page = this._dictParams.page - 1;
            return this._httpClient.get<any[]>(url, { params: params, observe: 'response' })
              .pipe(map(httpResponse => {
                const dictList = httpResponse.body!;
                const dictTotal = Number(httpResponse.headers.get('X-Total-Count'));
                return { dictList, dictTotal };
              }));
          }
          return of({ dictList, dictTotal });
        }))
        .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.error('获取数据字典列表失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
          return of({ dictList: [], dictTotal: 0 });
        }))
        .subscribe(({ dictList, dictTotal }) => {
          completeGetDictListFn();
          const dictExtras: any = {};
          dictList.forEach(dict => {
            dictExtras[dict.id] = { checked: false };
          });
          this._dictList = dictList;
          this._dictTotal = dictTotal;
          this._dictExtras = dictExtras;
          this._dictAllChecked = false;
          this._dictIndeterminate = false;
        });
      this._cancelGetDictListFn = () => {
        getDictListSubscription.unsubscribe();
        completeGetDictListFn();
      };
    } else {
      this._dictList = [];
      this._dictTotal = 0;
      this._dictExtras = {};
      this._dictAllChecked = false;
      this._dictIndeterminate = false;
    }
  }

}
