import {Component, OnInit} from '@angular/core';
import differenceInCalendarDays from "date-fns/differenceInCalendarDays";
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup} from "@angular/forms";
import {NzModalComponent, NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {NzMessageService} from "ng-zorro-antd/message";
import {PlatformService} from "../../../services/platform.service";
import {MerService} from "../../../services/mer.service";
import {TradeCheckingService} from "../../../services/trade-checking.service";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
import {environment} from "../../../../environments/environment";
import {RouterLink} from "@angular/router";
import {SalesmanStatusPipe} from "../../../pipes/salesman-status.pipe";
import {DatePipe, NgForOf, NgIf} from "@angular/common";
import {BreadcrumbComponent} from "../../common/breadcrumb/breadcrumb.component";
import {NzFormDirective, NzFormModule} from "ng-zorro-antd/form";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {NzOptionComponent, NzSelectComponent} from "ng-zorro-antd/select";
import {NzInputDirective} from "ng-zorro-antd/input";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {NzIconDirective} from "ng-zorro-antd/icon";
import {NzCellFixedDirective, NzTableComponent, NzTableModule, NzThMeasureDirective} from "ng-zorro-antd/table";
import {AgentStatusPipe} from "../../../pipes/agent-status.pipe";
import {NzSpinComponent, NzSpinModule} from "ng-zorro-antd/spin";
import {NzDatePickerComponent, NzDatePickerModule} from "ng-zorro-antd/date-picker";
import {SettleTypePipe} from "../../../pipes/trade-order/settle-type.pipe";
import {PayModePipe} from "../../../pipes/trade-order/pay-mode.pipe";
import {NzDividerComponent} from "ng-zorro-antd/divider";
import {BrowserStorageService} from "../../../utils/localStorage.service";
import {NzRadioComponent, NzRadioGroupComponent} from "ng-zorro-antd/radio";
import {NzTypographyComponent} from "ng-zorro-antd/typography";

@Component({
  selector: 'app-trade-checking-detail',
  standalone: true,
  imports: [
    RouterLink,
    SalesmanStatusPipe,
    DatePipe,
    BreadcrumbComponent,
    NzFormDirective,
    NzRowDirective,
    NzColDirective,
    NzSelectComponent,
    NzOptionComponent,
    ReactiveFormsModule,
    NgIf,
    NzInputDirective,
    NzButtonComponent,
    NzIconDirective,
    NzTableComponent,
    NzThMeasureDirective,
    NzCellFixedDirective,
    NgForOf,
    AgentStatusPipe,
    NzSpinComponent,
    NzDatePickerComponent,
    SettleTypePipe,
    PayModePipe,
    NzModalComponent,
    NzDividerComponent,
    NzModalModule,
    NzTableModule,
    NzFormModule,
    NzSpinModule,
    NzRadioGroupComponent,
    NzRadioComponent,
    NzDatePickerModule,
    NzTypographyComponent
  ],
  templateUrl: './trade-checking-detail.component.html',
  styleUrl: './trade-checking-detail.component.less'
})
export class TradeCheckingDetailComponent implements OnInit {
  tableLoading = true;
  searchForm: UntypedFormGroup;
  pageNum = 1;
  pageSize = 10;
  whereObject: any = {};
  merArray = [];
  loadingObject = {
    spinning: false,
    msg: '处理中'
  };
  dataObject = {
    totalTradeNum: 0,
    totalTradeAmount: 0,
    totalSettleAmount: 0,
    totalShdFeeAmount: 0,
    settleDetailList: {
      total: 0,
      list: []
    }
  };
  dataDetailModal = false;
  currentDate = new Date();
  // 角色类型 0：超级管理员  1：公司  2：代理商  3：业务员  4：商户  5：门店
  roleType: number;
  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private form: UntypedFormBuilder,
              private platformService: PlatformService,
              private localStorage: BrowserStorageService,
              private merService: MerService,
              private tradeCheckingService: TradeCheckingService) {
  }

  ngOnInit(): void {
    this.roleType = this.localStorage.get(ADMIN_INFO_OBJECT)['secRole'].roleType;
    this.currentDate.setDate(this.currentDate.getDate() - 1);
    this.searchForm = this.form.group({
      merNo: [null],
      outTradeNo: [null],
      accTradeNo: [null],
      settleTimeS: [ this.currentDate.getTime() ],
      settleTimeE: [ this.currentDate.getTime() ],
    });

    if (this.roleType == 1 || this.roleType == 2) {
      this.merService.getMerList({ merStatus: 1, pageNum: 1, pageSize: 9999}, data => {
        this.merArray = data['return_data']['list'];
        if (this.merArray.length > 0) {
          this.searchForm.controls['merNo'].setValue(this.merArray[0]['merNo']);
          this.requestData(this.pageNum, this.pageSize);
        }
      });
    } else if (this.roleType == 4) {
      this.merArray.push(this.localStorage.get(ADMIN_INFO_OBJECT)['mer']);
      this.searchForm.controls['merNo'].setValue(this.merArray[0]['merNo']);
      this.requestData(this.pageNum, this.pageSize);
    }
  }

  /**
   * 请求数据
   */
  requestData(pageNum: number, pageSize: number) {
    this.tableLoading = true;
    this.pageNum = pageNum;
    this.pageSize = pageSize;
    this.searchForm.value['pageNum'] = pageNum;
    this.searchForm.value['pageSize'] = pageSize;
    this.tradeCheckingService.queryCheckingDetail(this.searchForm.value, data => {
      if (data['return_code'] === '000000') {
        this.dataObject = data['return_data'];
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
      this.tableLoading = false;
    });
  }

  /**
   * 搜索
   * @param whereObject 条件
   */
  search(whereObject: object) {
    whereObject['settleTimeS'] = new Date(whereObject['settleTimeS']).getTime();
    whereObject['settleTimeE'] = new Date(whereObject['settleTimeE']).getTime();
    this.whereObject = whereObject;
    this.requestData(1, this.pageSize);
  }

  /**
   * 重置
   */
  resetForm(): void {
    this.searchForm.reset();
    this.searchForm.controls['merNo'].setValue(this.merArray.length > 0 ? this.merArray[0]['merNo'] : null);
    this.searchForm.controls['settleTimeS'].setValue(this.currentDate.getTime());
    this.searchForm.controls['settleTimeE'].setValue(this.currentDate.getTime());
  }

  download() {
    this.loadingObject.spinning = true;
    this.loadingObject.msg = '处理中...';
    this.tradeCheckingService.exportCheckingDetail(this.searchForm.value, data => {
      if (data['return_code'] === '000000') {
        window.location.href = environment.imageUrl + data['return_data'];
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
      this.loadingObject.spinning = false;
    });
  }

  showDetailModal(settleDay: string) {
    this.dataDetailModal = true;
  }

  closeDetailModal() {
    this.dataDetailModal = false;
  }

  disabledDate = (current: Date): boolean => {
    // Can not select days before today and today
    return differenceInCalendarDays(current, new Date()) > 0;
  };


  searchSettleTime(dateType: number, selectDate: Date) {
    const currentDate = new Date();
    if (currentDate.getFullYear() === selectDate.getFullYear()
      && currentDate.getMonth() === selectDate.getMonth()
      && currentDate.getDate() === selectDate.getDate()) {
      this.modal.error({
        nzTitle: '提示',
        nzContent: '无法选择当日，当日还未清算'
      });
      return;
      // 起始时间
      if (dateType === 1) {
        this.searchForm.controls['settleTimeS'].setValue(this.currentDate.getTime());
        // 终止时间
      } else if (dateType === 2) {
        this.searchForm.controls['settleTimeE'].setValue(this.currentDate.getTime());
      }
    }
  }
  showPrint() {
    console.log(document.getElementById('print-content').innerHTML);
    const oblHtml = window.document.body.innerHTML;
    const bdhtml = document.getElementById('print-content').innerHTML;
    window.document.body.innerHTML = bdhtml;
    window.print();
    document.body.innerHTML = oblHtml;
    window.location.reload();
  }


  // 此处为图文打印
  printQrCode(idstr) {
    /*    const imgUrlStr = 'https://weiliicimg9.pstatp.com/weili/l/905526294583705654.jpg';
        let iframe = document.createElement('IFRAME'),
            doc = null,
            img = new Image();
        img.src = imgUrlStr;
        iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
        document.body.appendChild(iframe);
        doc = iframe.contentWindow.document;
        doc.write('<h2>Print Pictures and Words</h2>');
        doc.body.append(img);
        console.log(doc.body.innerHTML);
        doc.close();
        const newWindow = window.open('', '');
        newWindow.document.write(doc.body.innerHTML);
        newWindow.print();
        newWindow.close();*/

    /*    iframe.onload = function() { //解决图片显示不了的问题
          iframe.contentWindow.focus();
          iframe.contentWindow.print();
          document.body.removeChild(iframe);
        };*/
  }
}

