import { query } from '@angular/animations';
import { CurrencyPipe } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STChange, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema, SFUISchema } from '@delon/form';
import { isTemplateRef } from 'ng-zorro-antd/core/util';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { TicketService } from '../../services/ticket.service';
import { PrintOrderModalComponent } from './print-order-modal/print-order-modal.component';
import { RequestedInvoiceModalComponent } from './requested-invoice-modal/requested-invoice-modal.component';

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

  _$expand = false;

  totalCallNo = 0;
  selectedRows: any[] = [];
  constructor(public service: TicketService, private nzModalService: NzModalService, private router: Router) {}

  ngOnInit(): void {}

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

  afterRes = (data: any[], rawData?: any) => {
    return data.map(item => ({
      ...item,
      disabled: item.expressHSts
    }));
  };

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

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

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

  printOrder(item: any[]) {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择订单');
      return;
    }
    const modal = this.nzModalService.create({
      nzTitle: '打印面单',
      nzContent: PrintOrderModalComponent,
      nzWidth: 650,
      nzComponentParams: { vatappcodes: this.selectedRows.map(item => item.vatappcode) },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  showReason(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '查看原因',
      nzContent: '运单数据异常，暂时无法开票，请联系客服400-xxxx-xxxx',
      nzFooter: [
        {
          label: '关闭',
          type: 'primary',
          onClick: () => {
            modal.destroy();
          }
        }
      ]
    });
  }

  batchRequested() {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择订单');
      return;
    }
    const modal = this.nzModalService.create({
      nzTitle: '开票',
      nzContent: '确认对所有申请单进行批量开票？',
      nzFooter: [
        {
          type: 'default',
          label: '手工处理',
          onClick: () => {
            const params = {
              ficoVatappBillVOList: this.selectedRows
              // id: this.id
            };
            this.service.request(this.service.$api_get_applyBatchFicoVatinv, params).subscribe((res: any) => {
              if (res) {
                this.service.msgSrv.success('开票成功！');
                modal.destroy();
                this.st.load(1);
              }
            });
          }
        },
        {
          type: 'primary',
          label: '自动开票',
          onClick: () => {
            const params = {
              ficoVatappBillVOList: this.selectedRows
              // id: this.id
            };
            this.service.request(this.service.$api_get_applyBatchFicoVatinv, params).subscribe((res: any) => {
              if (res) {
                this.service.msgSrv.success('开票成功！');
                modal.destroy();
                this.st.load(1);
              }
            });
          }
        }
      ]
    });
  }

  requestedInvoiceAction(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '开票',
      nzContent: RequestedInvoiceModalComponent,
      nzWidth: 1200,
      nzComponentParams: {
        id: item.id
      },
      nzFooter: null
    });
  }

  /**
   * 重置表单
   */
  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
          }
        },
        vatappcode: {
          type: 'string',
          title: '申请编号',
          ui: {
            placeholder: '请输入'
          }
        },
        billHCode: {
          type: 'string',
          title: '订单号',
          ui: {
            placeholder: '请输入'
          }
        },
        feeHCode: {
          type: 'string',
          title: '费用号',
          ui: {
            placeholder: '请输入'
          }
        },
        projectId: {
          title: '项目',
          type: 'string',
          default: '',
          ui: {
            widget: 'select',
            visibleIf: {
              expand: (value: boolean) => value
            },
            asyncData: () => this.service.getEnterpriseProject()
          }
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            },
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder()
          },
          default: ''
        },
        otherremarks: {
          type: 'string',
          title: '其他需求',
          enum: [{ label: '全部', value: '' }],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        createTime: {
          title: '申请时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true,
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        isdetail: {
          type: 'string',
          title: '销货清单',
          enum: [
            { label: '全部', value: '' },
            { label: '需要', value: 1 },
            { label: '不需要', value: 0 }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox' },
      { title: '申请编号', render: 'vatappcode', width: 180 },
      { title: '网络货运人', index: 'ltdName', width: 150 },
      { title: '购买方', index: 'artoName', width: 150 },
      { title: '订单数', index: 'ordlines', width: 90 },
      {
        title: '申请金额',
        index: 'applyAmount',
        width: 100,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.applyAmount }) }
      },
      {
        title: '运输费',
        index: 'fjfmoney2',
        width: 90,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.fjfmoney2 }) }
      },
      {
        title: '附加费',
        index: 'fjfmoney',
        width: 90,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.fjfmoney }) }
      },
      {
        title: '已开票金额',
        index: 'invoicedMoney',
        width: 120,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.invoicedMoney }) }
      },
      { title: '开户行', index: 'bankName', width: 160 },
      { title: '银行账户', index: 'bankAccount', width: 140 },
      { title: '注册地址', index: 'registerAddr', width: 140 },
      { title: '注册电话', index: 'registerPhone', width: 120 },
      { title: '服务名称', index: 'vatname', width: 100 },
      {
        title: '销货清单',
        index: 'isdetail',
        width: 100,
        format: item => {
          return item.isdetail === 0 ? '不需要' : '需要';
        }
      },
      { title: '其他要求', index: 'otherremarks', width: 100 },
      { title: '申请人', index: 'applyName', width: 90 },
      { title: '申请时间', index: 'applyTime', type: 'date', width: 150 },
      {
        title: '快递是否下单成功',
        index: 'expressHSts',
        width: 150,
        className: 'text-center',
        type: 'enum',
        enum: { true: '是', false: '否' }
      },
      {
        title: '操作',
        width: 125,
        fixed: 'right',
        buttons: [
          { type: 'divider' },
          {
            text: '开票<br/>',
            click: item => this.requestedInvoiceAction(item)
          },
          // {
          //   text: '驳回<br/>',
          //   click: item => this.rejectAction([item])
          // },
          {
            text: '订单明细<br/>',
            click: item => this.router.navigate(['/ticket/invoice-requested/detail/' + item?.id])
          },
          {
            text: '查看原因<br/>',
            click: item => this.showReason(item)
          }
          // {
          //   text: '下载对账单'
          //   // click: item => this.rejectAction(item)
          // }
        ]
      }
    ];
  }
  selectChange(e: any) {
    this.resourceStatus = e;
    this.initST();
    setTimeout(() => {
      console.log(this.resourceStatus);
      
      this.st.load();
    }, 500);
  }
}
