import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {LocalStorageService} from '../../../services/local-storage.service';
import {ADMIN_INFO_OBJECT} from '../../../services/local-storage.namespace';
import {OilCardService} from '../../../services/oil-card.service';
import {CompanyAccountService} from '../../../services/company-account.service';
import {OrganizationService} from "../../../services/organization.service";
import {NavigationComponent} from "../../navigation/navigation.component";
import {environment} from "../../../../environments/environment";
import {Router} from "@angular/router";
import {ValidatorsService} from "../../../services/validators.service";

@Component({
  selector: 'app-oil-card-list',
  templateUrl: './oil-card-list.component.html',
  styleUrls: ['./oil-card-list.component.scss']
})
export class OilCardListComponent implements OnInit {
  FILE_URL = environment.imageUrl;
  roleType;
  adminFlag;
  loadingObject = {
    spinning: false,
    msg: '加载中'
  };

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

  generateCardModal = false;
  generateCardForm: FormGroup;

  editContactModal = false;
  editContactForm: FormGroup;
  editContactData = {};

  rechargeModal = false;
  rechargeForm: FormGroup;
  rechargeBtnLoading = false;

  recycleAmountModal = false;
  recycleAmountForm: FormGroup;
  recycleAmountBtnLoading = false;

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

  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private store: LocalStorageService,
              private oilCardService: OilCardService,
              private organizationService: OrganizationService,
              private companyAccountService: CompanyAccountService,
              private router: Router,
              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],
      cardNo: [null],
      contactName: [null],
      contactPhone: [null],
      createTime: [null],
      createTimeS: [null],
      createTimeE: [null],
      bindTime: [null],
      bindTimeS: [null],
      bindTimeE: [null],
      isConfigContact: [null],
      status: [null],
      bindStatus: [null],
    });

    this.editContactForm = this.form.group({
      cardNo: [null, [Validators.required]],
      contactName: [null, [Validators.required]],
      contactPhone: [null, [Validators.required, ValidatorsService.mobile]],
    });

    this.generateCardForm = this.form.group({
      generateNum: [1, [Validators.required]],
    });

    this.rechargeForm = this.form.group({
      cardNo: [{ value: null, disabled: true }, [Validators.required]],
      price: [100, [Validators.required]],
      twoPwd: [null, [Validators.required]],
    });

    this.recycleAmountForm = this.form.group({
      cardNo: [{ value: null, disabled: true }, [Validators.required]],
      amount: [{ value: null, disabled: true }, [Validators.required]],
      twoPwd: [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.getAccount();
    }
    this.requestData(1);
  }

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

  /**
   * 查询账户
   */
  getAccount() {
    this.companyAccountService.getAccount(data => {
      this.accountObject = data['return_data'];
    });
  }

  /**
   * 搜索
   * @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;
    }
    if (this.searchForm.value.bindTime != null) {
      this.searchForm.value.bindTimeS = new Date(this.searchForm.value.bindTime[0]).getTime();
      this.searchForm.value.bindTimeE = new Date(this.searchForm.value.bindTime[1]).getTime();
    } else {
      this.searchForm.value.bindTimeS = null;
      this.searchForm.value.bindTimeE = null;
    }
    this.requestData(1);
  }

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

  /**
   * 展示生成油卡模态框
   */
  showGenerateCardModal() {
    this.generateCardModal = true;
  }

  /**
   * 关闭生成油卡模态框
   */
  closeGenerateCardModal() {
    this.generateCardModal = false;
  }

  /**
   * 提交生成数量
   */
  submitGenerateCard() {
    for (const i in this.generateCardForm.controls) {
      this.generateCardForm.controls[i].markAsDirty();
      this.generateCardForm.controls[i].updateValueAndValidity();
    }
    if (this.generateCardForm.status == null || this.generateCardForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有必填项',
      });
      return;
    }

    this.loadingObject.spinning = true;
    this.loadingObject.msg = '生成油卡中...';
    this.closeGenerateCardModal();

    this.oilCardService.generateCard(this.generateCardForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '生成成功',
        });
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
      this.loadingObject.spinning = false;
    });
  }

  /**
   * 展示编辑联系人模态框
   */
  showEditContactModal(data: object) {
    this.editContactForm.patchValue(data);
    this.editContactData = data;
    this.editContactModal = true;
  }

  /**
   * 关闭编辑联系人模态框
   */
  closeEditContactModal() {
    this.editContactForm.reset();
    this.editContactModal = false;
  }

  /**
   * 提交编辑联系人
   */
  submitEditContact() {
    if (this.editContactData['contactPhone'] != null && this.editContactData['contactPhone'] !== this.editContactForm.value.contactPhone) {
      this.modal.confirm({
        nzTitle: '警告',
        nzContent: '油卡更换联系电话后，油卡会自动与用户解绑！',
        nzOkText: '是',
        nzCancelText: '否',
        nzOkType: 'danger',
        nzOnOk: () => this.submitEditContactData()
      });
    } else {
      this.submitEditContactData();
    }
  }

  /**
   * 提交编辑联系人数据
   */
  submitEditContactData() {
    for (const i in this.editContactForm.controls) {
      this.editContactForm.controls[i].markAsDirty();
      this.editContactForm.controls[i].updateValueAndValidity();
    }
    if (this.editContactForm.status == null || this.editContactForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有必填项',
      });
      return;
    }
    this.oilCardService.setContact(this.editContactForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '设置成功',
        });
        this.closeEditContactModal();
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }

  /**
   * 弹出禁用对话框
   */
  showDisabledConfirm(cardNo: string): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否禁用油卡',
      nzOkText: '是',
      nzCancelText: '否',
      nzOkType: 'danger',
      nzOnOk: () => this.disabledData(cardNo)
    });
  }

  /**
   * 禁用数据
   */
  disabledData(cardNo: string) {
    this.oilCardService.disabled({ cardNo: cardNo}, data => {
      if (data['return_code'] === '000000') {
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
    });
  }

  /**
   * 弹出启用对话框
   */
  showEnableConfirm(cardNo: string): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否启用油卡',
      nzOkText: '是',
      nzCancelText: '否',
      nzOkType: 'danger',
      nzOnOk: () => this.enableData(cardNo)
    });
  }

  /**
   * 启用数据
   */
  enableData(cardNo: string) {
    this.oilCardService.enable({ cardNo: cardNo}, data => {
      if (data['return_code'] === '000000') {
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
    });
  }

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

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

  /**
   * 提交充值
   */
  submitRecharge() {
    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: '请填写所有必填项',
      });
      return;
    }
    this.rechargeBtnLoading = true;
    this.rechargeForm.value['cardNo'] = this.rechargeForm.controls['cardNo']['value'];
    this.oilCardService.recharge(this.rechargeForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '充值成功',
        });
        this.closeRechargeModal();
        this.getAccount();
        this.requestData(this.whereObject['pageNum']);

      } else if (data['return_code'] === '102136') {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
        this.router.navigateByUrl('admin/company-amount/pay-pwd-config');
        this.closeRechargeModal();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
      this.rechargeBtnLoading = false;
    });
  }


  /**
   * 展示充值模态框
   */
  showRecycleAmountModal(cardData: object) {
    this.recycleAmountForm.patchValue(cardData);
    this.recycleAmountModal = true;
  }

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

  /**
   * 提交回收余额
   */
  submitRecycleAmount() {
    for (const i in this.recycleAmountForm.controls) {
      this.recycleAmountForm.controls[i].markAsDirty();
      this.recycleAmountForm.controls[i].updateValueAndValidity();
    }
    if (this.recycleAmountForm.status == null || this.recycleAmountForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有必填项',
      });
      return;
    }
    this.recycleAmountBtnLoading = true;
    this.recycleAmountForm.value['cardNo'] = this.recycleAmountForm.controls['cardNo']['value'];
    this.oilCardService.recycleAmount(this.recycleAmountForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '回收成功',
        });
        this.closeRecycleAmountModal();
        this.getAccount();
        this.requestData(this.whereObject['pageNum']);

      } else if (data['return_code'] === '102136') {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
        this.router.navigateByUrl('admin/company-amount/pay-pwd-config');
        this.closeRecycleAmountModal();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
      this.recycleAmountBtnLoading = false;
    });
  }

  /**
   * 导出油卡
   */
  excelCard() {
    this.oilCardService.exportCard(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        window.location.href = this.FILE_URL + 'temporary/' + data['return_data'];
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
    });
  }
}
