import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core';
import { STComponent, STColumn, STChange, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFSchema } from '@delon/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { SystemService } from 'src/app/routes/sys-setting/services/system.service';
import { TicketService } from '../../services/ticket.service';
import { AddCartComponent } from './add-cart/add-cart.component';
import { AddOwnerComponent } from './add-owner/add-owner.component';

@Component({
  selector: 'app-etc-blacklist',
  templateUrl: './etc-blacklist.component.html',
  styleUrls: ['../../../commom/less/box.less', './etc-blacklist.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ETCBlacklistComponent implements OnInit {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  tabs = [
    {
      name: '货主',
      type: 1,
      isActived: false
    },
    {
      name: '车辆',
      type: 2,
      isActived: false
    }
  ];
  tabType = 1;

  searchSchema: SFSchema = this.initSF();

  columns: STColumn[] = this.initST();

  selectedRows: any[] = [];

  constructor(public service: TicketService, private nzModalService: NzModalService) {}

  ngOnInit(): void {}

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf.value
      });
    }
    this.selectedRows = [];
    return requestOptions;
  };

  // 切换Tab
  changeTab(item: any) {
    this.tabType = item.type;
    this.sf?.setValue('/tabType', item.type);
    this.sf?.reset();
    this.selectedRows = [];
    setTimeout(() => {
      this.tabs.forEach(i => (i.isActived = false));
      item.isActived = !item.isActived;
      // this.st.load(1);
      this.st.resetColumns();
    }, 500);
  }

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        break;
    }
  }

  configAction(item?: any) {
    if (this.tabType === 1) {
      this.addOwnerAction(item);
    } else {
      this.addCartAction(item);
    }
  }

  addOwnerAction(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '选择货主',
      nzContent: AddOwnerComponent,
      nzWidth: 850,
      nzComponentParams: { data: [] },
      nzOnOk: com => {
        if (com.selectedData?.length <= 0) {
          this.service.msgSrv.warning('请选择货主');
          return false;
        }
        const ids = com.selectedData.map(node => node.id);
        this.service.request(this.service.$api_save_etc_shipper, { shipperAppUserIdList: ids }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('添加成功');
            modal.destroy();
            this.st.load(1);
          }
        });
        return false;
      }
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  addCartAction(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '选择车辆',
      nzContent: AddCartComponent,
      nzWidth: 700,
      nzComponentParams: { data: [] },
      nzOnOk: com => {
        if (com.selectedData?.length <= 0) {
          this.service.msgSrv.warning('请选择车辆');
          return false;
        }
        const ids = com.selectedData.map(node => node.carId);
        this.service.request(this.service.$api_save_etc_cart, { carIds: ids }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('添加成功');
            modal.destroy();
            this.st.load(1);
          }
        });
        return false;
      }
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  deleteAction(item?: any) {
    let ids: Array<string> = [];
    if (item) {
      ids = [item.id];
    } else {
      ids = this.selectedRows.map(node => node.id);
    }
    if (ids?.length <= 0) {
      this.service.msgSrv.warning('请选择ETC白名单');
      return;
    }

    const modal = this.nzModalService.warning({
      nzTitle: this.tabType === 1 ? '确定将所选货主从ETC白名单中剔除？' : '确定将所选车辆从ETC白名单中剔除？',
      nzClosable: false,
      nzCancelText: '取消',
      nzOnOk: () => {
        if (this.tabType === 1) {
          this.service.request(this.service.$api_delete_etc_shipper, ids).subscribe(res => {
            if (res) {
              this.service.msgSrv.success('删除成功');
              this.st.load(1);
              this.selectedRows = [];
              modal.destroy();
            }
          });
        } else {
          this.service.request(this.service.$api_delete_etc_cart, ids).subscribe(res => {
            if (res) {
              this.service.msgSrv.success('删除成功');
              this.st.load(1);
              this.selectedRows = [];
              modal.destroy();
            }
          });
        }
        return false;
      },
      nzOkText: '确定'
    });
  }
  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
  }

  private initSF(): SFSchema {
    return {
      properties: {
        tabType: {
          type: 'number',
          ui: {
            hidden: true
          }
        },
        shipperAppUserName: {
          title: '企业名称',
          type: 'string',
          ui: {
            placeholder: '请输入',
            visibleIf: {
              tabType: (value: number) => this.tabType === 1
            }
          }
        },
        contactName: {
          title: '联系人姓名',
          type: 'string',
          ui: {
            placeholder: '姓名/手机/车牌号',
            visibleIf: {
              tabType: (value: number) => this.tabType === 1
            }
          }
        },
        contactPhoneNumber: {
          title: '联系人手机号',
          type: 'string',
          ui: {
            placeholder: '请输入',
            visibleIf: {
              tabType: (value: number) => this.tabType === 1
            }
          }
        },
        carNo: {
          title: '车牌号',
          type: 'string',
          ui: {
            placeholder: '请输入',
            visibleIf: {
              tabType: (value: number) => this.tabType === 2
            }
          }
        },
        carOwner: {
          title: '车辆所有人',
          type: 'string',
          ui: {
            placeholder: '请输入',
            visibleIf: {
              tabType: (value: number) => this.tabType === 2
            }
          }
        }
        // params6: {
        //   title: '手机号',
        //   type: 'string',
        //   ui: {
        //     placeholder: '请输入',
        //     visibleIf: {
        //       tabType: (value: number) => this.tabType === 2
        //     }
        //   }
        // }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox' },
      { title: '企业名称', index: 'shipperAppUserName', iif: () => this.tabType === 1 },
      { title: '联系人姓名', index: 'contactName', iif: () => this.tabType === 1 },
      { title: '联系人手机号', index: 'contactPhoneNumber', iif: () => this.tabType === 1 },
      {
        title: '认证状态',
        className: 'text-center',
        index: 'certificationStatus',
        type: 'enum',
        enum: { 1: '未上传', 0: '草稿', 10: '待审核', 20: '已审核', 30: '已驳回', 40: '证件过期' },
        iif: () => this.tabType === 1
      },
      { title: '车牌号', index: 'carNo', iif: () => this.tabType === 2 },
      { title: '车辆所有人', index: 'carOwner', iif: () => this.tabType === 2 },
      { title: '创建者', index: 'createUserIdLabel' },
      {
        title: '创建时间',
        index: 'createTime',
        type: 'date'
      },
      {
        title: '操作',
        className: 'text-center',
        buttons: [
          {
            text: '删除',
            click: item => this.deleteAction(item)
          }
        ]
      }
    ];
  }
  // 导出
  exprot() {
    if (this.tabType == 1) {
      this.service.exportStart({ ...this.sf.value, pageSize: -1 }, this.service.$api_get_aficoShipperWhiteList_asyncExport);
    } else {
      this.service.exportStart({ ...this.sf.value, pageSize: -1 }, this.service.$api_get_ficoCarWhiteList_asyncExport);
    }
  }
}
