import { Injectable } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import * as FileSaver from 'file-saver';
import { NzModalService } from 'ng-zorro-antd/modal';

@Injectable({
  providedIn: 'root',
})
export class EAFileUtil {
  constructor(private modal: NzModalService, private http: _HttpClient) {}

  /**
   * 保存文件
   * @param content 需要保存的内容
   * @param filename 文件名
   * @param confirm 显示确认框
   */
  save(content: any, filename: string, confirm: boolean = true): void {
    const blob = new Blob([JSON.stringify(content)], { type: 'text/plain;charset=utf-8' });
    if (confirm === true) {
      this.modal.confirm({
        nzTitle: '<i>文件下载确认</i>',
        nzContent: `<b>是否下载文件：<u><i>${filename}</i></u> ？</b>`,
        nzOnOk: () => {
          FileSaver.saveAs(blob, filename);
        },
      });
    } else {
      FileSaver.saveAs(blob, filename);
    }
  }

  /**
   * @param url 接口地址
   * @param body post请求参数
   * @param params get请求参数
   * @method 请求方法
   */
  download(url: string, body: any, params: any, method: 'POST' | 'GET' = 'POST'): void {
    if (method === 'POST') {
      this.http
        .post(url, body, params, {
          responseType: 'blob',
          observe: 'response',
        })
        .subscribe((res) => {
          this.saveBlob(res);
        });
    } else if (method === 'GET') {
      this.http
        .get(url, params, {
          responseType: 'blob',
          observe: 'response',
        })
        .subscribe((res) => {
          this.saveBlob(res);
        });
    }
  }

  /**
   * 创建blob对象，并利用浏览器打开url进行下载
   * @param data 文件流数据
   */
  private saveBlob(res: any): void {
    const disp = res.headers.get('Content-Disposition');
    const blob = new Blob([res.body], { type: 'text/plain;charset=utf-8' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    const fileName = disp.split(';')[1].split('=')[1];
    a.href = url;
    a.download = decodeURI(fileName);
    a.click();
    window.URL.revokeObjectURL(url);
  }
}
