import { debounceTime } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnInit, Output, ViewChild } from '@angular/core';
import { BaseService } from '@shared';
import { SFComponent, SFSchema, SFUISchema } from '@delon/form';
import { EventEmitter} from '@angular/core'
@Component({
  selector: 'app-rebate-table',
  templateUrl: './rebate-table.component.html',
  styleUrls: ['./rebate-table.component.less']
})
export class RebateTableComponent implements OnInit {
  @Input() data: any =[];
  @Output()
  private dataChange: EventEmitter<any> = new EventEmitter();
  emit() {
    this.dataChange.emit(this.data)
  }
  headers: any[] = [];
  gradeConfigId: string ='';
  grage: any[] = [];
  formatterDollar = (value: number): string => `${value}`;
  changeSub = new Subject<string>();
  constructor(public service: BaseService, private cdr: ChangeDetectorRef) {}

  ngOnInit(): void {
   this.data = [
      {
        gradeConfigId: '',
        startAmount: 0,
        endAmount: 0,
        managementFeeRatio: 0,
      }
    ];
    this.loadData();
    this.changeendAmountAction();
  }

  loadData() {
    this.service.request('/api/mdc/partnerGradeConfig/listPartnerGradeConfig').subscribe(res => {
      if (res) {
        console.log(res);
        this.grage = res;
        this.cdr.detectChanges();
      }
    });
    // this.service.request('/api/mdc/pbc/sysConfigItem/findItemValueByItemKeys', [
    //   "rebate.config.minrebatePrice"
    //  ]).subscribe(res => {
    //   if (res) {
    //     console.log(res);
    //   }
    // });
  }



  /**
   * 修改结束公里数
   * @param event 车长
   * @param i 下标
   */
  changeendAmount(event: any, i: number) {
    if (event) {
      console.log(event);

      this.changeSub.next(`${event},${i}`);
    }
  }
  changeendAmountAction() {
    this.changeSub.pipe(debounceTime(500)).subscribe((res: string) => {
      if (res) {
        const paras = res.split(',');
        const num = Number(paras[0]);
        const i = Number(paras[1]);

        if (num <= this.data[i]?.startAmount) {
          console.log(this.data[i].endAmount);
          this.data[i].endAmount = null;
          setTimeout(() => {
            this.data[i].endAmount = this.data[i]?.startAmount + 1 ;
          }, 0);
          this.changeNextstartAmount(this.data[i]?.startAmount + 1, i + 1);
          return;
        }
        this.data[i].endAmount = num;
        this.changeNextstartAmount(num, i + 1);
      }
    });
  }

  add() {
    console.log(this.data);

    const tem = this.data[this.data?.length - 1];
    if (tem) {
      this.data.push({
        gradeConfigId: '',
        startAmount: 0,
        endAmount: 0,
        managementFeeRatio: 0,
      });
      this.data = [...this.data];
    }
  }

  deleteRow(index: number) {
    console.log(index);
    var newArr = this.data.concat();
    newArr.splice(this.data.length-1,1)
    // this.data = this.data.pop()
    console.log(newArr);
    this.data = [...newArr];
  }

  save() {
    console.log(this.data)
    let params= {
      rebateConfigDTOS: this.data
    }
    console.log(params);
    this.service.request('/api/mdc/cuc/rebateConfig/saveBatch', params).subscribe(res => {
      if (res) {
        console.log(res);
        this.service.msgSrv.success('修改成功');
        this.loadData();
      }
    });
  }


  /**
   * 遍历同步后置位公里数
   * @param event  车长
   * @param i 下标
   */
  private changeNextstartAmount(event: number, i: number) {
    if (this.data[i]) {
      this.data[i].startAmount = event;
      if (this.data[i].endAmount <= event) {
        this.data[i].endAmount = this.data[i].startAmount + 1;
        this.changeNextstartAmount(event + 1, i + 1);
      }
    }
  }
}
