import {Component, OnInit} from '@angular/core';
import {environment} from "../../../../environments/environment";
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup} from "@angular/forms";
import {NzModalComponent, NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {NzMessageService} from "ng-zorro-antd/message";
import {TradeOrderService} from "../../../services/trade-order.service";
import {StoreService} from "../../../services/store.service";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
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 {NzTabComponent, NzTabSetComponent} from "ng-zorro-antd/tabs";
import {NzDescriptionsComponent, NzDescriptionsItemComponent} from "ng-zorro-antd/descriptions";
import {TradeOrderRefundStatusPipe} from "../../../pipes/trade-order/trade-order-refund-status.pipe";
import {TradeOrderStatusPipe} from "../../../pipes/trade-order/trade-order-status.pipe";
import {CreateTypePipe} from "../../../pipes/trade-order/create-type.pipe";
import {NzBreadCrumbComponent, NzBreadCrumbItemComponent} from "ng-zorro-antd/breadcrumb";
import {NzDropDownADirective, NzDropDownDirective, NzDropdownMenuComponent} from "ng-zorro-antd/dropdown";
import {NzMenuDirective, NzMenuItemComponent} from "ng-zorro-antd/menu";
import {BrowserStorageService} from "../../../utils/localStorage.service";
import {NzRadioComponent, NzRadioGroupComponent} from "ng-zorro-antd/radio";
import {DateSelectType, DateUtils} from "../../../utils/dateUtils.service";

@Component({
  selector: 'app-trade-order-list',
  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,
    NzTabComponent,
    NzDescriptionsComponent,
    NzDescriptionsItemComponent,
    TradeOrderRefundStatusPipe,
    TradeOrderStatusPipe,
    CreateTypePipe,
    NzTabSetComponent,
    NzBreadCrumbComponent,
    NzBreadCrumbItemComponent,
    NzDropdownMenuComponent,
    NzMenuItemComponent,
    NzDropDownADirective,
    NzMenuDirective,
    NzDropDownDirective,
    NzModalModule,
    NzTableModule,
    NzFormModule,
    NzSpinModule,
    NzRadioGroupComponent,
    NzRadioComponent,
    NzDatePickerModule
  ],
  templateUrl: './trade-order-list.component.html',
  styleUrl: './trade-order-list.component.less'
})
export class TradeOrderListComponent implements OnInit {
  FILE_URL = environment.imageUrl;
  loading = false;
  dataObject: any = {};
  tableLoading = true;
  searchForm: UntypedFormGroup;
  pageNum: number;
  whereObject: any = {};
  userObjectType: number;
  storeArray = [];

  loadingObject = {
    spinning: false,
    msg: '加载中'
  };

  totalData: any = {
    totalCount: 0,
    totalPrice: 0,
  };

  isCollapse = false;
  // 时间类型选择
  dateTypeSelect = DateSelectType;

  ngOnInit(): void {
  }
  constructor(private store: BrowserStorageService, // 数据请求
              private modal: NzModalService,
              private message: NzMessageService,
              private tradeOrderService: TradeOrderService,
              private storeService: StoreService,
              private form: UntypedFormBuilder) {
    this.userObjectType = this.store.get(ADMIN_INFO_OBJECT)['secUser']['objectType'];
    // 用户来源 0：超级管理员  1：公司  2：代理商  3：业务员  4：商户  5：门店
    if (this.userObjectType === 4) {
      // 查询门店
      this.storeService.getStoreListByMer({ merId: this.store.get(ADMIN_INFO_OBJECT)['mer']['id'], pageNum : 1, pageSize: 99999}, data => {
        this.storeArray = data['return_data']['list'];
      });
    }
    this.searchForm = this.form.group({
      salesmanId: [null],
      merNo: [null],
      merId: [null],
      merName: [null],
      merAbbreviate: [null],
      storeName: [null],
      outTradeNo: [null],
      accTradeNo: [null],
      payMode: [null],
      payTime: [null],
      payTimeS: [null],
      payTimeE: [null],
      status: ['3'],
      specialField: [null],
      createTimeArray: [[]],
      createTimeSelect: ['1'],
      createTimeS: [''],
      createTimeE: [''],
    });

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

    // 请求数据
    this.requestData(1);
  }


  /**
   * 创建时间初始化
   */
  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) {
    this.tableLoading = true;

    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.whereObject['pageNum'] = pageNum;
    this.whereObject['pageSize'] = 10;
    this.whereObject['status'] = this.searchForm.controls['status'].value;
    this.whereObject['tm'] = new Date().getTime();
    this.tradeOrderService.getOrderList(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        this.dataObject = data['return_data'];
      } else {
        this.modal.error(data['return_msg']);
      }
      this.tableLoading = false;
    });

    this.tradeOrderService.countOrderData(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        this.totalData = data['return_data'];
      } else {
        this.modal.error(data['return_msg']);
      }
      this.tableLoading = false;
    });
  }

  /**
   * 搜索
   * @param whereObject 条件
   */
  search(whereObject: object) {
    if (whereObject['payTime'] != null) {
      whereObject['payTimeS'] = new Date(whereObject['payTime'][0]).getTime();
      whereObject['payTimeE'] = new Date(whereObject['payTime'][1]).getTime();
    }
    this.whereObject = whereObject;
    this.requestData(1);
  }

  /**
   * 重置
   */
  resetForm(): void {
    this.searchForm.reset();
    this.searchForm.controls['status'].setValue('3');
    this.searchForm.controls['createTimeSelect'].setValue('1');
  }

  /**
   * 弹出退款对话框
   */
  showOrderRefundConfirm(outTradeNo: string, refundAmount: string): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '确定退款吗？',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.requestOrderRefund(outTradeNo, refundAmount)
    });
  }

  /**
   * 删除数据
   *
   */
  requestOrderRefund(outTradeNo: string, refundAmount: string) {
    this.loading = true;
    this.tradeOrderService.refund({ outTradeNo, refundAmount}, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '处理成功',
          nzOnOk: () => this.requestData(this.whereObject['pageNum'])
        });
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
      this.loading = false;
    });
  }

  exportTradeOrder() {
    this.loadingObject.spinning = true;
    this.loadingObject.msg = '导出中...';
    this.tradeOrderService.exportTradeOrder(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        window.location.href = this.FILE_URL + data['return_data'];
      } else {
        this.message.error(data['return_msg']);
      }
      this.loadingObject.spinning = false;
    });
  }

  toggleCollapse(): void {
    this.isCollapse = !this.isCollapse;
  }

}
