import { query } from '@angular/animations';
import { CurrencyPipe } from '@angular/common';
import { Component, 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 { ShipperBaseService } from '@shared';
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';
import { UpdateAddressModalComponent } from './update-address-modal/update-address-modal.component';
@Component({
  selector: 'app-invoice-requested',
  templateUrl: './invoice-requested.component.html',
  styleUrls: ['./invoice-requested.component.less', '../../../commom/less/box.less']
})
export class InvoiceRequestedComponent {
  @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[] = [];
  rejectReason = '';
  constructor(public service: TicketService, private nzModalService: NzModalService, private router: Router) {}
  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) => {
    this.totalCallNo = 0;
    this.selectedRows = [];
    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).toFixed(2);
        break;
    }
  }
  rejectAction(item: any[]) {
    this.rejectReason = '';
    if (item.length <= 0) {
      this.service.msgSrv.warning('请选择开票申请');
      return;
    }
    if (item.find(item => item.sts !== '1')) {
      this.service.msgSrv.warning('请勿选择非待处理订单');
      return;
    }
    const modal = this.nzModalService.create({
      nzTitle: '驳回',
      nzContent: this.rejectModal,
      nzOkLoading: this.service.http.loading,
      nzOnOk: () => {
        if (!this.rejectReason) {
          this.service.msgSrv.warning('请填写驳回原因');
          return false;
        }
        let ids = item.map(row => row.id);
        this.service.request(this.service.$api_reject_invoice, { id: ids, rejectContent: this.rejectReason }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('驳回成功');
            modal.destroy(true);
          }
        });
        return false;
      }
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }
  /**
   * 修改地址
   * @param item
   */
  changeAddress(item: any[]) {
    this.rejectReason = '';
    if (item.length <= 0) {
      this.service.msgSrv.warning('请选择开票申请');
      return;
    }
    // if (item.find(item => item.sts !== '1')) {
    //   this.service.msgSrv.warning('请勿选择非待处理订单');
    //   return;
    // }
    const modal = this.nzModalService.create({
      nzTitle: '修改地址',
      nzContent: UpdateAddressModalComponent,
      nzOkLoading: this.service.http.loading,
      nzOnOk: component => {
        if (!component.sf.valid) {
          component.sf.validator({ emitError: true });
          // this.service.msgSrv.warning('表单校验错误');
          return false;
        }
        this.service
          .request(this.service.$api_update_invoice_address, {
            ...component.sf.value,
            ids: item.map(i => i.id)
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('修改成功');
              modal.destroy(true);
            }
          });
        return false;
      }
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }
  printOrder(item: any[]) {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择订单');
      return;
    }
    if (this.selectedRows.find(item => item.sts !== '3')) {
      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;
    }
    if (this.selectedRows.find(item => item.sts !== '1')) {
      this.service.msgSrv.warning('请勿选择非待处理订单');
      return;
    }
    const modal = this.nzModalService.create({
      nzTitle: '开票',
      nzContent: '确认对所有申请单进行批量开票?',
      nzFooter: [
        {
          type: 'default',
          label: '手工处理',
          onClick: () => {
            const params = {
              ficoVatappHVOList: this.selectedRows.map(item => {
                const i = Object.assign({}, { ...item });
                delete i._values;
                delete i._rowClassName;
                delete i.checked;
                delete i.disabled;
                return i;
              })
              // 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 = {
              ficoVatappHVOList: this.selectedRows.map(item => {
                const i = Object.assign({}, { ...item });
                delete i._values;
                delete i._rowClassName;
                delete i.checked;
                delete i.disabled;
                return i;
              })
              // 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
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load(1);
      }
    });
  }
  downloadPdf(item: any) {
    this.service.request(this.service.$api_downloadPdf, { vatappHId: item.id }).subscribe(res => {
      if (res?.reconciliationUrl) {
        this.service.reviewPDF(res.reconciliationUrl);
      } else {
        this.service.msgSrv.warning('获取对账单失败');
      }
    });
  }
  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this._$expand = false;
  }
  /**
   * 伸缩查询条件
   */
  expandToggle() {
    this._$expand = !this._$expand;
    this.sf?.setValue('/expand', this._$expand);
  }
  // 导出
  exprot() {
    this.service.exportStart({ ...this.sf.value, pageSize: -1 }, this.service.$api_export_invoice_requested_page);
  }
  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: '其他需求',
          ui: {
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        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: ''
        },
        arto: {
          type: 'string',
          title: '货主名称',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => this.service.getEnterpriceList({ enterpriseName: q }),
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        }
      }
    };
  }
  private initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox' },
      { title: '申请编号', render: 'vatappcode', width: 190 },
      { title: '发票类型', index: 'vatapptypeLabel', width: 140 },
      { title: '网络货运人', index: 'ltdName', width: 170 },
      { title: '货主名称', index: 'artoName', width: 170 },
      { title: '订单数', index: 'ordlines', width: 90 },
      {
        title: '申请金额',
        index: 'applyAmount',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.applyAmount }) }
      },
      {
        title: '运输费',
        index: 'fjfmoney2',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.fjfmoney2 }) }
      },
      {
        title: '附加费',
        index: 'fjfmoney',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.fjfmoney }) }
      },
      {
        title: '已开票金额',
        index: 'invoicedMoney',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: {
          type: 'currency-chy',
          params: ({ record }) => ({ value: record.invoicedMoney })
        }
      },
      { title: '已开票张数', className: 'text-right', index: 'invoicedNum', width: 160 },
      { title: '开户行', index: 'bankName', width: 160 },
      { title: '银行账户', index: 'bankAccount', width: 140 },
      { title: '注册地址', index: 'registerAddr', width: 140 },
      { title: '注册电话', index: 'registerPhone', width: 130 },
      { title: '服务名称', index: 'vatnameLabel', width: 150 },
      {
        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: 170,
        className: 'text-center',
        type: 'enum',
        enum: { true: '是', false: '否' }
      },
      {
        title: '操作',
        width: 125,
        fixed: 'right',
        className: 'text-center',
        buttons: [
          { type: 'divider' },
          {
            text: '开票受理
',
            click: item => this.requestedInvoiceAction(item),
            iif: item => item.sts === '1'
          },
          {
            text: '驳回申请
',
            click: item => this.rejectAction([item]),
            iif: item => item.sts === '1'
          },
          {
            text: '订单明细
',
            click: item => this.router.navigate([`/ticket/invoice-requested/detail/${item?.id}`], { queryParams: { sts: item.sts } })
          },
          {
            text: '查看原因
',
            click: item => this.showReason(item),
            iif: item => item.sts === '4'
          },
          {
            text: '下载对账单',
            iif: item => item.sts === '3',
            click: item => this.downloadPdf(item)
          }
        ]
      }
    ];
  }
  selectChange(e: any) {
    this.resourceStatus = e;
    this.initST();
    setTimeout(() => {
      this.st.load();
    }, 500);
  }
}