import valuesConstants from 'core/constants/values';
import {
  PaymentRow,
  PreparedValues,
} from 'core/services/CoreService/types/Calculation/prepared';
import { PreparedData } from 'core/services/CoreService/types/Calculation/request';
import { currentDate } from 'core/tools/date';
import { NIL } from 'core/tools/uuid';
import { ICalculationStore } from 'core/types/Calculation/Store';
import { convertPrice } from '../../lib/tools';

export default function (this: ICalculationStore): PreparedData {
  const { values, options, tables } = this;

  const preparedPaymentsRows: PaymentRow[] = Array.from(
    { length: values.leasingPeriod },
    () => ({
      numberPayment: 0,
      percentPayment: 0,
      sumPayment: 0,
      gpsBasePayment: 0,
      gpsCostPayment: 0,
      tlmBasePayment: 0,
      tlmCostPayment: 0,
    }),
  );

  const tracker = options.selectTracker?.find(
    x => x.evo_addproduct_typeid === values.tracker,
  );
  const telematic = options.selectTelematic?.find(
    x => x.evo_addproduct_typeid === values.telematic,
  );

  for (let i = 0; i < values.leasingPeriod; i++) {
    preparedPaymentsRows[i].numberPayment = i + 1;
    preparedPaymentsRows[i].percentPayment =
      i === 0 ? 0 : tables.tablePayments.rows[i].paymentRelation?.value;
    preparedPaymentsRows[i].sumPayment = 0;

    if (tracker) {
      if (tracker.evo_planpayments && tracker.evo_planpayments.length > 0) {
        const evo_planpayment = tracker.evo_planpayments.find(
          x => x.evo_name === (i + 1).toString(),
        );
        if (evo_planpayment) {
          preparedPaymentsRows[i].gpsBasePayment =
            (evo_planpayment.evo_cost_price_telematics_withoutnds || 0) +
            (evo_planpayment.evo_cost_equipment_withoutnds || 0);

          preparedPaymentsRows[i].gpsCostPayment =
            evo_planpayment.evo_cost_telematics_withoutnds || 0;
        }
      }
    }

    if (telematic) {
      if (telematic.evo_planpayments && telematic.evo_planpayments.length > 0) {
        const evo_planpayment = telematic.evo_planpayments.find(
          x => x.evo_name === (i + 1).toString(),
        );
        if (evo_planpayment) {
          preparedPaymentsRows[i].tlmBasePayment =
            (evo_planpayment.evo_cost_price_telematics_withoutnds || 0) +
            (evo_planpayment.evo_cost_equipment_withoutnds || 0);

          preparedPaymentsRows[i].tlmCostPayment =
            evo_planpayment.evo_cost_telematics_withoutnds || 0;
        }
      }
    }
  }

  const preparedValues: PreparedValues = {
    brandId: NIL,
    configurationId: NIL,
    firstPaymentAbs: 0,
    firstPaymentNdsAbs: 0,
    firstPaymentWithNdsAbs: 0,
    modelId: NIL,
    paymentDateNew: currentDate,
    plTypeId: NIL,
    tlmCostPaymentSum: preparedPaymentsRows
      .map(x => x.tlmCostPayment || 0)
      .reduce((a, b) => a + b, 0),
    gpsCostPaymentSum: preparedPaymentsRows
      .map(x => x.gpsCostPayment || 0)
      .reduce((a, b) => a + b, 0),
  };

  preparedValues.calcDate = currentDate;
  preparedValues.calcType = values.calcType;
  preparedValues.irrExpected = (values.IRR_Perc as number) / 100;
  preparedValues.npvniExpected = 0;
  preparedValues.totalExpected = values.totalPayments + values.subsidySum;
  preparedValues.nmper = values.leasingPeriod;
  preparedValues.leasing0K =
    values.product === 'LEASING0'
      ? ((preparedValues.nmper as number) - 2) *
        (0.0234 / ((1 - 1 / 1.0234) ^ ((preparedValues.nmper as number) - 2)))
      : 1;
  preparedValues.loanRate = parseFloat(values.creditRate) / 100;
  preparedValues.loanRatePeriod =
    this.getOption('selectRate')?.evo_credit_period;
  preparedValues.balanceHolder = values.balanceHolder;
  preparedValues.dogDate = preparedValues.calcDate;
  preparedValues.paymentDateNew = undefined;
  preparedValues.deliveryTime = values.deliveryTime;
  preparedValues.firstPaymentAbs = undefined;
  preparedValues.firstPaymentNdsAbs = undefined;
  preparedValues.firstPaymentWithNdsAbs = undefined;
  preparedValues.lastPaymentFix = values.lastPaymentRule !== 100_000_002;
  preparedValues.lastPayment = (values.lastPaymentPerc as number) / 100;
  preparedValues.lastPaymentSum =
    (values.lastPaymentRub as number) / (1 + valuesConstants.VAT);
  preparedValues.subsidySum =
    parseInt(values.subsidySum) / (1 + valuesConstants.VAT);
  preparedValues.subsidyPaymentNumber =
    this.getOption('selectSubsidy')?.evo_get_subsidy_payment;
  preparedValues.fuelCardSum =
    this.getOption('selectFuelCard')?.evo_graph_price_withoutnds;
  preparedValues.scheduleOfPayments = values.graphType;
  preparedValues.comissionRub =
    (values.comissionRub as number) / (1 + valuesConstants.VAT);
  preparedValues.plTypeId = values.leaseObjectType;
  preparedValues.brandId = values.brand;
  preparedValues.modelId = values.model;
  preparedValues.configurationId = values.configuration;
  preparedValues.plYear = values.leaseObjectYear;
  preparedValues.carCapacity = values.leaseObjectMotorPower;
  preparedValues.motorVolume = values.engineVolume;
  preparedValues.plEngineType = values.engineType;
  preparedValues.carCarrying = values.maxMass;
  preparedValues.bonus = (values.saleBonus as number) / 100;
  preparedValues.bonusCoefficient = values.bonusCoefficient;
  preparedValues.profitExpected =
    this.getOption('selectTarif')?.evo_margin_min || 0;

  preparedValues.transTax = values.vehicleTaxInYear;
  preparedValues.transIncludeGr = values.vehicleTaxInYear > 0;
  preparedValues.transportTaxGrYear = values.vehicleTaxInYear;
  preparedValues.transportTaxGr = values.vehicleTaxInLeasingPeriod;

  const insuranceKaskoRow = tables.tableInsurance.rows.find(
    x => x?.key === 'kasko',
  );

  const insuranceNSRow = tables.tableInsurance.rows.find(x => x?.key === 'ns');

  const insuranceDGORow = tables.tableInsurance.rows.find(
    x => x?.key === 'dgo',
  );

  const insuranceOSAGORow = tables.tableInsurance.rows.find(
    x => x?.key === 'osago',
  );

  const insuranceFinGAPRow = tables.tableInsurance.rows.find(
    x => x?.key === 'finGAP',
  );

  if (insuranceKaskoRow?.insured?.value === 100000001) {
    preparedValues.insuranceKasko =
      insuranceKaskoRow?.insCost?.value +
      insuranceDGORow?.insCost?.value +
      insuranceNSRow?.insCost?.value;
  } else {
    preparedValues.insuranceKasko = 0;
  }

  preparedValues.nmperInsurance =
    insuranceKaskoRow?.insTerm?.value === 100000001 ? values.leasingPeriod : 12;

  preparedValues.insuranceOsago =
    insuranceOSAGORow?.insured?.value === 100000001
      ? insuranceOSAGORow?.insCost?.value
      : 0;

  preparedValues.insuranceFinGAP =
    insuranceFinGAPRow?.insured?.value === 100000001
      ? insuranceFinGAPRow.insCost?.value
      : 0;

  preparedValues.nmperFinGAP =
    insuranceFinGAPRow?.insTerm?.value === 100000001
      ? values.leasingPeriod
      : 12;

  //@ts-ignore
  const importProgramSum: number = this.importProgramSum();
  //@ts-ignore
  const plPriceRub: number = this.plPriceRub();
  //@ts-ignore
  const discountRub: number = this.discountRub();

  preparedValues.insuranceEvoKasko = 0;
  const selectLeasingWithoutKasko = this.getOption('selectLeasingWithoutKasko');

  if (selectLeasingWithoutKasko?.evo_evokasko_calc_type === 100_000_001) {
    preparedValues.insuranceEvoKasko =
      (selectLeasingWithoutKasko?.evo_cost_service_provider_withoutnds || 0) *
      (plPriceRub -
        discountRub -
        importProgramSum +
        values.addEquipmentPrice -
        values.firstPaymentRub);
  } else {
    preparedValues.insuranceEvoKasko =
      (selectLeasingWithoutKasko?.evo_cost_service_provider_withoutnds || 0) *
      (plPriceRub - discountRub - importProgramSum + values.addEquipmentPrice);
  }

  preparedValues.insuranceBonusLoss = 0;

  if (selectLeasingWithoutKasko?.evo_evokasko_calc_type === 100_000_001) {
    preparedValues.insuranceBonusLoss =
      ((selectLeasingWithoutKasko?.evo_loss_kv || 0) *
        (plPriceRub -
          discountRub -
          importProgramSum +
          values.addEquipmentPrice -
          values.firstPaymentRub)) /
      100;
  } else {
    preparedValues.insuranceBonusLoss =
      ((selectLeasingWithoutKasko?.evo_loss_kv || 0) *
        (plPriceRub -
          discountRub -
          importProgramSum +
          values.addEquipmentPrice)) /
      100;
  }

  preparedValues.insuranceKaskoNmper =
    (preparedValues.nmperInsurance || 0) >= 16
      ? ((preparedValues.insuranceKasko || 0) *
          (preparedValues.nmperInsurance || 0)) /
        12
      : preparedValues.insuranceKasko;

  preparedValues.insuranceContract =
    (preparedValues.insuranceKaskoNmper || 0) +
    (preparedValues.insuranceOsago || 0);

  preparedValues.repayment = 0.25;

  //plPrice && discount
  const supplierCurrency = options.selectSupplierCurrency?.find(
    x => x.transactioncurrencyid === values.supplierCurrency,
  );

  const evo_currencychanges = this.getStaticData('evo_currencychange');
  const evo_currencychange = evo_currencychanges.find(
    x => x.evo_ref_transactioncurrency === values.supplierCurrency,
  );

  preparedValues.plPrice = convertPrice(
    supplierCurrency?.isocurrencycode,
    values.leaseObjectPriceWthtVAT +
      values.addEquipmentPrice / (1 + valuesConstants.VAT),
    evo_currencychange?.evo_currencychange || 1,
  );

  preparedValues.plPriceWithVAT = convertPrice(
    supplierCurrency?.isocurrencycode,
    values.leaseObjectPrice + values.addEquipmentPrice,
    evo_currencychange?.evo_currencychange || 1,
  );

  preparedValues.plPriceVAT = convertPrice(
    supplierCurrency?.isocurrencycode,
    values.VATInLeaseObjectPrice +
      (values.addEquipmentPrice -
        values.addEquipmentPrice / (1 + valuesConstants.VAT)),
    evo_currencychange?.evo_currencychange || 1,
  );

  preparedValues.importProgramSum =
    importProgramSum / (1 + valuesConstants.VAT);

  preparedValues.discount =
    convertPrice(
      supplierCurrency?.isocurrencycode,
      values.supplierDiscountRub + importProgramSum,
      evo_currencychange?.evo_currencychange || 1,
    ) /
    (1 + valuesConstants.VAT);
  //

  const firstPaymentPercWthtVAT =
    values.firstPaymentRub /
    (1 + valuesConstants.VAT) /
    ((preparedValues.plPrice || 0) - (preparedValues.importProgramSum || 0));
  if (firstPaymentPercWthtVAT * 100 < 30) {
    const evo_coefficient_season = this.getStaticData('evo_coefficient').filter(
      x =>
        x.evo_corfficient_type === 100000000 &&
        x.evo_min_period &&
        x.evo_min_period <= values.leasingPeriod &&
        x.evo_max_period &&
        x.evo_max_period >= values.leasingPeriod,
    );
    switch (values.graphType) {
      case 100000003:
        if (values.highSeasonStart !== 100_000_000) {
          if (evo_coefficient_season && evo_coefficient_season.length > 0) {
            const evo_coefficient = evo_coefficient_season.find(
              x =>
                x.evo_season_type === values.seasonType &&
                x.evo_graph_type === 100000003,
            );
            preparedValues.firstPayment =
              (firstPaymentPercWthtVAT * 100 +
                (evo_coefficient?.evo_correction_coefficient || 0)) /
              100;
          }
        } else {
          preparedValues.firstPayment = firstPaymentPercWthtVAT;
        }

        break;

      case 100000004:
        if (evo_coefficient_season && evo_coefficient_season.length > 0) {
          const evo_coefficient = evo_coefficient_season.find(
            x => x.evo_graph_type === 100000004,
          );
          if (evo_coefficient)
            preparedValues.firstPayment =
              (firstPaymentPercWthtVAT * 100 +
                (evo_coefficient?.evo_correction_coefficient || 0)) /
              100;
        }
        break;

      //TODO: beautify
      default:
        preparedValues.firstPayment = firstPaymentPercWthtVAT;
        break;
    }
  } else {
    preparedValues.firstPayment = firstPaymentPercWthtVAT;
  }

  preparedValues.acceptSum =
    (preparedValues.plPrice || 0) - (preparedValues.discount || 0);

  preparedValues.firstPaymentSum =
    (preparedValues.firstPayment || 0) *
    ((preparedValues.plPrice || 0) - (preparedValues.importProgramSum || 0));

  /**
   * @description
   * если в selectIndAgentRewardCondition значение evo_reward_condition.Расчет вознаграждения от (evo_calc_reward_rules) = 100 000 001 (от суммы),
    то AgentsSum = Размер АВ агента ФЛ (tbxIndAgentRewardSumm) * ЕСН [ESN]
    иначе
    если в selectIndAgentRewardCondition указана запись, у которой evo_reward_condition.evo_agency_agreementid. Стоимость ПЛ (evo_leasingobject_price) = 100 000 001 (с НДС), 
    то  AgentsSum =  (Размер АВ агента ФЛ (tbxIndAgentRewardSumm) /100 * (PreparedValues.PlPriceWithVAT - Discount*(1+VAT)) * ЕСН [ESN],
    иначе AgentsSum = (значение поля Размер АВ агента ФЛ (tbxIndAgentRewardSumm) /100 * Стоимость ПЛ с учетом скидки [AcceptSum] ) * ЕСН [ESN]
   */
  const selectIndAgentRewardConditionOption = this.getOption(
    'selectIndAgentRewardCondition',
  );
  if (
    selectIndAgentRewardConditionOption?.evo_calc_reward_rules === 100_000_001
  ) {
    preparedValues.agentsSum = values.indAgentRewardSumm * valuesConstants.ESN;
  } else if (
    selectIndAgentRewardConditionOption?.evo_agency_agreementidData
      ?.evo_leasingobject_price === 100_000_001
  ) {
    preparedValues.agentsSum =
      (values.indAgentRewardSumm / 100) *
      ((preparedValues.plPriceWithVAT || 0) -
        (preparedValues.discount || 0) * (1 + valuesConstants.VAT)) *
      valuesConstants.ESN;
  } else {
    preparedValues.agentsSum =
      (values.indAgentRewardSumm / 100) *
      preparedValues.acceptSum *
      valuesConstants.ESN;
  }

  /**
  * @description
  * если в selectCalcDoubleAgentRewardCondition значение evo_reward_condition.Расчет вознаграждения от (evo_calc_reward_rules) = 100 000 001 (от суммы),
    то DoubleAgentsSum= Размер АВ двойного агента (tbxCalcDoubleAgentRewardSumm)  * ЕСН [ESN]
    иначе
    если в selectCalcDoubleAgentRewardCondition указана запись, у которой evo_reward_condition.evo_agency_agreementid. Стоимость ПЛ (evo_leasingobject_price) = 100 000 001 (с НДС), 
    то  DoubleAgentsSum=  (Размер АВ двойного агента (tbxCalcDoubleAgentRewardSumm) /100 * (PreparedValues.PlPriceWithVAT - Discount*(1+VAT)) * ЕСН [ESN],
    иначе DoubleAgentsSum= (значение поля Размер АВ двойного агента (tbxCalcDoubleAgentRewardSumm) /100 * Стоимость ПЛ с учетом скидки [AcceptSum] ) * ЕСН [ESN]
  */
  const selectCalcDoubleAgentRewardCondition = this.getOption(
    'selectCalcDoubleAgentRewardCondition',
  );
  if (
    selectCalcDoubleAgentRewardCondition?.evo_calc_reward_rules === 100_000_001
  ) {
    preparedValues.doubleAgentsSum =
      values.calcDoubleAgentRewardSumm * valuesConstants.ESN;
  } else if (
    selectCalcDoubleAgentRewardCondition?.evo_agency_agreementidData
      ?.evo_leasingobject_price === 100_000_001
  ) {
    preparedValues.doubleAgentsSum =
      (values.calcDoubleAgentRewardSumm / 100) *
      ((preparedValues.plPriceWithVAT || 0) -
        (preparedValues.discount || 0) * (1 + valuesConstants.VAT)) *
      valuesConstants.ESN;
  } else {
    preparedValues.doubleAgentsSum =
      (values.calcDoubleAgentRewardSumm / 100) *
      preparedValues.acceptSum *
      valuesConstants.ESN;
  }

  /**
   * @description
   * если в selectDealerRewardCondition значение evo_reward_condition.Расчет вознаграждения от (evo_calc_reward_rules) = 100 000 001 (от суммы),
    то DeliverySum= Размер АВ ЮЛ поставщика (tbxDealerRewardSumm) / (1+VAT)
    иначе
    если в selectDealerRewardCondition  указана запись, у которой evo_reward_condition.evo_agency_agreementid. Стоимость ПЛ (evo_leasingobject_price) = 100 000 001 (с НДС), 
    то  DeliverySum=  Размер АВ ЮЛ поставщика (tbxDealerRewardSumm) /100 * (PreparedValues.PlPriceWithVAT - Discount*(1+VAT)),
    иначе DeliverySum=значение поля Размер АВ ЮЛ поставщика (tbxDealerRewardSumm) /100 * Стоимость ПЛ с учетом скидки [AcceptSum]
   */
  const selectDealerRewardCondition = this.getOption(
    'selectDealerRewardCondition',
  );
  if (selectDealerRewardCondition?.evo_calc_reward_rules === 100_000_001) {
    preparedValues.deliverySum =
      values.dealerRewardSumm / (1 + valuesConstants.VAT);
  } else if (
    selectDealerRewardCondition?.evo_agency_agreementidData
      ?.evo_leasingobject_price === 100_000_001
  ) {
    preparedValues.deliverySum =
      (values.dealerRewardSumm / 100) *
      ((preparedValues.plPriceWithVAT || 0) -
        (preparedValues.discount || 0) * (1 + valuesConstants.VAT));
  } else {
    preparedValues.deliverySum =
      (values.dealerRewardSumm / 100) * preparedValues.acceptSum;
  }

  /**
 * @description
 * если в selectCalcBrokerRewardCondition  значение evo_reward_condition.Расчет вознаграждения от (evo_calc_reward_rules) = 100 000 001 (от суммы),
  то BrokerSum= Размер АВ брокера (tbxCalcBrokerRewardSum) / (1+VAT)
  иначе
  если в selectCalcBrokerRewardCondition  указана запись, у которой evo_reward_condition.evo_agency_agreementid. Стоимость ПЛ (evo_leasingobject_price) = 100 000 001 (с НДС), 
  то  BrokerSum=  Размер АВ брокера (tbxCalcBrokerRewardSum) /100 * (PreparedValues.PlPriceWithVAT - Discount*(1+VAT)) ,
  иначе BrokerSum= значение поля Размер АВ брокера (tbxCalcBrokerRewardSum)/100 * Стоимость ПЛ с учетом скидки [AcceptSum]
 */
  const selectCalcBrokerRewardCondition = this.getOption(
    'selectCalcBrokerRewardCondition',
  );
  if (selectCalcBrokerRewardCondition?.evo_calc_reward_rules === 100_000_001) {
    preparedValues.brokerSum =
      values.calcBrokerRewardSum / (1 + valuesConstants.VAT);
  } else if (
    selectCalcBrokerRewardCondition?.evo_agency_agreementidData
      ?.evo_leasingobject_price === 100_000_001
  ) {
    preparedValues.brokerSum =
      (values.calcBrokerRewardSum / 100) *
      ((preparedValues.plPriceWithVAT || 0) -
        (preparedValues.discount || 0) * (1 + valuesConstants.VAT));
  } else {
    preparedValues.brokerSum =
      (values.calcBrokerRewardSum / 100) * preparedValues.acceptSum;
  }

  /**
   * @description
   * если в selectDealerBrokerRewardCondition значение evo_reward_condition.Расчет вознаграждения от (evo_calc_reward_rules) = 100 000 001 (от суммы),
    то BrokerOfDeliverySum= Размер АВ брокера поставщика (tbxDealerBrokerRewardSumm) / (1+VAT)
    иначе
    если в selectDealerBrokerRewardCondition указана запись, у которой evo_reward_condition.evo_agency_agreementid. Стоимость ПЛ (evo_leasingobject_price) = 100 000 001 (с НДС), 
    то  BrokerOfDeliverySum=  Размер АВ брокера поставщика (tbxDealerBrokerRewardSumm) /100 * (PreparedValues.PlPriceWithVAT - Discount*(1+VAT)),
    иначе BrokerOfDeliverySum= значение поля Размер АВ брокера поставщика (tbxDealerBrokerRewardSumm)/100 * Стоимость ПЛ с учетом скидки [AcceptSum]
   */
  const selectDealerBrokerRewardCondition = this.getOption(
    'selectDealerBrokerRewardCondition',
  );
  if (
    selectDealerBrokerRewardCondition?.evo_calc_reward_rules === 100_000_001
  ) {
    preparedValues.brokerOfDeliverySum =
      values.dealerBrokerRewardSumm / (1 + valuesConstants.VAT);
  } else if (
    selectDealerBrokerRewardCondition?.evo_agency_agreementidData
      ?.evo_leasingobject_price === 100_000_001
  ) {
    preparedValues.brokerOfDeliverySum =
      (values.dealerBrokerRewardSumm / 100) *
      ((preparedValues.plPriceWithVAT || 0) -
        (preparedValues.discount || 0) * (1 + valuesConstants.VAT));
  } else {
    preparedValues.brokerOfDeliverySum =
      (values.dealerBrokerRewardSumm / 100) * preparedValues.acceptSum;
  }

  /**
   * @description
   * если в selectFinDepartmentRewardCondtion значение evo_reward_condition.Расчет вознаграждения от (evo_calc_reward_rules) = 100 000 001 (от суммы),
    то FinancialDeptOfDeliverySum= Размер АВ финотдела (tbxFinDepartmentRewardSumm) / (1+VAT)
    иначе
    если в selectFinDepartmentRewardCondtion  указана запись, у которой evo_reward_condition.evo_agency_agreementid. Стоимость ПЛ (evo_leasingobject_price) = 100 000 001 (с НДС), 
    то  FinancialDeptOfDeliverySum=  Размер АВ финотдела (tbxFinDepartmentRewardSumm) /100 * (PreparedValues.PlPriceWithVAT - Discount*(1+VAT)),
    иначе FinancialDeptOfDeliverySum= значение поля Размер АВ финотдела (tbxFinDepartmentRewardSumm)/100 * Стоимость ПЛ с учетом скидки [PreparedValue.AcceptSum]
   */
  const selectFinDepartmentRewardCondtion = this.getOption(
    'selectFinDepartmentRewardCondtion',
  );
  if (
    selectFinDepartmentRewardCondtion?.evo_calc_reward_rules === 100_000_001
  ) {
    preparedValues.financialDeptOfDeliverySum =
      values.finDepartmentRewardSumm / (1 + valuesConstants.VAT);
  } else if (
    selectFinDepartmentRewardCondtion?.evo_agency_agreementidData
      ?.evo_leasingobject_price === 100_000_001
  ) {
    preparedValues.financialDeptOfDeliverySum =
      (values.finDepartmentRewardSumm / 100) *
      ((preparedValues.plPriceWithVAT || 0) -
        (preparedValues.discount || 0) * (1 + valuesConstants.VAT));
  } else {
    preparedValues.financialDeptOfDeliverySum =
      (values.finDepartmentRewardSumm / 100) * preparedValues.acceptSum;
  }

  if (values.importerRewardRub > 0) {
    preparedValues.importerSum = values.importerRewardRub;
  } else {
    preparedValues.importerSum =
      (values.importerRewardPerc / 100) * preparedValues.acceptSum;
  }

  const evo_coefficient_bonuses = this.getStaticData('evo_coefficient').filter(
    x => x.evo_corfficient_type === 100000002 && x.evo_sot_coefficient_typeid,
  );
  const systemuser = this.getStaticData('systemuser')[0];

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser &&
    !Array.isArray(systemuser)
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'EXTRA_BONUS');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_job_titleid === systemuser.evo_job_titleid &&
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid &&
        x.evo_baseproducts?.map(x => x.evo_id).includes(values.product),
    );

    if (evo_coefficient) {
      preparedValues.extraBonus = evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser &&
    !Array.isArray(systemuser)
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'BONUS_FIX');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_job_titleid === systemuser.evo_job_titleid &&
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid &&
        x.evo_baseproducts?.map(x => x.evo_id).includes(values.product),
    );

    if (evo_coefficient) {
      preparedValues.bonusFix = evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'DIRECTOR_BONUS');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid &&
        x.evo_baseproducts?.map(x => x.evo_id).includes(values.product),
    );

    if (evo_coefficient) {
      preparedValues.directorBonus = evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'DIRECTOR_BONUS_FIX');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid &&
        x.evo_baseproducts?.map(x => x.evo_id).includes(values.product),
    );

    if (evo_coefficient) {
      preparedValues.directorBonusFix =
        evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'DIRECTOR_EXTRA_BONUS');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid &&
        x.evo_baseproducts?.map(x => x.evo_id).includes(values.product),
    );

    if (evo_coefficient) {
      preparedValues.directorExtraBonus =
        evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'REGIONAL_DIRECTOR_BONUS_FINGAP');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
        evo_sot_coefficient_type?.evo_sot_coefficient_typeid,
    );

    if (evo_coefficient) {
      preparedValues.regionalDirectorBonusFinGAP =
        (evo_coefficient.evo_sot_coefficient || 0) *
        (insuranceFinGAPRow?.insCost?.value || 0);
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'REGIONAL_DIRECTOR_BONUS');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid &&
        x.evo_baseproducts?.map(x => x.evo_id).includes(values.product),
    );

    if (evo_coefficient) {
      preparedValues.regionalDirectorBonus =
        evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'REGIONAL_DIRECTOR_BONUS_FIX');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid &&
        x.evo_baseproducts?.map(x => x.evo_id).includes(values.product),
    );

    if (evo_coefficient) {
      preparedValues.regionalDirectorBonusFix =
        evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'REGIONAL_DIRECTOR_EXTRA_BONUS');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid &&
        x.evo_baseproducts?.map(x => x.evo_id).includes(values.product),
    );

    if (evo_coefficient) {
      preparedValues.regionalDirectorExtraBonus =
        evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'MARKET_RATE');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid &&
        x.evo_businessunits?.find(
          x => x.evo_sale_businessunitid === systemuser.businessunitid,
        ),
    );

    if (evo_coefficient) {
      preparedValues.marketRate = evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'DISTRICT_RATE');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid &&
        x.evo_businessunits?.find(
          x => x.evo_sale_businessunitid === systemuser.businessunitid,
        ),
    );

    if (evo_coefficient) {
      preparedValues.districtRate = evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'SALARY_RATE');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
        evo_sot_coefficient_type?.evo_sot_coefficient_typeid,
    );

    if (evo_coefficient) {
      preparedValues.salaryRate = evo_coefficient.evo_sot_coefficient || 0;
    }
  }

  const technicalCard = options.selectTechnicalCard?.find(
    x => x.evo_addproduct_typeid === values.technicalCard,
  );

  if (technicalCard) {
    preparedValues.rats = technicalCard.evo_graph_price_withoutnds || 0;
    preparedValues.baseRatCost =
      technicalCard.evo_cost_service_provider_withoutnds || 0;
    preparedValues.retroBonus = technicalCard.evo_retro_bonus_withoutnds || 0;
  }

  const selectedRegistration = options.selectRegistration?.find(
    x => x.evo_addproduct_typeid === values.registration,
  );

  if (selectedRegistration) {
    preparedValues.registration =
      selectedRegistration.evo_graph_price_withoutnds || 0;
    preparedValues.baseRegistration =
      selectedRegistration.evo_cost_service_provider_withoutnds || 0;
  }

  if (tracker) {
    preparedValues.trackerCost = tracker.evo_graph_price_withoutnds || 0;
  }

  if (telematic) {
    preparedValues.tLMCost = telematic.evo_graph_price_withoutnds || 0;
  }

  //

  const nsibBaseValue =
    ((preparedValues.plPrice || 0) -
      (preparedValues.importProgramSum || 0) +
      (preparedValues.insuranceContract +
        (preparedValues.rats || 0) +
        (preparedValues.registration || 0) +
        (preparedValues.trackerCost || 0) +
        (preparedValues.tLMCost || 0) +
        (preparedValues.transportTaxGr || 0) +
        (preparedValues.tlmCostPaymentSum || 0) +
        (preparedValues.gpsCostPaymentSum || 0)) *
        preparedValues.leasing0K -
      preparedValues.firstPaymentSum -
      (values.product === 'LEASING0' ? 0 : preparedValues.discount || 0)) *
    (1 + valuesConstants.VAT);

  if (nsibBaseValue > valuesConstants.NSIB_MAX) {
    preparedValues.nsibBase = valuesConstants.NSIB_MAX;
  } else {
    preparedValues.nsibBase = nsibBaseValue;
  }

  const selectedInsNSIB = options.selectInsNSIB?.find(
    x => x.evo_addproduct_typeid === values.insNSIB,
  );

  if (selectedInsNSIB) {
    preparedValues.nsibBrutto =
      ((((selectedInsNSIB.evo_graph_price || 0) / 100) *
        preparedValues.nsibBase) /
        12) *
      (preparedValues.nmper || 0);

    preparedValues.nsibNetto =
      ((((selectedInsNSIB.evo_cost_service_provider_withoutnds || 0) / 100) *
        preparedValues.nsibBase) /
        12) *
      (preparedValues.nmper || 0);
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser &&
    !Array.isArray(systemuser)
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'BONUS_RAT_PR');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_job_titleid === systemuser.evo_job_titleid &&
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid,
    );

    if (evo_coefficient) {
      preparedValues.ratBonus =
        (evo_coefficient.evo_sot_coefficient || 0) * (preparedValues.rats || 0);
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser &&
    !Array.isArray(systemuser)
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'BONUS_NSIB_PR');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_job_titleid === systemuser.evo_job_titleid &&
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid,
    );

    if (evo_coefficient) {
      preparedValues.nsibBonus =
        (evo_coefficient.evo_sot_coefficient || 0) *
        (preparedValues.nsibBrutto || 0);
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'DIRECTOR_BONUS_NSIB');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
        evo_sot_coefficient_type?.evo_sot_coefficient_typeid,
    );

    if (evo_coefficient) {
      preparedValues.directorBonusNsib =
        (evo_coefficient.evo_sot_coefficient || 0) *
        (preparedValues.nsibBrutto || 0);
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'REGIONAL_DIRECTOR_BONUS_NSIB');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
        evo_sot_coefficient_type?.evo_sot_coefficient_typeid,
    );

    if (evo_coefficient) {
      preparedValues.regionalDirectorBonusNsib =
        (evo_coefficient.evo_sot_coefficient || 0) *
        (preparedValues.nsibBrutto || 0);
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser &&
    !Array.isArray(systemuser)
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'BONUS_NS_PR');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_job_titleid === systemuser.evo_job_titleid &&
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid,
    );

    if (evo_coefficient && insuranceKaskoRow?.insured?.value === 100000001) {
      preparedValues.nsBonus =
        (evo_coefficient.evo_sot_coefficient || 0) *
        (insuranceNSRow?.insCost?.value || 0);
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser &&
    !Array.isArray(systemuser)
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'BONUS_FINGAP_PR');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_job_titleid === systemuser.evo_job_titleid &&
        x.evo_sot_coefficient_typeid ===
          evo_sot_coefficient_type?.evo_sot_coefficient_typeid,
    );

    if (evo_coefficient) {
      preparedValues.bonusFinGAP =
        (evo_coefficient.evo_sot_coefficient || 0) *
        (insuranceFinGAPRow?.insCost?.value || 0);
    }
  }

  if (
    evo_coefficient_bonuses &&
    evo_coefficient_bonuses.length > 0 &&
    systemuser
  ) {
    const evo_sot_coefficient_type = this.getStaticData(
      'evo_sot_coefficient_type',
    ).find(x => x.evo_id === 'DIRECTOR_BONUS_FINGAP');

    const evo_coefficient = evo_coefficient_bonuses.find(
      x =>
        x.evo_sot_coefficient_typeid ===
        evo_sot_coefficient_type?.evo_sot_coefficient_typeid,
    );

    if (evo_coefficient) {
      preparedValues.directorBonusFinGAP =
        (evo_coefficient.evo_sot_coefficient || 0) *
        (insuranceFinGAPRow?.insCost?.value || 0);
    }
  }

  preparedValues.insuranceBonus = 0;

  preparedValues.cityc = values.townRegistration || values.regionRegistration;

  const tarif = options.selectTarif?.find(x => x.evo_tarifid === values.tarif);
  if (tarif) {
    preparedValues.irr_MSFO_Plan = (tarif.evo_irr_plan || 0) / 100;
  }

  const evo_coefficient_risk = this.getStaticData('evo_coefficient')?.find(
    x =>
      x.evo_corfficient_type === 100000001 &&
      x.evo_min_period &&
      x.evo_min_period <= values.leasingPeriod &&
      x.evo_max_period &&
      x.evo_max_period >= values.leasingPeriod,
    // x.evo_client_riskid === values.clientRisk,
    // x.evo_leasingobject_types &&
    // x.evo_leasingobject_types.length > 0 &&
    // x.evo_leasingobject_types.filter(
    //   z => z.evo_leasingobject_typeid === values.leaseObjectType,
    // ).length > 0,
  );

  if (evo_coefficient_risk)
    preparedValues.npvniDelta = evo_coefficient_risk.evo_risk_delta || 0;

  const evo_leasingobject_type = options.selectLeaseObjectType?.find(
    x => x.evo_leasingobject_typeid === values.leaseObjectType,
  );

  if (evo_leasingobject_type && evo_leasingobject_type.evo_id) {
    let deprecation_rate = 1;

    if (
      (evo_leasingobject_type.evo_id === '1' &&
        (values.engineType === 100000000 || values.engineType === 100000004) &&
        values.engineVolume <= 3.5) ||
      (evo_leasingobject_type.evo_id === '2' &&
        (values.engineType === 100000000 ||
          values.engineType === 100000004 ||
          values.engineType === 100000001) &&
        values.maxMass <= 3500) ||
      (evo_leasingobject_type.evo_id !== '1' &&
        evo_leasingobject_type.evo_id !== '2')
    ) {
      if (evo_leasingobject_type.evo_expluatation_period1)
        preparedValues.nmperDeprecation =
          evo_leasingobject_type.evo_expluatation_period1;
      if (evo_leasingobject_type.evo_depreciation_rate1)
        deprecation_rate = evo_leasingobject_type.evo_depreciation_rate1;
    } else {
      if (evo_leasingobject_type.evo_expluatation_period2)
        preparedValues.nmperDeprecation =
          evo_leasingobject_type.evo_expluatation_period2;
      if (evo_leasingobject_type.evo_depreciation_rate2)
        deprecation_rate = evo_leasingobject_type.evo_depreciation_rate2;
    }
    if (
      preparedValues.nmperDeprecation === 85 ||
      preparedValues.nmperDeprecation === 61
    ) {
      preparedValues.deprecationTime = deprecation_rate * 3;
    } else {
      preparedValues.deprecationTime = deprecation_rate;
    }
  }

  return {
    preparedPayments: { rows: preparedPaymentsRows },
    preparedValues,
  };
}
