import { message } from 'antd';
import { openNotification } from 'client/Elements/Notification';
import CoreService from 'core/services/CoreService';
import { ICalculationStore } from 'core/types/Calculation/Store';
import { ValuesNames } from 'core/types/Calculation/Store/values';
import { ElementStatus } from 'types/elements';
import checkValidation from './checkValidation';
import prepareCalculationData from './prepareData';
import results from './results';
import validate from './validate';

const BUTTONS_TIMEOUT = 500;

export const RESULT_VALUES: ValuesNames[] = [
  'resultTotalGraphwithNDS',
  'resultPlPrice',
  'resultPriceUpPr',
  'resultIRRGraphPerc',
  'resultIRRNominalPerc',
  'resultInsKasko',
  'resultInsOsago',
  'resultDopProdSum',
  'resultFirstPayment',
  'resultLastPayment',
  'resultTerm',
  'resultAB_FL',
  'resultAB_UL',
  'resultBonusMPL',
  'resultDopMPLLeasing',
  'resultBonusDopProd',
  'resultParticipationAmount',
];

export default function (this: ICalculationStore) {
  const cleanResults = () => {
    this.setValues(
      RESULT_VALUES.reduce((acc, v) => {
        acc[v] = '';
        return acc;
      }, {}),
    );
  };

  const blockButtons = () => {
    this.setStatus('btnCreateKP', ElementStatus.Loading);
    this.setStatus('btnCalculate', ElementStatus.Loading);
  };

  const unlockButtons = () => {
    setTimeout(() => {
      this.setStatus('btnCreateKP', ElementStatus.Default);
    }, BUTTONS_TIMEOUT);
    setTimeout(() => {
      this.setStatus('btnCalculate', ElementStatus.Default);
    }, BUTTONS_TIMEOUT);
  };

  validate.call(this);
  const { invalidElements, invalidTables } = checkValidation.call(this);
  if (invalidElements.length > 0 || invalidTables.length > 0) {
    if (invalidElements.length > 0)
      openNotification({
        type: 'error',
        message: 'Ошибка во время расчета графика',
        description:
          'Некорректно заполнены поля: ' + invalidElements.join(', '),
      });

    if (invalidTables.length > 0)
      openNotification({
        type: 'error',
        message: 'Ошибка во время расчета графика',
        description:
          'Некорректно заполнены таблицы: ' + invalidTables.join(', '),
      });
    return;
  }

  blockButtons();

  var preparedData = prepareCalculationData.call(this);
  console.log('preparedData', preparedData);

  const getAdditionalData = () => {
    return {
      //@ts-ignore
      minCashflowMSFONominal: this.irr().min,
      //@ts-ignore
      maxCashflowMSFONominal: this.irr().max,
    };
  };

  var additionalData = getAdditionalData.call(this);
  console.log('additionalData', additionalData);

  this.cleanTable('tableResults');
  cleanResults();

  return CoreService.calculate(Object.assign(preparedData, { additionalData }))
    .then(res => {
      console.log('calculation res', res);

      message.success({
        content: 'Расчет завершен успешно!',
      });

      results.showResultsTable.call(this, preparedData, res);
      results.showResults.call(this, preparedData, res);
      results.setResValues.call(this, res);

      return Object.assign(preparedData, res);
    })
    .catch(err => {
      openNotification({
        type: 'error',
        message: 'Ошибка во время расчета!',
        description:
          err.response &&
          err.response.data &&
          (err.response.data.errors
            ? err.response.data.errors.join(', ')
            : err.response.data),
      });

      throw err;
    })
    .finally(() => {
      unlockButtons();
    });
}
