import { DOCUMENT } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, Inject, OnInit } from '@angular/core';
import { BixiI18nService } from '@bixi/core/i18n';
import { IICON, IICONCate, IIconData } from '@shared/models/icons';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'icons-box',
  templateUrl: './icons-box.component.html',
  styleUrls: ['./icons-box.component.less']
})
export class IconsBoxComponent implements OnInit {
  prefix = `bixi`;
  icons: IICONCate[] = [];
  displayIcons: IICONCate[] = [];
  categories: string[] = [];
  search = '';
  theme = 'outline';
  modalVisible = false;
  selectedIcon: IICON = {
    type: '',
    path: '',
    copyCode: '',
    copySvgPath: '',
    text: ''
  };
  order = ['robot', 'ai', 'data', 'file', 'direction', 'suggest', 'edit', 'chart', 'logo', 'common'];

  // tslint:disable-next-line: no-any
  constructor(private http: HttpClient, @Inject(DOCUMENT) private dom: any, private i18n: BixiI18nService, private messageService: NzMessageService) {
  }

  ngOnInit() {
    this.getAllIcons();
  }

  getAllIcons() {
    this.http.get<IIconData>(`assets/icon-data.json`).subscribe(res => {
      const ret: IICONCate[] = [];
      for (const iconType in res.data) {
        if (res.data.hasOwnProperty(iconType)) {
          for (const iconCate in res.data[iconType]) {
            if (res.data[iconType].hasOwnProperty(iconCate)) {
              const icons: IICON[] = [];
              res.data[iconType][iconCate].forEach(e => {
                icons.push({
                  type: iconType,
                  path: `icons/${this.prefix}/${iconType}/${iconCate}:${e.replace('.svg', '')}`,
                  copySvgPath: `icons/${this.prefix}/${iconType}/${iconCate}/${e.replace('.svg', '')}`,
                  copyCode: `<i nz-icon nzType="${this.prefix}/${iconType}/${iconCate}:${e.replace('.svg', '')}"></i>`,
                  text: e.replace('.svg', '')
                });
              });
              ret.push({
                cate: this.getCateText(iconCate),
                cateCode: iconCate,
                icons
              });
            }
          }
        }
      }
      this.icons = this.ordered(ret, this.order);
      this.displayIcons = this.filterIcons(this.icons, this.theme, this.search);
    });
  }

  onIconClick(_: MouseEvent, icon: IICON): void {
    this.selectedIcon = {...icon};
    this.modalVisible = true;
  }

  onThemeChange(val: string) {
    this.displayIcons = this.filterIcons(this.icons, val, this.search);
  }

  onSearchChange(val: string) {
    this.displayIcons = this.filterIcons(this.icons, this.theme, val);
  }

  filterIcons(icons: IICONCate[], theme: string, search: string): IICONCate[] {
    return icons.filter(e => e.icons.filter(i => i.type.includes(theme) && i.text.includes(search.toLowerCase())).length > 0).map(e => ({
      cate: e.cate,
      cateCode: e.cateCode,
      icons: e.icons.filter(i => i.text.includes(search.toLowerCase()))
    }));
  }

  getCateText(value: string) {
    return this.i18n.getLocaleData(`icon.${value}`);
  }

  onCopyText(icon: IICON) {
    this._copy(icon.path.replace(/^icons\//, '')).then(() => {
      this.messageService.success('复制成功');

      this.modalVisible = false;
    });
  }

  onCopyCode(icon: IICON) {
    this._copy(icon.copyCode).then(() => {
      this.messageService.success('复制成功');
      this.modalVisible = false;
    });
  }

  onCopySvg(icon: IICON) {
    this.http.get<any>(`assets/${icon.copySvgPath}.svg`).subscribe(() => { // tslint:disable-line:no-any
      // 由于 svg 不是正确的 json 格式，请求会走 error 处理
    }, error => {
      this._copy(error.error.text).then(() => {
        this.messageService.success('复制成功');
        this.modalVisible = false;
      });
    });
  }

  onModalClose() {
    this.modalVisible = false;
  }

  private _copy(value: string): Promise<string> {
    const promise = new Promise<string>((resolve): void => {
      let copyTextArea = (null as any) as HTMLTextAreaElement; // tslint:disable-line:no-any
      try {
        copyTextArea = this.dom.createElement('textarea');
        copyTextArea.style.height = '0px';
        copyTextArea.style.opacity = '0';
        copyTextArea.style.width = '0px';
        this.dom.body.appendChild(copyTextArea);
        copyTextArea.value = value;
        copyTextArea.select();
        this.dom.execCommand('copy');
        resolve(value);
      } finally {
        if (copyTextArea && copyTextArea.parentNode) {
          copyTextArea.parentNode.removeChild(copyTextArea);
        }
      }
    });

    return promise;
  }

  private ordered(source: IICONCate[], order: string[]) {
    const ret: IICONCate[] =[];
    order.forEach( (o) => {
      const cate = source.filter( s => s.cateCode === o);
      if(cate && cate.length > 0) {
        ret.push(...cate);
      }
    } );
    return ret;
  }
}

