import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { STComponent, STColumn, STChange } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFUISchema } from '@delon/form';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { DemoService } from '../../services/demo.service';
import { DemoEditComponent } from '../zorro-demo/edit/edit.component';

@Component({
  selector: 'app-alian-demo',
  templateUrl: './alian-demo.component.html',
  styleUrls: ['./alian-demo.component.less']
})
export class AlianDemoComponent implements OnInit {
  url = `/rule?_allow_anonymous=true`;

  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 }
  ];
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  columns: STColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: '规则编号', index: 'no' },
    { title: '描述', index: 'description' },
    {
      title: '服务调用次数',
      index: 'callNo',
      type: 'number',
      format: item => `${item.callNo} 万`,
      sort: {
        compare: (a, b) => a.callNo - b.callNo
      }
    },
    {
      title: '状态',
      index: 'status',
      render: 'status',
      filter: {
        menus: this.status,
        fn: (filter, record) => record.status === filter.index
      }
    },
    {
      title: '更新时间',
      index: 'updatedAt',
      type: 'date',
      sort: {
        compare: (a, b) => a.updatedAt - b.updatedAt
      }
    },
    {
      title: '操作',
      buttons: [
        {
          text: '修改',
          click: item => this.edit(item)
        },
        {
          text: '删除',
          click: item => this.delete(item)
        }
      ]
    }
  ];
  searchSchema: SFSchema = {
    properties: {
      expand: {
        type: 'boolean',
        ui: {
          hidden: true
        }
      },
      orderSn: {
        type: 'string',
        title: '订单号',
        ui: {
          autocomplete: 'off'
        }
      },
      receiveName: {
        type: 'string',
        title: '收件人'
      },
      receiveMobile: {
        type: 'string',
        title: '收件人电话'
      },
      tenantName: {
        type: 'string',
        title: '下单商家',
        ui: {
          visibleIf: {
            expand: (value: boolean) => value
          }
        }
      },
      createTime: {
        title: '下单时间',
        type: 'string',
        ui: {
          widget: 'date',
          mode: 'range',
          format: 'yyyy-MM-dd',
          visibleIf: {
            expand: (value: boolean) => value
          }
        } as SFDateWidgetSchema
      }
    }
  };

  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 90,
      grid: { span: 8, gutter: 4 }
    },
    $orderSn: {
      grid: { span: 8 }
    },
    $receiveName: {
      grid: { span: 8 }
    },
    $createTime: { grid: { span: 8 } }
  };
  _$expand = false;

  selectedRows: any[] = [];
  totalCallNo = 0;
  constructor(public service: DemoService, public msg: NzMessageService, private modal: ModalHelper) {}

  ngOnInit(): void {}

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.callNo, 0);
        break;
      case 'filter':
        this.st.load();
        break;
    }
  }

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

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

  add(): void {
    this.modal.createStatic(DemoEditComponent, { i: { id: 0 } }).subscribe(res => {
      if (res) {
        console.log(res);
      }
    });
  }

  edit(item: any) {
    this.modal
      .createStatic(DemoEditComponent, { i: { no: 1, owner: '22222', callNo: 111, status: 1, description: '222' } })
      .subscribe(res => {
        if (res) {
          this.st.setRow(item, res);
        }
      });
  }

  delete(item: any) {
    this.st.removeRow(item);
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this._$expand = false;
  }

  /**
   * 伸缩查询条件
   */
  expandToggle() {
    this._$expand = !this._$expand;
    this.sf?.setValue('/expand', this._$expand);
  }
}
