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

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

  _$expand = false;
  refundStatus: any = '';

  msg = '';

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

  ngOnInit(): void {}

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

  changeRefundStatus(status?: string) {
    this.refundStatus = status || null;
    this.st.load(1);
  }

  auditAction(item?: any) {
    this.msg = '';
    const modal = this.nzModalService.create({
      nzTitle: '审核',
      nzContent: this.auditModal,
      nzFooter: [
        {
          label: '拒绝',
          type: 'default',
          onClick: () => {
            if (!this.msg) {
              this.service.msgSrv.warning('请填写原因');
              return false;
            }
            this.service
              .request(this.service.$api_disagree_refund_record, {
                applicationId: item.id,
                remark: this.msg
              })
              .subscribe(res => {
                if (res) {
                  this.service.msgSrv.success('审核拒绝成功');
                  modal.destroy(true);
                  this.st.load(1);
                }
              });
            return false;
          }
        },
        {
          label: '通过',
          type: 'primary',
          onClick: () => {
            this.service
              .request(this.service.$api_agree_refund_record, {
                applicationId: item.id,
                remark: this.msg
              })
              .subscribe(res => {
                if (res) {
                  this.service.msgSrv.success('审核通过成功');
                  modal.destroy(true);
                  this.st.load(1);
                }
              });
            return false;
          }
        }
      ]
    });
  }

  reApply(item: any) {
    const modal = this.nzModalService.warning({
      nzTitle: '确定要重新发起退款？',
      nzOnOk: () => {
        this.service
          .request(this.service.$api_rebulid_refund_record, {
            applicationId: item.id
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('发起成功');
              modal.destroy(true);
              this.st.load(1);
            }
          });
        return false;
      }
    });
  }

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

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

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        orderRefundCode: {
          type: 'string',
          title: '退款单号',
          ui: {
            placeholder: '请输入'
          }
        },
        refundType: {
          type: 'string',
          title: '退款类型',
          enum: [
            { value: '1', label: '平台退款货主' },
            { value: '2', label: '司机退款平台' },
            { value: '3', label: '车队长退款司机' },
            { value: '4', label: '车队长退款平台' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        enterpriseInfoName: {
          type: 'string',
          title: '货主',
          ui: {
            placeholder: '请输入'
          }
        },
        billCode: {
          type: 'string',
          title: '订单号',
          ui: {
            visibleIf: {
              expand: (value: boolean) => value
            },
            placeholder: '请输入'
          }
        },
        enterpriseProjectName: {
          type: 'string',
          title: '所属项目',
          ui: {
            placeholder: '请输入',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        resourceCode: {
          type: 'string',
          title: '货源号',
          ui: {
            visibleIf: {
              expand: (value: boolean) => value
            },
            placeholder: '请输入'
          }
        },
        refundExecuteTime: {
          title: '退款时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            },
            nzShowTime: true
          } as SFDateWidgetSchema
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder(),
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        bankType: {
          type: 'string',
          title: '银行类型',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'bankname:type' },
            placeholder: '请输入',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '退款单号', render: 'orderRefundCode', width: 190 },
      { title: '退款类型', index: 'refundTypeLabel', width: 140 },
      { title: '退款金额', render: 'refundAmount', className: 'text-right', width: 180 },
      { title: '退款时间', index: 'refundExecuteTime', width: 170 },
      { title: '货主', index: 'enterpriseInfoName', width: 150 },
      { title: '所属项目', index: 'enterpriseProjectName', width: 140 },
      { title: '支付单', render: 'billRefundPaymentVOS', width: 150 },
      { title: '订单号', index: 'billCode', width: 150 },
      { title: '货源号', index: 'resourceCode', width: 150 },
      { title: '司机', render: 'driver', width: 150 },
      { title: '收款人', render: 'captain', width: 150 },
      { title: '网络货运人', index: 'ltdName', width: 180 },
      { title: '银行类型', index: 'bankTypeLabel', width: 120 },
      { title: '退款原因', index: 'reason', width: 170 },
      { title: '失败原因', index: 'failCause', width: 170 },
      {
        title: '操作',
        fixed: 'right',
        className: 'text-center',
        width: '150px',
        buttons: [
          {
            text: '审核',
            iif: item => item.refundStatus === '1',
            click: item => this.auditAction(item)
          },
          {
            text: '重新发起',
            iif: item => item.refundStatus === '5',
            click: item => this.reApply(item)
          }
          // {
          //   text: '关闭',
          //   click: item => this.router.navigate(['/financial-management/withdrawals-record/detail/' + item.id])
          // }
        ]
      }
    ];
  }
  // 导出
  exprot() {
    this.service.exportStart({ ...this.sf.value, pageSize: -1 }, this.service.$api_get_asyncExportBillRefundApplicationList);
  }
}
