import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STChange, STColumn, STComponent, STData } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFUISchema } from '@delon/form';
import { ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { ReportingService } from '../../services/reporting.service';
import { DatatableReportingFundInfoComponent } from '../fund-info/fund-info.component';

@Component({
  selector: 'app-datatable-fund-reporting',
  templateUrl: './fund-reporting.component.html',
  styleUrls: ['./fund-reporting.component.less']
})
export class DatatableFundReportingComponent implements OnInit {
  _$expand = false;
  ui!: SFUISchema;
  schema!: SFSchema;
  columns!: STColumn[];
  @ViewChild('st', { static: false }) st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  tabType!: string;
  tabs: any[] = [
    { name: '待上传', value: '1' },
    { name: '上传中', value: '2' },
    { name: '已上传', value: '3' },
    { name: '异常', value: '4' },
    { name: '全部', value: '' }
  ];
  selectedIndex = '1'; //选择的项目
  serviceTel = '';
  selectedRows: any[] = [];
  isLoading: boolean = false;
  constructor(
    public service: ReportingService,
    private router: Router,
    private ar: ActivatedRoute,
    private modal: NzModalService,
    public shipperSrv: ShipperBaseService
  ) {
  }

  /**
   * 查询字段个数
   */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }

  /**
   * 查询参数
   */
  get reqParams() {
    const params = Object.assign({}, this.sf?.value || {}, {
      uploadStatus: this.selectedIndex
    });
    delete params._$expand;
    return { ...params };
  }

  /**
   * 选中行
   */
  // get selectedRows() {
  //   return this.st?.list.filter((item: any) => item.checked) || [];
  // }

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

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this._$expand = false;
    this.isLoading = true
  }
  /**
   * 程序初始化入口
   */
  ngOnInit() {
    this.initSF();
    this.initST();
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        orderCode: { title: '订单号', type: 'string', ui: { placeholder: '请输入' } },
        wayBillCode: {
          type: 'string',
          title: '运单号',
          ui: {
            placeholder: '请输入',
          },
        },
        serialNumberCode: {
          type: 'string',
          title: '流水单号',
          ui: {
            placeholder: '请输入',
          },
        },
        carrier: {
          title: '承运司机',
          type: 'string',
          ui: {
            placeholder: '请输入司机姓名', visibleIf: {
              _$expand: (value: boolean) => value,
            },
          }
        },
        carNumber: {
          title: '车牌号',
          type: 'string',
          maxLength: 9,
          ui: {
            placeholder: '请输入',
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          }
        },
        payee: {
          title: '车队长',
          type: 'string',
          maxLength: 9,
          ui: {
            placeholder: '请输入',
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          }
        },
        // uploadStatus: {
        //   title: '上传状态',
        //   type: 'string',
        //   enum: [
        //     { label: '待上传', value: 0 },
        //     { label: '已上传', value: 1 },
        //     { label: '异常', value: 2 }
        //   ],
        //   ui: {
        //     placeholder: '请选择',
        //     widget: 'select',
        //     allowClear: true,
        //     visibleIf: {
        //       _$expand: (value: boolean) => value,
        //     },
        //   }
        // },
        verifyStatus: {
          title: '本地校验',
          type: 'string',
          enum: [
            { label: '检测中', value: '0' },
            { label: '通过', value: '1' },
            { label: '不通过', value: '2' }
          ],
          ui: {
            placeholder: '请选择',
            allowClear: true,
            widget: 'select',
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          }
        },
        ltdId: {
          title: '网络货运人',
          type: 'string',
          ui: {
            placeholder: '请选择',
            widget: 'select',
            asyncData: () => this.shipperSrv.getNetworkFreightForwarder({}, false),
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
            allowClear: true
          }
        },
        transactionTime: {
          title: '交易时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd',
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          } as SFDateWidgetSchema,
        },
        uploadTime: {
          title: '上传时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd',
            visibleIf: {
              _$expand: (value: boolean) => value,
            },
          } as SFDateWidgetSchema,
        },
      },
    };
    this.ui = {
      '*': { spanLabelFixed: 120, grid: { span: 8, gutter: 4 }, enter: () => this.search() },
      $time: { grid: { span: 24 } },
    };
  }

  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', className: 'text-center', width: '60px', },
      { title: '上传状态', render: 'uploadStatus', className: 'text-center', width: '120px', },
      { title: '本地校验', render: 'verifyStatus', className: 'text-center', width: '120px', },
      { title: '流水单号', index: 'serialNumberCode', className: 'text-center', width: '190px', },
      {
        title: '订单号',
        render: 'orderCode',
        className: 'text-center',
        width: '180px',
      },
      { title: '运单号', render: 'wayBillCode', className: 'text-center', width: '180px', },
      {
        title: '网络货运人',
        index: 'ltdName',
        className: 'text-center',
        width: '180px',
      },
      { title: '实际承运人名称', index: 'carrier', className: 'text-center', width: '150px' },
      { title: '实际承运人证件号码', index: 'cardId', className: 'text-center', width: '200px' },
      { title: '车牌号', index: 'carNumber', className: 'text-center', width: '180px' },
      { title: '车牌颜色', index: 'carColorLabel', className: 'text-center', width: '180px' },
      { title: '总金额', render: 'tolalAmount', className: 'text-center', width: '120px' },

      { title: '付款方式', index: 'payType', className: 'text-center', width: '150px' },
      { title: '车队长', index: 'payee', className: 'text-center', width: '150px' },
      { title: '收款账户', index: 'collectionAccount', className: 'text-center', width: '180px' },

      { title: '收款银行', index: 'bankTypeLabel', className: 'text-center', width: '150px' },

      { title: '银行流水号', index: 'bankSerialNumber', className: 'text-center', width: '180px' },
      { title: '实际支付金额', render: 'payAmount', className: 'text-center', width: '150px' },
      { title: '交易时间', index: 'transactionTime', className: 'text-center', width: '180px' },
      { title: '上传次数', index: 'uploadFrequency', className: 'text-center', width: '120px' },
      { title: '上传时间', index: 'uploadTime', className: 'text-center', width: '180px' },
    ];
  }



  /**
   *撤销
   * @param record 记录实例
   */
  recall() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要撤回的数据');
      return;
    }
    this.modal.confirm({
      nzTitle: '撤回提示',
      nzContent: ' 撤回后可以重新上传，重新上传会覆盖已上传数据，确定要撤回？',
      nzOkText: '确定',
      nzCancelText: '取消',
      nzOnOk: () => {
        const ids = this.selectedRows.map(i => i?.id);
        this.service.request(this.service.$api_fund_reporting_recall, ids).subscribe((res: any) => {
          if (res) {
            this.service.msgSrv.success('撤销成功');

            this.search();
          }
        })
      }
    });


  }

  selectChange(item: any) {
    this.selectedIndex = item?.value || '';

    setTimeout(() => {
      this.selectedRows = [];
      this.st.load(1);
    })
  }

  /**
   * 查看当行数据
   */
  view(record: STData) {
    // this.router.navigate(['../view', record.uuid], { relativeTo: this.ar });
    this.router.navigate(['../detail'], {
      queryParams: {
        id: record.id,
      },
      relativeTo: this.ar
    });
  }

  // appeal(item: any) {
  //   const modalRef = this.modal.create({
  //     nzTitle: '申诉',
  //     nzWidth: '40%',
  //     nzContent: CtcAppealComponent,
  //     nzComponentParams: {
  //       i: item,
  //       status: 'add'
  //     },
  //     nzFooter: null
  //   });
  //   modalRef.afterClose.subscribe(res => {
  //     if (res) {
  //       this.search({ representationsStatus: '' });
  //     }
  //   })
  // }

  /**
   * 上传
   */
  upload() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要上传的数据');
      return;
    }
    const ids = this.selectedRows.map(i => i?.id);
    this.service.request(this.service.$api_fund_reporting_upload, ids).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('上传成功');
        this.search();
      }
    })
  }




  /**
   * 查看校验结果
   */
  viewResult(record: any) {
    const modalRef = this.modal.create({
      nzTitle: '校验结果',
      nzWidth: 1200,

      nzContent: DatatableReportingFundInfoComponent,
      nzComponentParams: {
        record
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe(res => {
    })
  }



  /**
   * 查看监管审核结果
   */
  viewAuditResult(record: any) {
    if (record?.verifyStatus !== '2') {
      return;
    }
    this.openWainingModal('监管审核结果', record?.uploadResult)
  }

  /**
   * 更新数据
   */
  updateData() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要更新的数据');
      return;
    }
    const ids = this.selectedRows.map(i => i?.id);
    this.service.request(this.service.$api_update_fund_data, ids).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('更新成功');
        this.selectedRows = [];
        this.st.reload();

      }
    })
  }


  search() {
    this.selectedRows = [];
    this.st.load(1);
  }

  /**
  * 异步导出
  */
  export() {
    this.service.exportStart({ ...this.sf.value, pageSize: -1 }, this.service.$api_export_fund_reporting);
  }

  openWainingModal(content: string, title = '提示') {
    this.modal.warning({
      nzMask: false,
      nzTitle: title,
      nzContent: content,
    })
  }

  changeSt(e: STChange): void {

    if (e.type === 'checkbox') {
      const checkRows = (e.checkbox as STData[]) || [];
      //判断当前页是否有选中的行
      if (checkRows.length === 0) {
        // 当前页没有存在已勾选的行，移除之前所记录的当前页的行
        const stList = this.st.list;
        stList.forEach(item => {
          this.selectedRows = this.selectedRows.filter((e: any) => e.id !== item.id);
        })
      } else {
        //添加新增的行
        checkRows.forEach((item: any) => {
          const newSelectedList = this.selectedRows.filter((r: any) => r.id === item.id);
          if (newSelectedList.length === 0) {
            this.selectedRows.push(item);

          }
        })
        // 移除取消选中的行
        const stList = this.st.list;
        stList.forEach(item => {
          if (!item.checked) {
            const index = this.selectedRows.findIndex(_item => item.id === _item.id);
            if (index !== -1) this.selectedRows.splice(index, 1);
          }
        })
      }
    } else if (e.type === 'loaded') {
      // 页面加载时勾选
      (e?.loaded || []).forEach((r: any) => {
        this.selectedRows.forEach((x) => {
          if (x.id === r.id) {
            r.checked = true;
          }
        });
      });
    }
  }

  routeToOrder(item: any) {
    if (item.orderType === '1') {
      window.open(location.origin + `/#/order-management/vehicle/vehicle-detail/${item.orderId}`);
    } else {
      window.open(location.origin + `/#/order-management/bulk/bulk-detail/${item.orderId}`);
    }
  }

  routeTowaybill(item: any) {
    if (item.orderType === '1') {
      window.open(location.origin + `/#/waybill-management/vehicle/vehicle-detail/${item.wayBillId}`);

    } else {
      window.open(location.origin + `/#/waybill-management/bulk/bulk-detail/${item.wayBillId}`);

    }
  }


}
