import {Component, OnDestroy, OnInit} from '@angular/core';
import {environment} from '../../../../environments/environment';

import {DiscountService} from '../../../services/discount.service';
import {CouponService} from '../../../services/coupon.service';
import {IconService} from '../../../services/icon.service';

import {CommonsService} from '../../../services/commons.service';
import {RechargeService} from '../../../services/recharge.service';
import {NzMessageService, NzNotificationService} from 'ng-zorro-antd';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';

@Component({
  selector: 'app-order-list',
  templateUrl: './order-list.component.html',
  styleUrls: ['./order-list.component.scss']
})
export class OrderListComponent implements OnInit , OnDestroy {
  FILE_URL = environment.imageUrl;
  searchForm: FormGroup; // 搜索框
  validateForm: FormGroup; // 添加框
  requestData = []; // 列表数据

  total: number; // 页码
  pageNum = 1; // 页码
  pageSize = 10; // 条码
  loading = true;
  isVisible = false;
  id: number;
  edit = false;
  data = {};
  private timer; // 定时器
  constructor(
      private form: FormBuilder,
      private recharge: RechargeService,
      private discount: DiscountService,
      private coupon: CouponService,
      private iconService: IconService,
      private message: NzMessageService,
      private router: Router,
      private notification: NzNotificationService,
      private common: CommonsService
  ) {
  }

  ngOnInit(): void {
    this.init();
    this.timer = setInterval(() => { // 设置定时刷新事件，每隔1分钟刷新
      this.recharge.countOrder(data => {
        if (data['return_data'] > 0) {
          this.getRequest(true, this.searchForm.value);
          this.notification.info(
              '充值订单',
              '您有' + data['return_data'] + '条未充值的订单，请尽快充值，点击可查看未充值订单！'
          ).onClick.subscribe(() => {
            this.searchForm.value.status = 2;
            this.getRequest(true, this.searchForm.value);
          });
        }
      });
    }, 10000);
  }

  // 销毁
  ngOnDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

  public init(): void {
    this.searchForm = this.form.group({
      status: [null],
      orderNo: [null],
      rechargeModel: [null],
      idCard: [null],
      rechargeContent: [null],
      userPhone: [null],
      payTime: [null],
      payType: [null],
      createTime: [null],
    });
    this.validateForm = this.form.group({
      type: [null, [Validators.required]],
      price: [null, [Validators.required]],
      realPrice: [null, [Validators.required]],
    });

    this.getRequest(true, this.searchForm.value);
  }

  // 查询列表
  public getRequest(reset: boolean = false, whereObject: object) {
    if (whereObject['payTime'] != null && whereObject['payTime'].length !== 0) {
      whereObject['payTimeS'] = whereObject['payTime'][0].getTime();
      whereObject['payTimeE'] = whereObject['payTime'][1].getTime();
    }

    if (whereObject['createTime'] != null && whereObject['createTime'].length !== 0) {
      whereObject['createTimeS'] = whereObject['createTime'][0].getTime();
      whereObject['createTimeE'] = whereObject['createTime'][1].getTime();
    }
    this.loading = false;
    if (reset) {
      this.pageNum = 1;
    }
    whereObject['pageNum'] = this.pageNum;
    whereObject['pageSize'] = this.pageSize;
    this.recharge.getOrderList(whereObject, data => {
      if (data['return_code'] === '000000') {
        this.requestData = data['return_data'].list;
        this.total = data['return_data'].total;
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }

  // 重置
  public resetForm(): void {
    this.searchForm.reset();
  }

  // 详情
  public getDetail(id: number): void {
    this.id = id;
    this.recharge.getOrderById(id , data => {
      if (data['return_code'] === '000000') {
        console.log(data);
        this.data = data['return_data'];
      } else {
        this.message.error(data['return_msg']);
      }
    });

    this.isVisible = true;
  }


  handleCancel(): void {
    this.isVisible = false;
  }


  public finishOrder(id: number): void {
    this.common.showConfirm('确认订单是否完成充值', item => {
      if (item) {
        this.recharge.finishOrder(id, data => {
          if (data['return_code'] === '000000') {
            this.getRequest(false, this.searchForm.value);
            this.isVisible = false;
            this.message.success('充值成功');
          } else {
            this.message.error(data['return_msg']);
          }
        });
      }
    });

  }

  public orderToRefund(id): void {
    this.common.showConfirm('确认订单是否退款', item => {
      if (item) {
        this.recharge.orderToRefund(id, data => {
          if (data['return_code'] === '000000') {
            this.message.success('退款成功');
            this.getRequest(false, this.searchForm.value);
          } else {
            this.message.error(data['return_msg']);
          }
        });
      }
    });
  }

  public postRefund(orderNo): void {
    this.common.showConfirm('确认订单申请退款', item => {
      if (item) {
        this.recharge.postRefund({
          refundSource: 1 ,
          sourceOrderNo: orderNo
        }, data => {
          if (data['return_code'] === '000000') {
            this.message.success('申请成功');
            this.getRequest(false, this.searchForm.value);
          } else {
            this.message.error(data['return_msg']);
          }
        });
      }
    });
  }



  // 下载模板
  downloadTemplate(whereObject) {
    if (whereObject['payTime'] != null && whereObject['payTime'].length !== 0) {
      whereObject['payTimeS'] = whereObject['payTime'][0].getTime();
      whereObject['payTimeE'] = whereObject['payTime'][1].getTime();
    }
    if (whereObject['createTime'] != null && whereObject['createTime'].length !== 0) {
      whereObject['createTimeS'] = whereObject['createTimeS'][0].getTime();
      whereObject['createTimeE'] = whereObject['createTimeE'][1].getTime();
    }
    this.recharge.exportOrderList(whereObject, data => {
      if (data['return_code'] === '000000') {
        window.location.href = this.FILE_URL + data['return_data'];
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }


}
