import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema, SFSelectWidgetSchema, SFSchemaEnum } from '@delon/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { FreightAccountService } from '../../services/freight-account.service';

@Component({
  selector: 'app-cost-management',
  templateUrl: './cost-management.component.html',
  styleUrls: ['../../../commom/less/box.less']
})
export class CostManagementComponent implements OnInit {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  @ViewChild('auditModal', { static: false })
  auditModal!: any;
  searchSchema: SFSchema = this.initSF();
  columns: STColumn[] = this.initST();

  selectedRows: any[] = [];

  _$expand = false;

  constructor(public service: FreightAccountService, private nzModalService: NzModalService, private router: Router) {}

  ngOnInit(): void {}

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf.value,
        feedate: {
          start: this.sf.value.feedate?.[0] || '',
          end: this.sf.value.feedate?.[1] || ''
        },
        createTime: {
          start: this.sf.value.createTime?.[0] || '',
          end: this.sf.value.createTime?.[1] || ''
        }
      });
    }
    return requestOptions;
  };

  auditAction(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '审核',
      nzContent: this.auditModal,
      nzFooter: [
        {
          label: '拒绝',
          type: 'default',
          onClick: () => {
            modal.destroy();
          }
        },
        {
          label: '通过',
          type: 'primary',
          onClick: () => {
            modal.destroy();
          }
        }
      ]
    });
    modal.afterClose.subscribe(res => {
      this.st.load();
    });
  }

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

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

  exportList() {
    this.service.exportStart( { ...this.sf.value, pageSize: -1 }, this.service.$api_get_exportPlatformAccountBalanceByOperator,);
  }

  routeTo(url: string, params?: any, status?: any) {
    this.router.navigate([url], { queryParams: params });
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        feecode: {
          type: 'string',
          title: '费用单号',
          ui: { placeholder: '请输入' }
        },
        billHCode: {
          type: 'string',
          title: '订单号',
          ui: { placeholder: '请输入' }
        },
        waybillHCode: {
          type: 'string',
          title: '运单号',
          ui: {
            placeholder: '请输入'
          }
        },
        feedate: {
          title: '费用日期',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true,
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        feetype: {
          type: 'string',
          title: '费用类型',
          enum: [
            { label: '全部', value: '' },
            { label: '应收', value: 1 },
            { label: '应付', value: 2 }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        feeSubId: {
          type: 'string',
          title: '费用科目',
          enum: [
            { label: '全部', value: '全部' },
            { label: '运输费', value: '1475197820443299842' },
            { label: '附加费', value: '1476197820443299842 ' },
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder(),
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        hrto: {
          type: 'string',
          title: '应付对象',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service
                  .request(this.service.$api_crm_enterpriceList, { enterpriseName: str })
                  .pipe(map((res: any) => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.enterpriseId } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        arto: {
          type: 'string',
          title: '应收对象',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service
                  .request(this.service.$api_crm_enterpriceList, { enterpriseName: str })
                  .pipe(map((res: any) => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.crmUserId } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        createTime: {
          title: '创建时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true,
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        ishrhx: {
          type: 'string',
          title: '应付核销',
          enum: [
            { label: '全部', value: '' },
            { label: '否', value: 0 },
            { label: '是', value: 1 }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        cno: {
          type: 'string',
          title: '结算客户',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getCloseAccount(),
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '费用单号', fixed: 'left', index: 'feecode', width: 200, className: 'text-left' },
      { title: '网络货运人', index: 'ltdName', width: 220, className: 'text-left' },
      { title: '订单号', index: 'billHCode', width: 200, className: 'text-left' },
      { title: '运单号', index: 'waybillHCode', width: 200, className: 'text-left' },
      { title: '费用日期', index: 'feedate', width: 200, className: 'text-left' },
      { title: '费用类型', index: 'feetypeLabel', width: 150, className: 'text-center' },
      { title: '应付核销', index: 'ishrhx', width: 200, type: 'enum', enum: { 0: '否', 1: '是' }, className: 'text-left' },
      { title: '结算客户', render: 'artocode', width: 200, className: 'text-left' },
      { title: '应收对象', index: 'artoname', width: 200, className: 'text-left' },
      { title: '应付对象', index: 'hrtoname', width: 200, className: 'text-left' },
      { title: '应收金额', render: 'armoeny', width: 150, className: 'text-right' },
      { title: '应付金额', render: 'hrmoney', width: 150, className: 'text-right' },
      { title: '收/付款金额', render: 'hrpaymoney', width: 150, className: 'text-right' },
      { title: '开/收票金额', render: 'hrvatmoney', width: 150, className: 'text-right' },
      { title: '创建时间', index: 'createTime', type: 'date', width: 200, className: 'text-center' },
      { title: '状态', index: 'stsLabel', width: 120, className: 'text-center' },
      {
        title: '操作',
        fixed: 'right',
        className: 'text-center',
        width: '110px',
        buttons: [
          {
            text: '浏览',
            click: item => this.routeTo('/financial-management/cost-management/detail/' + item.id, { status: item?.feetypeLabel }),
            acl: { ability: ['FINANCIAL-COST-view'] }
          },
          {
            text: '审核',
            click: item => this.auditAction(item),
            iif: item => item.sts === 2,
            acl: { ability: ['FINANCIAL-COST-audit'] }
          }
          // {
          //   text: '修改',
          //   click: item => this.router.navigate(['/financial-management/cost-management/expenses-receivable/1'], { queryParams: { id: 1 } })
          // }
        ]
      }
    ];
  }
}
