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 { NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { <%= getPascalCase(name) %>EditorComponent } from '../<%= getSeparatorCase(name) %>-editor/<%= getSeparatorCase(name) %>-editor.component';

/** <%= description %>明细页面 */
@Component({
  selector: '<%= getSeparatorCase(prefix) %>-<%= getSeparatorCase(name) %>-detail',
  templateUrl: './<%= getSeparatorCase(name) %>-detail.page.html',
  styleUrls: ['./<%= getSeparatorCase(name) %>-detail.page.scss']
})
export class <%= getPascalCase(name) %>DetailPage implements OnInit {

  /** 标题 */
  title: string = '<%= description %>明细';

  /** <%= description %> */
  _<%= getCamelCase(name) %>: any = null;
  /** <%= description %>加载状态 */
  _<%= getCamelCase(name) %>Loading: boolean = false;

  /** <%= description %>id */
  private _<%= getCamelCase(name) %>Id!: number;
  /** <%= description %>列表路由 */
  private _<%= getCamelCase(name) %>ListRoute!: string;
  /** 取消获取<%= description %> */
  private _cancelGet<%= getPascalCase(name) %>Fn = () => { };

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

  /** 初始化后 */
  ngOnInit(): void {
    this._<%= getCamelCase(name) %>Id = this._activatedRoute.snapshot.params.id;
    this._<%= getCamelCase(name) %>ListRoute = this._router.url.replace(/\?.*$/, '').replace(/\/[^\/]+$/, '');
    this._query<%= getPascalCase(name) %>();
  }

  /** 查询<%= description %> */
  _query<%= getPascalCase(name) %>(): void {
    this._get<%= getPascalCase(name) %>().subscribe();
  }

  /** 返回<%= description %>列表 */
  _backTo<%= getPascalCase(name) %>List(): void {
    this._router.navigateByUrl(this._<%= getCamelCase(name) %>ListRoute);
  }

  /** 编辑<%= description %> */
  _update<%= getPascalCase(name) %>(): void {
    this._nzModalService.create({
      nzTitle: '编辑<%= description %>',
      nzContent: <%= getPascalCase(name) %>EditorComponent,
      nzComponentParams: {
        <%= getCamelCase(name) %>: this._<%= getCamelCase(name) %>
      }<% if (editorWidth) { %>,
      nzWidth: <%= editorWidth %><% } %>,
      nzOnOk: <%= getCamelCase(name) %>Editor => {
        return <%= getCamelCase(name) %>Editor.submit()
          .pipe(map(({ success, updated }) => {
            if (updated) {
              this._get<%= getPascalCase(name) %>();
            }
            return success;
          }))
          .toPromise();
      }
    });
  }

  /** 删除<%= description %> */
  _delete<%= getPascalCase(name) %>(): void {
    let cancelDelete<%= getPascalCase(name) %>Fn = () => { };
    this._nzModalService.confirm({
      nzTitle: '删除确认',
      nzContent: '是否确认删除<%= description %> “' + this._<%= getCamelCase(name) %>.<%= getCamelCase(titleFieldName) %> + '”',
      nzOnOk: () => {
        return new Observable(subscriber => {
            const url = '@<%= serviceName %>/api/<%= getPluralForm(getSeparatorCase(name)) %>/' + this._<%= getCamelCase(name) %>.id;
            const delete<%= getPascalCase(name) %>Subscription = this._httpClient.delete(url, { responseType: 'text' })
              .pipe(map(() => {
                this._ngCortexService.closeRoute(this._router.url);
                return true;
              }))
              .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
                this._nzNotificationService.error('删除<%= description %>失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
                return of(false);
              }))
              .subscribe(subscriber);
            cancelDelete<%= getPascalCase(name) %>Fn = () => {
              delete<%= getPascalCase(name) %>Subscription.unsubscribe();
            };
          })
          .toPromise();
      },
      nzOnCancel: () => {
        cancelDelete<%= getPascalCase(name) %>Fn();
      }
    });
  }

  /** 获取<%= description %> */
  private _get<%= getPascalCase(name) %>(): Observable<HttpErrorResponse | Error | null> {
    this._cancelGet<%= getPascalCase(name) %>Fn();
    return new Observable(subscriber => {
      this._<%= getCamelCase(name) %>Loading = true;
      const completeGet<%= getPascalCase(name) %>Fn = () => {
        this._cancelGet<%= getPascalCase(name) %>Fn = () => { };
        this._<%= getCamelCase(name) %>Loading = false;
      };
      const url = '@<%= serviceName %>/api/<%= getPluralForm(getSeparatorCase(name)) %>/' + this._<%= getCamelCase(name) %>Id;
      const get<%= getPascalCase(name) %>Subscription = this._httpClient.get<any>(url)
        .pipe(tap(<%= getCamelCase(name) %> => {
          this._<%= getCamelCase(name) %> = <%= getCamelCase(name) %>;
          this.title = '<%= description %>：' + <%= getCamelCase(name) %>.<%= getCamelCase(titleFieldName) %>;
          subscriber.next(null);
        }))
        .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
          this._nzNotificationService.error('获取<%= description %>失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
          subscriber.next(httpErrorResponse);
          return of(null);
        }))
        .subscribe(() => {
          completeGet<%= getPascalCase(name) %>Fn();
          subscriber.complete();
        });
      this._cancelGet<%= getPascalCase(name) %>Fn = () => {
        get<%= getPascalCase(name) %>Subscription.unsubscribe();
        completeGet<%= getPascalCase(name) %>Fn();
        subscriber.next(new Error('取消获取<%= description %>列表'));
        subscriber.complete();
      };
    });
  }

}
