import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NgCortexService } from '@ng-cortex/core';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { environment } from '../../../../../environments/environment';

/** 系统消息明细页面 */
@Component({
  selector: 'nc-system-message-detail',
  templateUrl: './nc-system-message-detail.page.html',
  styleUrls: ['./nc-system-message-detail.page.scss']
})
export class NcSystemMessageDetailPage implements OnInit {

  /** 标题 */
  title: string = '系统消息明细';

  /** 系统消息 */
  _systemMessage: any = null;
  /** 系统消息额外属性 */
  _systemMessageExtra: any = null;
  /** 系统消息加载状态 */
  _systemMessageLoading: boolean = false;

  /** 系统消息id */
  private _systemMessageId!: number;
  /** 系统消息列表路由 */
  private _systemMessageListRoute!: string;
  /** 取消获取系统消息 */
  private _cancelGetSystemMessageFn = () => { };

  constructor(
    private _httpClient: HttpClient,
    private _activatedRoute: ActivatedRoute,
    private _router: Router,
    private _ngCortexService: NgCortexService,
    private _nzNotificationService: NzNotificationService) { }

  /** 初始化后 */
  ngOnInit(): void {
    const route = this._router.url.replace(/\?.*$/, '');
    this._systemMessageListRoute = this._router.url.replace(/-detail(\?.*)?$/, '');
    this._activatedRoute.queryParams.subscribe(queryParams => {
      const systemMessageId = Number(queryParams.systemMessageId);
      if (systemMessageId) {
        if (systemMessageId !== this._systemMessageId) {
          this._systemMessageId = systemMessageId;
          this._querySystemMessage();
        }
        this._router.navigateByUrl(route);
      } else if (!this._systemMessageId) {
        this._ngCortexService.closeRoute(route, this._systemMessageListRoute);
      }
    });
    this._querySystemMessage();
  }

  /** 查询系统消息 */
  _querySystemMessage(): void {
    this._getSystemMessage().subscribe();
  }

  /** 返回系统消息列表 */
  _backToSystemMessageList(): void {
    this._router.navigateByUrl(this._systemMessageListRoute);
  }

  /** 获取系统消息 */
  private _getSystemMessage(): Observable<HttpErrorResponse | Error | null> {
    this._cancelGetSystemMessageFn();
    return new Observable(subscriber => {
      this._systemMessageLoading = true;
      const completeGetSystemMessageFn = () => {
        this._cancelGetSystemMessageFn = () => { };
        this._systemMessageLoading = false;
      };
      const url = '@' + environment.coreService + '/api/system-message-deliveries/' + this._systemMessageId;
      const getSystemMessageSubscription = this._httpClient.get<any>(url)
        .pipe(tap(systemMessage => {
          this._systemMessage = systemMessage;
          this._systemMessageExtra = {
            sender: systemMessage.sender && JSON.parse(systemMessage.sender).name
          };
          this.title = '系统消息：' + systemMessage.title;
          subscriber.next(null);
        }))
        .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.error('获取系统消息失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
          subscriber.next(httpErrorResponse);
          return of(null);
        }))
        .subscribe(() => {
          completeGetSystemMessageFn();
          subscriber.complete();
        });
      this._cancelGetSystemMessageFn = () => {
        getSystemMessageSubscription.unsubscribe();
        completeGetSystemMessageFn();
        subscriber.next(new Error('取消获取系统消息列表'));
        subscriber.complete();
      };
    });
  }

}
