import { Component } from '@angular/core';
import {BreadcrumbComponent} from "../../common/breadcrumb/breadcrumb.component";
import {DatePipe, NgForOf, NgIf} from "@angular/common";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {
  NzCellFixedDirective,
  NzTableCellDirective,
  NzTableComponent, NzTableModule,
  NzTbodyComponent, NzTheadComponent,
  NzThMeasureDirective, NzTrDirective
} from "ng-zorro-antd/table";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {NzDatePickerComponent, NzDatePickerModule, NzRangePickerComponent} from "ng-zorro-antd/date-picker";
import {
  NzFormDirective,
  NzFormModule
} from "ng-zorro-antd/form";
import {NzIconDirective} from "ng-zorro-antd/icon";
import {NzInputDirective} from "ng-zorro-antd/input";
import {NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {NzOptionComponent, NzSelectComponent} from "ng-zorro-antd/select";
import {NzRadioComponent, NzRadioGroupComponent} from "ng-zorro-antd/radio";
import {NzSpinComponent, NzSpinModule} from "ng-zorro-antd/spin";
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup} from "@angular/forms";
import {TradeSharingCmdTypePipe} from "../../../pipes/trade-order/trade-sharing-cmd-type.pipe";
import {TradeSharingStatusPipe} from "../../../pipes/trade-order/trade-sharing-status.pipe";
import {RouterLink} from "@angular/router";
import {SalesmanStatusPipe} from "../../../pipes/salesman-status.pipe";
import {AgentStatusPipe} from "../../../pipes/agent-status.pipe";
import {NzContentComponent, NzLayoutComponent} from "ng-zorro-antd/layout";
import {NzTypographyComponent} from "ng-zorro-antd/typography";
import {NzDropDownADirective, NzDropDownDirective, NzDropdownMenuComponent} from "ng-zorro-antd/dropdown";
import {NzMenuDirective, NzMenuItemComponent} from "ng-zorro-antd/menu";
import {PayModePipe} from "../../../pipes/trade-order/pay-mode.pipe";
import {SettleTypePipe} from "../../../pipes/trade-order/settle-type.pipe";
import {DateSelectType, DateUtils} from "../../../utils/dateUtils.service";
import {NzMessageService} from "ng-zorro-antd/message";
import {PlatformService} from "../../../services/platform.service";
import {TradeProfitSharingService} from "../../../services/trade-profit-sharing.service";
import {BrowserStorageService} from "../../../utils/localStorage.service";
import {MerService} from "../../../services/mer.service";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
import {environment} from "../../../../environments/environment";

@Component({
  selector: 'app-sharing-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,
    NzLayoutComponent,
    NzContentComponent,
    NzTypographyComponent,
    NzModalModule,
    NzTableModule,
    NzFormModule,
    NzSpinModule,
    NzRadioGroupComponent,
    NzRadioComponent,
    NzDatePickerModule,
    TradeSharingCmdTypePipe,
    TradeSharingStatusPipe,
    NzDropDownADirective,
    NzDropDownDirective,
    NzDropdownMenuComponent,
    NzMenuDirective,
    NzMenuItemComponent,
    PayModePipe,
    SettleTypePipe
  ],
  templateUrl: './sharing-detail.component.html',
  styleUrl: './sharing-detail.component.less'
})
export class SharingDetailComponent {
  tableLoading = true;
  searchForm: UntypedFormGroup;
  pageNum = 1;
  pageSize = 10;
  whereObject: any = {};
  loadingObject = {
    spinning: false,
    msg: '处理中'
  };
  merArray = [];
  tableData: any = {
    total: 0,
    list: [],
  };
  currentDate = new Date();
  // 角色类型 0：超级管理员  1：公司  2：代理商  3：业务员  4：商户  5：门店
  roleType: number;
  // 时间类型选择
  dateTypeSelect = DateSelectType;
  // 接收方数据
  receiverModal = false;
  receiverData = [];
  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private form: UntypedFormBuilder,
              private platformService: PlatformService,
              private tradeProfitSharingService: TradeProfitSharingService,
              private localStorage: BrowserStorageService,
              private merService: MerService) {
    this.searchForm = this.form.group({
      merNo: [null],
      profitSharingOrderNo: [null],
      platformProfitSharingOrderNo: [null],
      platformTradeNo: [null],
      receiverNo: [null],
      cmdType: [""],
      status: [""],
      createTimeArray: [[]],
      createTimeSelect: ['1'],
      createTimeS: [''],
      createTimeE: [''],
    });

    // 初始化创建时间
    this.createTimeInit();
  }

  ngOnInit(): void {
    this.roleType = this.localStorage.get(ADMIN_INFO_OBJECT)['secRole'].roleType;
    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(1,10);
        }
      });
    } 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(1,10);
    }
  }

  /**
   * 创建时间初始化
   */
  createTimeInit() {
    let createTimeSelect = this.searchForm.controls['createTimeSelect'].value;
    if (createTimeSelect != null) {
      let timeObj = DateUtils.getDate(new Date(), Number(createTimeSelect));
      this.searchForm.controls['createTimeArray'].setValue([timeObj.timeS, timeObj.timeE]);
    }
  }

  /**
   * 请求数据
   */
  requestData(pageNum: number,pageSize: number) {
    this.tableLoading = true;
    this.whereObject = this.searchForm.value;

    if (this.searchForm.controls['createTimeArray'].value != null
      && this.searchForm.controls['createTimeArray'].value.length > 0) {
      this.whereObject['createTimeS'] = new Date(this.searchForm.controls['createTimeArray'].value[0]).getTime();
      this.whereObject['createTimeE'] = new Date(this.searchForm.controls['createTimeArray'].value[1]).getTime();
    } else {
      this.whereObject['createTimeS'] = null;
      this.whereObject['createTimeE'] = null;
    }
    this.pageNum = pageNum;
    this.pageSize = pageSize;
    this.whereObject['pageNum'] = pageNum;
    this.whereObject['pageSize'] = pageSize;
    this.tradeProfitSharingService.getReceiverList(this.whereObject, (data: any) => {
      if (data['return_code'] === '000000') {
        this.tableData = data['return_data'];
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
      this.tableLoading = false;
    });
  }

  /**
   * 搜索
   * @param whereObject 条件
   */
  search(whereObject: object) {
    this.whereObject = whereObject;
    this.requestData(1, this.pageSize);
  }

  /**
   * 重置
   */
  resetForm(): void {
    const oldMerNo = this.searchForm.controls['merNo'].value;
    this.searchForm.reset();
    this.searchForm.controls['merNo'].setValue(this.merArray.length > 0 ? oldMerNo : null);
    this.searchForm.controls['createTimeSelect'].setValue('1');
  }

  download() {
    this.loadingObject.spinning = true;
    this.loadingObject.msg = '处理中...';
    this.tradeProfitSharingService.exportReceiver(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;
    });
  }
}
