import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {OrganizationService} from '../../../services/organization.service';
import {LocalStorageService} from '../../../services/local-storage.service';
import {ADMIN_INFO_OBJECT} from '../../../services/local-storage.namespace';
import {CompanyAccountService} from '../../../services/company-account.service';

@Component({
  selector: 'app-company-amount-record',
  templateUrl: './company-amount-record.component.html',
  styleUrls: ['./company-amount-record.component.scss']
})
export class CompanyAmountRecordComponent implements OnInit {
  roleType;
  adminFlag;

  dataObject: any = {};
  tableLoading = true;
  searchForm: FormGroup;
  pageNum: number;
  whereObject: any = {};

  rechargeModal = false;
  rechargeForm: FormGroup;
  rechargeParam = {
    phone: null,
    orgId: null,
    amount: null,
    smsCode: null,
  };
  submitRechargeBtnLoading = false;

  smsCodeBtnName = '获取验证码';
  smsCodeBtnLoading = false;
  countdownTime;

  orgArray = [];
  accountObject = {
    amounts: 0
  };

  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private store: LocalStorageService,
              private companyAccountService: CompanyAccountService,
              private organizationService: OrganizationService,
              private form: FormBuilder) {
    this.roleType = Number(this.store.get(ADMIN_INFO_OBJECT)['secRole'].roleType);
    this.adminFlag = Number(this.store.get(ADMIN_INFO_OBJECT)['secUser'].adminFlag);
  }

  ngOnInit(): void {
    this.searchForm = this.form.group({
      orgId: [null],
      type: [null],
      sourceType: [null],
      createTime: [null],
      createTimeS: [null],
      createTimeE: [null],
    });

    this.rechargeForm = this.form.group({
      orgId: [null, [Validators.required]],
      amount: [null, [Validators.required]],
      smsCode: [null, [Validators.required]],
    });

    if (this.roleType === 5 && this.adminFlag === 1) {
      this.organizationService.getOrganizationList(this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['id'], data => {
        this.orgArray = data['return_data'];
      });
    }

    if (this.roleType === 5 && this.adminFlag === 0) {
      this.companyAccountService.getAccount(data => {
        this.accountObject = data['return_data'];
      });
    }

    this.requestData(1);
  }

  /**
   * 请求数据
   */
  requestData(pageNum) {
    this.tableLoading = true;
    this.whereObject['pageNum'] = pageNum;
    this.whereObject['pageSize'] = 10;
    this.companyAccountService.getAmountRecordList(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        this.dataObject = data['return_data'];
      } else {
        this.modal.error(data['return_msg']);
      }
      this.tableLoading = false;
    });
  }

  /**
   * 搜索
   * @param whereObject 条件
   */
  search(whereObject: object) {
    this.whereObject = whereObject;
    if (this.searchForm.value.createTime != null) {
      this.searchForm.value.createTimeS = new Date(this.searchForm.value.createTime[0]).getTime();
      this.searchForm.value.createTimeE = new Date(this.searchForm.value.createTime[1]).getTime();
    } else {
      this.searchForm.value.createTimeS = null;
      this.searchForm.value.createTimeE = null;
    }
    this.requestData(1);
  }

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

  /**
   * 展示充值模态框
   */
  showRechargeModal() {
    this.rechargeModal = true;
  }

  /**
   * 关闭充值模态框
   */
  closeRechargeModal() {
    this.rechargeModal = false;
  }

  /**
   * 提交充值
   */
  submitRecharge() {
    this.submitRechargeBtnLoading = true;
    for (const i in this.rechargeForm.controls) {
      this.rechargeForm.controls[i].markAsDirty();
      this.rechargeForm.controls[i].updateValueAndValidity();
    }
    if (this.rechargeForm.status == null || this.rechargeForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有必填项',
      });
      this.submitRechargeBtnLoading = false;
      return;
    }

    this.rechargeParam.smsCode = this.rechargeForm.value['smsCode'];
    this.companyAccountService.recharge(this.rechargeParam, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '充值成功',
        });

        this.rechargeForm.controls.orgId.enable();
        this.rechargeForm.controls.amount.enable();
        this.rechargeForm = this.form.group({
          orgId: [null, [Validators.required]],
          amount: [null, [Validators.required]],
          smsCode: [null, [Validators.required]],
        });

        this.closeRechargeModal();
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
      this.submitRechargeBtnLoading = false;
    });
  }

  /**
   * 发送验证码
   */
  sendSmsCode() {
    this.rechargeForm.controls.orgId.enable();
    this.rechargeForm.controls.amount.enable();

    if (this.rechargeForm.value.orgId == null) {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请选择部门',
      });
      return;
    }

    this.rechargeParam.phone = '13251378838';
    this.rechargeParam.orgId = this.rechargeForm.value['orgId'];
    this.rechargeParam.amount = this.rechargeForm.value['amount'];

    this.rechargeForm.controls.orgId.disable();
    this.rechargeForm.controls.amount.disable();
    this.companyAccountService.sendRechargeSmsCode('13251378838', this.rechargeParam.orgId, this.rechargeParam.amount, data => {
      if (data['return_code'] === '000000') {
        this.getVerifyCodeCountdown();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
        this.rechargeForm.controls.orgId.enable();
        this.rechargeForm.controls.amount.enable();
      }
    });
  }

  /**
   * 获取验证码倒计时
   */
  getVerifyCodeCountdown() {
    let countdownSecond = 60; // 倒计时60秒
    this.countdownTime = setInterval(() => {
      if (countdownSecond <= 1) {
        this.smsCodeBtnName = '获取验证码';
        this.smsCodeBtnLoading = false;
        clearInterval(this.countdownTime);
      } else {
        countdownSecond--;
        this.smsCodeBtnName = String(countdownSecond);
        this.smsCodeBtnLoading = true;
      }
    }, 1000);
  }
}

