import { Component, OnInit, ViewChild, Type } from '@angular/core';
import { STComponent, STColumn, STChange } from '@delon/abc/st';
import { SFComponent, SFRadioWidgetSchema, SFSchema, SFSchemaEnum, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { SystemService } from '../../services/system.service';

@Component({
  selector: 'app-close-account',
  templateUrl: './close-account.component.html',
  styleUrls: ['../../../commom/less/box.less', '../../../commom/less/expend-but.less']
})
export class CloseAccountComponent implements OnInit {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sfFre', { static: false }) sfFre!: SFComponent;
  ui: SFUISchema = {};
  ui2: SFUISchema = {};
  schema: SFSchema = {};
  addSchema: SFSchema = {};
  _$expand = false;
  editText = '';
  formData :any;
  isVisible = false;
  edit = false;
  editId = false;

  columns: STColumn[] = [
    { title: '结算客户名称', index: 'customerName' },
    { title: '结算客户编码', index: 'customerCode' },
    { title: '网络货运人', index: 'networkTransporterName' },
    { title: '货主名称', index: 'enterpriseName' },
    { title: '客户编码', index: 'crmCustomerCode' },
    {
      title: '操作',
      className: 'text-center',
      buttons: [
        {
          text: '编辑',
          click: item => this.roleAction(item, 2)
        },
        {
          text: '删除',
          click: item => this.deleteAction(item)
        },
      ]
    }
  ];

  selectedRows: any[] = [];

  get reqParams (){ 
    return {
    ...this.sf?.value,
  }};

  constructor(
    public service: SystemService, 
    private nzModalService: NzModalService,
    public shipperservice: ShipperBaseService,
    ) {}

  ngOnInit(): void {
    this.initSF()
    this.initSFFre()
  }

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        break;
      case 'filter':
        this.st.load();
        break;
    }
  }
    /**
  * 伸缩查询条件
  */
     expandToggle(): void {
      this._$expand = !this._$expand;
      this.sf?.setValue('/_$expand', this._$expand);
    }
    /**
   * 查询字段个数
   */
     get queryFieldCount(): number {
      return Object.keys(this.schema?.properties || {}).length;
    }
  initSF(){
  this.schema = {
    properties: {
      _$expand: { type: 'boolean', ui: { hidden: true } },
      customerName: {
        type: 'string',
        title: '结算客户名称',
        ui: { placeholder: '请输入' }
      },
      customerCode: {
        type: 'string',
        title: '结算客户编码',
        ui: { placeholder: '请输入' }
      },
      networkTransporterId: {
        title: '网络货运人',
        type: 'string',
        ui: {
          placeholder: '请选择',
          widget: 'select',
          allowClear: true,
          asyncData: () => this.shipperservice.getNetworkFreightForwarder(),
        }
      },
      enterpriseName: {
        type: 'string',
        title: '货主名称',
        ui: { placeholder: '请输入',
        visibleIf: {
          _$expand: (value: boolean) => value
        } }
      },
    }
    
  };
  this.ui = { '*': { spanLabelFixed: 110, grid: { span: 8, gutter: 4 } } };
  }
  initSFFre() {
  this.addSchema = {
    properties: {
      customerName: {
        type: 'string',
        title: '结算客户名称',
        ui: { placeholder: '请输入' }
      },
      customerCode: {
        type: 'string',
        title: '结算客户编码',
        ui: { placeholder: '请输入' }
      },
      networkTransporterId: {
        title: '网络货运人',
        type: 'string',
        ui: {
          placeholder: '请选择',
          widget: 'select',
          asyncData: () => this.shipperservice.getNetworkFreightForwarder(),
        }
      },
      enterpriseId: {
        title: '货主',
        type: 'string',
        maxLength: 30,
        ui: {
          widget: 'select',
          serverSearch: true,
          searchDebounceTime: 300,
          searchLoadingText: '搜索中...',
          onSearch: (q: any) => {
            let str =q.replace(/^\s+|\s+$/g,"");
            if (str) {
              return this.service
                .request(this.service.$api_enterpriceList, { enterpriseName: str})
                .pipe(map((res: any) => (res as any[]).map((i) => ({ label: i.enterpriseName, value: i.id } as SFSchemaEnum))))
                .toPromise();
            } else {
              return of([]);
            }
          },
        } as SFSelectWidgetSchema,
      }, 
  },
  required: ['customerName', 'customerCode', 'networkTransporterId', 'enterpriseId']
  };
this.ui2 = { '*': { spanLabelFixed: 120, grid: { span: 24 } } };
}
  roleAction(value: any,item?: any) {
    if(item === 1) {
      this.edit = false;
      this.editText = '新增';
      this.formData = {};
    } else {
      this.service.request(this.service.$api_settlementCustomer_get, {id: value.id}).subscribe((res: any) => {
        console.log(res)
        if(res) {
          this.formData = res;
        }
      })
      this.edit = true;
      this.editId = value.id;
      this.editText = '编辑';
    }
   this.isVisible = true;
  }

  deleteAction(item?: any) {
    this.nzModalService.error({
      nzTitle: '确认删除？',
      nzClosable: false,
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service.request(this.service.$api_deletebatchButton, [item.id]).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('删除成功！');
            this.st.reload(1)
          }
        })
      }
    });
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
  }
  handleCancel() {
    this.isVisible = false
  }

  handleOK() {
    console.log(this.sfFre.value)
    if(!this.sfFre.valid) {
      this.service.msgSrv.warning('请正确填写完整！')
      return
    }
    const params ={
      ...this.sfFre.value
    }
    if(this.editId) {
      params.id = this.editId
    }
    this.service.request(this.service.$api_settlementCustomer_save, params).subscribe((res:any) => {
      if(res) {
    this.service.msgSrv.success('保存成功！')
    this.isVisible = false
    this.st.reload();
      } else {
    this.service.msgSrv.warning(res?.msg)

      }
    })
  }
}
