import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STComponent, STColumn, STChange, STRequestOptions, STData } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema } from '@delon/form';
import { ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FreightAccountService } from 'src/app/routes/financial-management/services/freight-account.service';
import Big from 'src/app/shared/utils/deal-precision';
import { RecordedService } from '../../services/recorded.service';


@Component({
  selector: 'app-partner-recorded-record',
  templateUrl: './record.component.html',
  styleUrls: ['../../../../commom/less/box.less', '../../../../commom/less/expend-but.less']
})
export class PartnerRecordedRecordComponent implements OnInit {
  @ViewChild('st', { static: true }) st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('auditModal', { static: false }) auditModal!: any;
  @ViewChild('viewReasonModal', { static: false }) viewReasonModal!: any;
  columns!: STColumn[];
  searchSchema!: SFSchema;
  totalInfo: any = {
    invoiceAmountSum: 0,
    invoiceEntryNum: 0,
    partnerNum: 0,
    recordedAmountSum: 0,
    taxPersonalSum: 0
  }

  _$expand = false;

  selectedRows: any[] = [];
  totalCallNo = 0;
  refundStatus: any = '';

  msg = '';

  ltdId = ''; // 网络货运人
  accountName = ''; // 账户名称


  constructor(public service: RecordedService, private nzModalService: NzModalService,
    private router: Router, public ar: ActivatedRoute, public shipperSrv: ShipperBaseService) {
    this.ltdId = this.ar.snapshot.queryParams?.ltdId || '';

  }

  ngOnInit(): void {
    this.searchSchema = this.initSF();
    this.columns = this.initST();
  }

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

  afterRes = (data: any[], rawData?: any) => {
    // data = data.map(node => ({ ...node, disabled: node.sts !== '0' }));
    return data;
  };

  stChange(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);
          }
        })
      }
      let totalCallNo = 0;
      this.selectedRows.forEach((item => {
        totalCallNo = new Big(this.totalCallNo).plus(item?.entryAmount).parse();
      }));
      this.totalCallNo = totalCallNo;
    } else if (e.type === 'loaded') {
      // 页面加载时勾选
      (e?.loaded || []).forEach((r) => {
        this.selectedRows.forEach((x) => {
          if (x.id === r.id) {
            r.checked = true;
          }
        });
      });
    }
  }

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

  auditAction(item?: any, type: string = '1') {
    if (!item && this.selectedRows.length === 0) {
      this.service.msgSrv.warning('请选择需要审核的记录');
      return;
    }
    this.msg = '';
    let params: Array<string> = [];
    if (item) {
      params = [item.id];
    } else {
      params = this.selectedRows.map(node => node.id);
    }
    const modal = this.nzModalService.create({
      nzTitle: type === '1' ? '审核' : '复审',
      nzContent: this.auditModal,
      nzFooter: [
        {
          label: '拒绝',
          type: 'default',
          onClick: () => {
            if (!this.msg || this.msg.trim().length === 0) {
              this.service.msgSrv.warning('请填写拒绝原因 ');
              return;
            }
            this.audit({ ids: params, rejectReason: this.msg, sts: '3' }, () => {
              modal.destroy();
              this.st.load(1);
            }, '审核拒绝成功');
            // this.service
            //   .request(this.service.$api_disagree_recorded, {
            //     id: params,
            //     rejectReason: this.msg
            //   })
            //   .subscribe(res => {
            //     if (res) {
            //       this.service.msgSrv.success('审核拒绝成功');
            //       modal.destroy();
            //       this.st.load(1);
            //     }
            //   });
          }
        },
        {
          label: '通过',
          type: 'primary',
          onClick: () => {
            this.audit({ ids: params, rejectReason: this.msg, sts: '1' }, () => {
              modal.destroy();
              this.st.load(1);
            }, '审核通过成功');
          }
        }
      ]
    });
    modal.afterClose.subscribe(res => {
      this.st.load();
    });
  }

  showReason(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '查看原因',
      nzContent: item?.rejectionCause || item?.failCause,
      nzFooter: [
        {
          label: '关闭',
          type: 'primary',
          onClick: () => {
            modal.destroy();
          }
        }
      ]
    });
  }

  /**
   * 重置表单
   */
  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
          }
        },
        accountName: {
          type: 'string',
          title: '账户名称',
          default: this.accountName,
          ui: {
            placeholder: '请输入'
          }
        },
        sts: {
          type: 'string',
          title: '入账状态',
          default: '',
          enum: [
            { label: '全部', value: '' },
            { label: '待初审', value: '0' },
            { label: '待复核', value: '1' },
            { label: '已入账', value: '2' },
            { label: '已拒绝', value: '3' },
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          default: this.ltdId,
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.shipperSrv.getNetworkFreightForwarder({}, true),
          }
        },
        submitTime: {
          title: '提交时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true,
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox', className: 'text-center' },
      { title: '账户名称', index: 'accountName', width: 180, className: 'text-center' },
      { title: '虚拟账户', index: 'fictitiousAccount', width: 180, className: 'text-center' },
      { title: '入账单号', index: 'entryNumber', width: 190, className: 'text-center' },
      { title: '网络货运人', index: 'ltdName', width: 220, className: 'text-center' },
      {
        title: '开票金额',
        index: 'amount',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.amount }) }
      },
      {
        title: '代缴个税',
        index: 'taxPersonal',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.amount }) }
      },
      {
        title: '入账金额',
        index: 'entryAmount',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.amount }) }
      },

      { title: '提交时间', index: 'submitTime', width: 180, className: 'text-center' },
      { title: '入账状态', index: 'stsLabel', width: 120, className: 'text-center' },
      {
        title: '操作',
        fixed: 'right',
        width: '110px',
        buttons: [
          {
            text: '审核',
            iif: item => item.sts === '0',
            click: item => this.auditAction(item)
          },
          {
            text: '复审',
            iif: item => item.sts === '1',
            click: item => this.router.navigate(['./detail/' + item.id], { relativeTo: this.ar })
          },
          {
            text: '详情',
            click: item => this.router.navigate(['./detail/' + item.id], { relativeTo: this.ar })
          }
        ]
      }
    ];
  }

  /**
 * 审核
 */
  audit(params: any, callback: Function, msg = '成功') {
    this.service
      .request(this.service.$api_audit_recored, { ...params })
      .subscribe(res => {
        if (res) {
          this.service.msgSrv.success(msg);
          callback();
        }
      });
  }

  search() {
    this.st.load(1);
    this.getSummary();
  }
  /**
   * 底部统计
   */
  getSummary() {
    this.service.request(this.service.$api_get_list_summary, { ...this.sf.value }).subscribe(res => {
      if (res) {
        this.totalInfo = res;
      }
    })
  }
}
