import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { AfterViewInit, Component, Input, 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 { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { NcDictItemEditorComponent } from '../nc-dict-item-editor/nc-dict-item-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-detail',
  templateUrl: './nc-dict-detail.component.html',
  styleUrls: ['./nc-dict-detail.component.scss']
})
export class NcDictDetailComponent implements OnInit, AfterViewInit {

  /** 字典 */
  @Input() dict: any = null;

  /** 数字模板 */
  @ViewChild('numberContentTemplate') _numberContentTemplate!: TemplateRef<{ $implicit: number; }>;
  /** 时间模板 */
  @ViewChild('timeTemplate') _timeTemplate!: TemplateRef<{ $implicit: string; }>;

  /** 数据字典项目列表 */
  _dictItemList: any[] = [];
  /** 数据字典项目额外属性 */
  _dictItemExtras: any = {};
  /** 数据字典项目搜索表单 */
  _dictItemSearchForm!: FormGroup;
  /** 数据字典项目加载状态 */
  _dictItemLoading: boolean = false;
  /** 数据字典项目全部选中状态 */
  _dictItemAllChecked: boolean = false;
  /** 数据字典项目模糊选中状态 */
  _dictItemIndeterminate: boolean = false;
  /** 数据字典项目字段列表 */
  _dictItemFieldList: Field[] = [
    { name: 'label', description: '字典标签', visible: true, width: '200px' },
    { name: 'value', description: '字典键值', visible: true, width: '200px' },
    { name: 'sequence', description: '顺序号', visible: true, align: 'right', width: '80px' },
    { name: 'createdBy', description: '创建人', width: '200px' },
    { name: 'createdTime', description: '创建时间', width: '200px' },
    { name: 'lastModifiedBy', description: '最后更新人', width: '200px' },
    { name: 'lastModifiedTime', description: '最后更新时间', width: '200px' }
  ];

  /** 取消获取数据字典项目列表 */
  private _cancelGetDictItemListFn = () => { };

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

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

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

  /** 查询数据字典项目列表 */
  _queryDictItemList(): void {
    validateForm(this._dictItemSearchForm).subscribe(() => this._getDictItemList());
  }

  /** 重新查询数据字典项目列表 */
  _requeryDictItemList(): void {
    this._queryDictItemList();
  }

  /** 重置数据字典项目搜索表单 */
  _resetDictItemSearchForm(): void {
    this._dictItemSearchForm.reset();
    this._queryDictItemList();
  }

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

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

  /**
   * 选中所有数据字典项目列表
   * @param checked 选中状态
   */
  _checkAllDictItemList(checked: boolean): void {
    for (const id in this._dictItemExtras) {
      this._dictItemExtras[id].checked = checked;
    }
    this._dictItemAllChecked = checked;
    this._dictItemIndeterminate = false;
  }

  /** 更新数据字典项目选中状态 */
  _updateDictItemCheckStatus(): void {
    const checkedDictItemList = this._dictItemList.filter(dictItem => this._dictItemExtras[dictItem.id].checked);
    switch (checkedDictItemList.length) {
      case 0:
        this._dictItemAllChecked = false;
        this._dictItemIndeterminate = false;
        break;
      case this._dictItemList.length:
        this._dictItemAllChecked = true;
        this._dictItemIndeterminate = false;
        break;
      default:
        this._dictItemAllChecked = false;
        this._dictItemIndeterminate = true;
    }
  }

  /** 新增数据字典项目 */
  _createDictItem(): void {
    this._nzModalService.create({
      nzTitle: '新增数据字典项目',
      nzContent: NcDictItemEditorComponent,
      nzComponentParams: {
        dictItem: { dictId: this.dict.id }
      },
      nzWidth: 520,
      nzOnOk: dictItemEditor => {
        return dictItemEditor.submit()
          .pipe(map(({ success, updated }) => {
            if (updated) {
              this._queryDictItemList();
            }
            return success;
          }))
          .toPromise();
      }
    });
  }

  /**
   * 编辑数据字典项目
   * @param dictItem 数据字典项目
   */
  _updateDictItem(dictItem: any): void {
    this._nzModalService.create({
      nzTitle: '编辑数据字典项目',
      nzContent: NcDictItemEditorComponent,
      nzComponentParams: {
        dictItem: dictItem
      },
      nzWidth: 520,
      nzOnOk: dictItemEditor => {
        return dictItemEditor.submit()
          .pipe(map(({ success, updated }) => {
            if (updated) {
              this._queryDictItemList();
            }
            return success;
          }))
          .toPromise();
      }
    });
  }

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

  /** 获取数据字典项目列表 */
  private _getDictItemList(): void {
    this._cancelGetDictItemListFn();
    if (this._dictItemSearchForm.valid) {
      this._dictItemLoading = true;
      const completeGetDictItemListFn = () => {
        this._cancelGetDictItemListFn = () => { };
        this._dictItemLoading = false;
      };
      const url = '@<%= getSeparatorCase(serviceName) %>/api/dict-items';
      const params: any = {
        dictCode: this.dict.code,
        ...this._dictItemSearchForm.getRawValue()
      };
      for (const key in params) {
        if (!isValid(params[key])) {
          delete params[key];
        }
      }
      const getDictItemListSubscription = this._httpClient.get<any[]>(url, { params })
        .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.error('获取数据字典项目列表失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
          return of([]);
        }))
        .subscribe(dictItemList => {
          completeGetDictItemListFn();
          const dictItemExtras: any = {};
          dictItemList
            .sort((dictItem1, dictItem2) => dictItem1.sequence - dictItem2.sequence)
            .forEach(dictItem => {
              dictItemExtras[dictItem.id] = { checked: false };
            });
          this._dictItemList = dictItemList;
          this._dictItemExtras = dictItemExtras;
          this._dictItemAllChecked = false;
          this._dictItemIndeterminate = false;
        });
      this._cancelGetDictItemListFn = () => {
        getDictItemListSubscription.unsubscribe();
        completeGetDictItemListFn();
      };
    } else {
      this._dictItemList = [];
      this._dictItemExtras = {};
      this._dictItemAllChecked = false;
      this._dictItemIndeterminate = false;
    }
  }

}
