import { ChangeDetectorRef, Component, OnInit, TemplateRef } from '@angular/core';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { map, tap } from 'rxjs/operators';
import { DemoService } from '../../services/demo.service';

@Component({
  selector: 'app-zorro-demo',
  templateUrl: './zorro-demo.component.html',
  styleUrls: ['./zorro-demo.component.less']
})
export class ZorroDemoComponent implements OnInit {
  data: any[] = [];
  loading = false;
  expandForm = false;

  q: {
    pi: number;
    ps: number;
    no: string;
    sorter: string;
    status: number | null;
    statusList: NzSafeAny[];
  } = {
    pi: 1,
    ps: 10,
    no: '',
    sorter: '',
    status: null,
    statusList: []
  };

  status = [
    { index: 0, text: '关闭', value: false, type: 'default', checked: false },
    {
      index: 1,
      text: '运行中',
      value: false,
      type: 'processing',
      checked: false
    },
    { index: 2, text: '已上线', value: false, type: 'success', checked: false },
    { index: 3, text: '异常', value: false, type: 'error', checked: false }
  ];

  selectedRows: any[] = [];
  totalCallNo = 0;
  description: string = '';
  checkedAll = false;
  indeterminate = false;
  constructor(
    private service: DemoService,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    this.getData();
  }

  getData(): void {
    this.loading = true;
    this.q.statusList = this.status.filter(w => w.checked).map(item => item.index);
    if (this.q.status !== null && this.q.status > -1) {
      this.q.statusList.push(this.q.status);
    }
    this.service
      .request('/rule?_allow_anonymous=true', this.q)
      .pipe(
        map((list: { records: Array<{ status: number; statusText: string; statusType: string }> }) =>
          list.records.map(i => {
            const statusItem = this.status[i.status];
            i.statusText = statusItem.text;
            i.statusType = statusItem.type;
            return i;
          })
        ),
        tap(() => (this.loading = false))
      )
      .subscribe(res => {
        this.data = res;
      });
  }

  action(tpl: TemplateRef<{}>, data?: any): void {
    if (data) {
      this.description = data.description;
    }
    this.modalSrv.create({
      nzTitle: '新建规则',
      nzContent: tpl,
      nzOnOk: () => {
        this.loading = true;

        // this.http.post('/rule', { description: this.description }).subscribe(() => this.getData());
        if (data) {
          Object.assign(data, { description: this.description });
        } else {
          this.data.push({
            checked: false,
            key: this.data.length,
            callNo: 111,
            description: this.description
          });
          this.data = [...this.data];
        }
        setTimeout(() => {
          this.loading = false;
        }, 1000);
      }
    });
  }

  remove(): void {
    this.service.request('/delete/rule?_allow_anonymous=true', { nos: this.selectedRows.map((i: any) => i.no).join(',') }).subscribe(() => {
      this.getData();
      this.clearCheck();
    });
  }

  deleteAction(item: any) {
    this.data = this.data.filter(({ no }) => no !== item.no);
  }

  approval(): void {
    this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
  }

  onAllChecked(checked: boolean): void {
    this.data.filter(({ disabled }) => !disabled).forEach(item => (item.checked = checked));
    this.selectedRows = this.data.filter(({ checked }) => checked);
  }

  onItemChecked(checked: boolean, item: any): void {
    if (checked) {
      this.selectedRows.push(item);
    } else {
      this.selectedRows = this.selectedRows.filter(({ no }) => no !== item.no);
    }
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checkedAll = this.data.every(item => item.checked);
    this.indeterminate = this.data.some(item => item.checked) && !this.checkedAll;
  }

  clearCheck() {
    this.data.forEach(item => (item.checked = false));
    this.selectedRows = [];
    this.checkedAll = false;
    this.indeterminate = false;
  }

  reset(): void {
    // wait form reset updated finished
    setTimeout(() => this.getData());
  }
}
