import { gql } from '@apollo/client';
import { message } from 'antd';
import { resetIns } from 'client/Containers/Calculation/Components/ELT/lib/resetIns';
import { numberElementsProps } from 'client/Containers/Calculation/Elements/props/common';
import {
  getTitle,
  getValueName
} from 'client/Containers/Calculation/Elements/tools';
import { ElementsNames } from 'client/Containers/Calculation/types/elements';
import { openNotification } from 'client/Elements/Notification';
import initialValues from 'client/stores/CalculationStore/config/initialValues';
import CrmService from 'core/services/CrmService';
import {
  mainOptionsForQuoteQuery,
  quoteQuery,
  secondaryOptionsForQuoteQuery,
  singleOptionsForQuoteQuery
} from 'core/services/CrmService/graphql/query/quote';
import { TOptionizedEntity } from 'core/services/CrmService/types/common';
import {
  CRMEntity,
  IAccount,
  IEvoGraph,
  IEvoRewardCondition,
  IEvoTown,
  IQuote
} from 'core/services/CrmService/types/entities';
import { currentISODate } from 'core/tools/date';
import { NIL } from 'core/tools/uuid';
import { IReactionEffect } from 'core/types/Calculation/Store/effect';
import { Process } from 'core/types/Calculation/Store/process';
import { get, invert, isEqual, isNil } from 'lodash';
import { ElementStatus } from 'types/elements';
import { getValuesFromKP } from './mapKpToValues';

const map_add_product_types_to_values = {
  technicalCard: 100000000,
  registration: 100000001,
  insNSIB: 100000002,
  tracker: 100000003,
  telematic: 100000004,
  fuelCard: 100000005,
  leasingWithoutKasko: 100000007,
};

const tablePaymentsStatuses = (graphType, seasonType, leasingPeriod) => {
  switch (graphType) {
    case 100000001: {
      if (seasonType === 100_000_007)
        return Array.from({ length: leasingPeriod - 3 }, (_, i) => i + 2);
      break;
    }
    case 100000003: {
      return Array.from({ length: 12 }, (_, i) => i + 1);
    }
    case 100000004: {
      return [1, 2, 3];
    }
    default: {
      return [];
    }
  }
};

function getLeasingPeriod(recalcWithRevision: boolean, quote: IQuote) {
  return recalcWithRevision && quote.evo_period && quote.evo_accept_period
    ? Math.min(quote.evo_period, quote.evo_accept_period)
    : quote.evo_period;
}

function getObjectRegistration(recalcWithRevision: boolean, quote: IQuote) {
  return recalcWithRevision && quote.evo_db_accept_registration
    ? quote.evo_db_accept_registration
    : quote.evo_object_registration;
}

async function getRewardSumm(
  reward_conditionid: string,
  quote: IQuote,
  quoteRewardSummName: string,
  quoteRewardTotalName: string,
) {
  if (reward_conditionid) {
    const { evo_reward_condition } = await CrmService.getCRMEntities<
      'evo_reward_condition',
      IEvoRewardCondition
    >({
      query: gql`
        query ($id: Uuid!) {
          evo_reward_condition(evo_reward_conditionid: $id) {
            evo_calc_reward_rules
          }
        }
      `,
      variables: {
        id: reward_conditionid,
      },
    });

    if (evo_reward_condition?.evo_calc_reward_rules === 100_000_001) {
      return quote[quoteRewardSummName];
    } else {
      return quote[quoteRewardTotalName];
    }
  } else {
    return quote[quoteRewardTotalName];
  }
}

const loadKpReaction: IReactionEffect = calculationStore => ({
  expression: () => {
    const { quote } = calculationStore.values;
    return quote;
  },
  effect: quoteId => {
    if (!quoteId) {
      return;
    }
    const {
      lead,
      opportunity,
      recalcWithRevision,
      calcType,
      INNForCalc,
      creditRate,
      rate,
      infuranceOPF,
      balanceHolder,
    } = calculationStore.values;

    calculationStore.setStatus('selectQuote', ElementStatus.Disabled);
    calculationStore.setStatus('btnCalculate', ElementStatus.Disabled);
    calculationStore.setStatus('btnCreateKP', ElementStatus.Disabled);

    const { calculationProcess } = calculationStore.stores;

    CrmService.getCRMEntities<'quote', IQuote>({
      query: quoteQuery,
      variables: {
        quoteId,
      },
    })
      .then(async ({ quote }) => {
        if (!quote) throw new Error('no quote');
        calculationProcess.addProcess(Process.LoadKp);

        const newValues = getValuesFromKP(quote);

        const mainOptions = await CrmService.getCRMOptions<
          ElementsNames,
          CRMEntity
        >({
          query: mainOptionsForQuoteQuery,
          variables: {
            statecode: 0,
            evo_brandid: quote.evo_brandid || NIL,
            evo_modelid: quote.evo_modelid || NIL,
            salonaccountid: quote.evo_supplier_accountid || NIL,
            currentDate: currentISODate,
            dealer_person_accountid: quote.evo_dealer_person_accountid || NIL,
            dealer_broker_accountid: quote.evo_dealer_broker_accountid || NIL,
            // ind_agent_accountid: quote.evo_agent_accountid || NIL,
            double_agent_accountid: quote.evo_double_agent_accountid || NIL,
            // broker_accountid: quote.evo_broker_accountid || NIL,
            // findepartment_accountid:
            //   quote.evo_fin_department_accountid || NIL,
            evo_gps_brandid: quote.evo_gps_brandid || NIL,
            evo_regionid: quote.evo_regionid || NIL,
            evo_legal_regionid: quote.evo_legal_regionid || NIL,
            evo_agency_agreementid_param: { has: true },
          },
        });

        // selectDealerBroker query
        let selectDealerBroker: TOptionizedEntity<IAccount>[] = [];
        const dealer_broker_accountid =
          mainOptions?.selectDealerPerson &&
          mainOptions?.selectDealerPerson?.length > 0 &&
          mainOptions.selectDealerPerson[0].evo_broker_accountid;
        if (dealer_broker_accountid) {
          const selectDealerBrokerRes = await CrmService.getCRMOptions<
            'selectDealerBroker',
            IAccount
          >({
            query: singleOptionsForQuoteQuery,
            variables: {
              dealer_broker_accountid,
            },
          });
          if (selectDealerBrokerRes?.selectDealerBroker)
            selectDealerBroker = selectDealerBrokerRes.selectDealerBroker;
        }
        // selectDealerBroker query

        calculationStore.applyOptions({
          ...mainOptions,
          selectDealerBroker: selectDealerBroker,
        });

        // agents
        //TODO: refactor

        let {
          indAgentRewardCondition,
          indAgentRewardSumm,
          calcBrokerRewardCondition,
          calcBrokerRewardSum,
          finDepartmentRewardCondtion,
          finDepartmentRewardSumm,
        } = calculationStore.values;

        const indAgent = calculationStore.getValue('indAgent');
        if (indAgent === quote.evo_agent_accountid) {
          indAgentRewardCondition = quote.evo_agent_reward_conditionid;

          indAgentRewardSumm = await getRewardSumm(
            //@ts-ignore
            quote.evo_agent_reward_conditionid,
            quote,
            'evo_agent_reward_summ',
            'evo_agent_reward_total',
          );
        }

        const calcBroker = calculationStore.getValue('calcBroker');
        if (calcBroker === quote.evo_broker_accountid) {
          calcBrokerRewardCondition = quote.evo_broker_reward_conditionid;

          calcBrokerRewardSum = await getRewardSumm(
            //@ts-ignore
            quote.evo_broker_reward_conditionid,
            quote,
            'evo_broker_reward_summ',
            'evo_broker_reward_total',
          );
        }

        const calcFinDepartment =
          calculationStore.getValue('calcFinDepartment');
        if (calcFinDepartment === quote.evo_fin_department_accountid) {
          finDepartmentRewardCondtion =
            quote.evo_fin_department_reward_conditionid;

          finDepartmentRewardSumm = await getRewardSumm(
            //@ts-ignore
            quote.evo_fin_department_reward_conditionid,
            quote,
            'evo_fin_department_reward_summ',
            'evo_fin_department_reward_total',
          );
        }

        const dealerRewardSumm = await getRewardSumm(
          //@ts-ignore
          quote.evo_dealer_reward_conditionid,
          quote,
          'evo_dealer_reward_summ',
          'evo_dealer_reward_total',
        );

        const dealerBrokerRewardSumm = await getRewardSumm(
          //@ts-ignore
          quote.evo_dealer_broker_reward_conditionid,
          quote,
          'evo_dealer_broker_reward_summ',
          'evo_dealer_broker_reward_total',
        );

        const calcDoubleRewardSumm = await getRewardSumm(
          //@ts-ignore
          quote.evo_double_agent_reward_conditionid,
          quote,
          'evo_double_agent_reward_summ',
          'evo_double_agent_reward_total',
        );

        const agentsValues = {
          indAgentRewardCondition,
          indAgentRewardSumm,
          calcBrokerRewardCondition,
          calcBrokerRewardSum,
          finDepartmentRewardCondtion,
          finDepartmentRewardSumm,
          dealerRewardSumm,
          dealerBrokerRewardSumm,
          calcDoubleRewardSumm,
        };
        // agents

        // dealer

        let { dealerPerson } = calculationStore.values;

        // TODO: сделать запрос на account
        const dealer = calculationStore.getOption('selectDealer', {
          accountid: quote.evo_supplier_accountid,
        });

        if (dealer?.evo_return_leasing_dealer) {
          calculationStore.setOptions('selectDealerPerson', []);
          calculationStore.setValue('dealerPerson', null);
          calculationStore.setStatus(
            'selectDealerPerson',
            ElementStatus.Disabled,
          );
        } else {
          const { selectDealerPerson: dealerPersonOptions } =
            await CrmService.getCRMOptions<'selectDealerPerson', IAccount>({
              query: gql`
                query GetSelectDealerPersonByQuote($dealerId: Uuid!) {
                  selectDealerPerson: salon_providers(
                    statecode: 0
                    salonaccountid: $dealerId
                  ) {
                    accountid
                    name
                    evo_broker_accountid
                    evo_kpp
                    evo_inn
                    evo_supplier_type
                  }
                }
              `,
              variables: {
                dealerId: quote.evo_supplier_accountid,
              },
            });

          const dealer_broker_accountid =
            dealerPersonOptions &&
            dealerPersonOptions?.length > 0 &&
            dealerPersonOptions[0].evo_broker_accountid;
          if (dealer_broker_accountid) {
            const { selectDealerBroker: dealerBrokerOptions } =
              await CrmService.getCRMOptions<'selectDealerBroker', IAccount>({
                query: gql`
                  query GetDealerBrokerByDealerPerson($brokerid: Uuid!) {
                    selectDealerBroker: account(accountid: $brokerid) {
                      accountid
                      name
                    }
                  }
                `,
                variables: {
                  brokerid: dealer_broker_accountid,
                },
              });
            if (dealerBrokerOptions)
              calculationStore.setOptions(
                'selectDealerBroker',
                dealerBrokerOptions,
              );
          }

          if (dealerPersonOptions?.length) {
            calculationStore.setOptions(
              'selectDealerPerson',
              dealerPersonOptions,
            );
            dealerPerson = quote.evo_dealer_person_accountid;
            calculationStore.setStatus(
              'selectDealerPerson',
              ElementStatus.Default,
            );
          }
        }

        // dealer

        // fill insurance table
        calculationStore.setTableRows(
          'tableInsurance',
          0,
        )([
          {
            insuranceCompany: {
              value: quote?.evo_osago_accountid,
            },
            insured: { value: quote.evo_osago_payer },
            insCost: { value: quote.evo_osago_price || 0 },
          },
          {
            insuranceCompany: {
              value: quote.evo_kasko_accountid,
            },
            insured: { value: quote.evo_kasko_payer },
            insCost: { value: quote.evo_kasko_price || 0 },
            insTerm: { value: quote.evo_insurance_period },
          },
          {
            insuranceCompany: {
              value: quote.evo_kasko_accountid,
            },
            insured: { value: quote.evo_kasko_payer },
            insCost: { value: quote.evo_dgo_price || 0 },
            insTerm: { value: quote.evo_insurance_period },
          },
          {
            insuranceCompany: {
              value: quote.evo_kasko_accountid,
            },
            insured: { value: quote.evo_kasko_payer },
            insCost: { value: quote.evo_ns_price || 0 },
            insTerm: { value: quote.evo_insurance_period },
          },
          {
            insuranceCompany: {
              value: quote.evo_fingap_accountid,
            },
            insured: { value: quote.evo_fingap_payer },
            // insCost: { value: quote.evo_fingap_price },
            insTerm: { value: quote.evo_fingap_period },
          },
        ]);
        // fill insurance table

        // fill finGAP
        const selectedRisks = quote.evo_product_risks?.map(
          x => x.evo_addproduct_typeid,
        );
        const { $finGAP } = calculationStore.stores;
        if (selectedRisks) $finGAP.setSelectedKeys(selectedRisks);
        // fill finGAP

        // fill payments table
        let evo_graph: IEvoGraph = {};
        const leasingPeriod = getLeasingPeriod(recalcWithRevision, quote);

        if (quote.evo_graphs) {
          evo_graph = quote.evo_graphs.sort(
            //@ts-ignore
            (a, b) => b.createdon - a.createdon,
          )[0];
          if (evo_graph.evo_planpayments) {
            const statuses = tablePaymentsStatuses(
              quote.evo_graph_type,
              quote.evo_seasons_type,
              leasingPeriod,
            );
            const payments = evo_graph.evo_planpayments
              .slice(1, evo_graph.evo_planpayments.length - 1)
              //@ts-ignore
              .slice(0, leasingPeriod - 2)
              .map((evo_planpayment, i) => ({
                paymentRelation: {
                  validation: undefined,
                  value: evo_planpayment.evo_payment_ratio,
                  status: statuses?.includes(i + 1)
                    ? ElementStatus.Default
                    : ElementStatus.Disabled,
                },
              }));
            calculationStore.replaceTableRows('tablePayments')([
              {
                paymentRelation: {
                  value: quote.evo_first_payment_perc,
                  status: ElementStatus.Disabled,
                },
              },
              ...payments,
              {
                paymentRelation: {
                  value: quote.evo_last_payment_perc,
                  status: ElementStatus.Disabled,
                },
              },
            ]);
          }
        }
        // fill payments table

        // get product evo_id
        const base_product = calculationStore.getOption('selectProduct', {
          evo_baseproductid: newValues.product,
        });
        const product = base_product?.evo_id;
        // get product evo_id

        // get addproducts
        let addProducts = Object.assign(
          {},
          ...Object.keys(map_add_product_types_to_values).map(valueName => {
            const target_add_product_type = quote?.evo_addproduct_types?.find(
              x =>
                x.evo_product_type ===
                map_add_product_types_to_values[valueName],
            );

            return {
              [valueName]: target_add_product_type?.evo_addproduct_typeid,
            };
          }),
        );
        // get addproducts

        // get clientRisk
        let clientRisk = quote.evo_client_riskid;
        if (opportunity) {
          const current_opportunity = calculationStore.getOption(
            'selectOpportunity',
            {
              value: opportunity,
            },
          );

          if (current_opportunity) {
            const { evo_programsolution, evo_client_riskid } =
              current_opportunity;

            if (evo_programsolution === 100000000) {
              const midClientRisk = calculationStore.getOption(
                'selectClientRisk',
                {
                  evo_id: '2',
                },
              );
              if (midClientRisk) {
                clientRisk = midClientRisk.evo_client_riskid;
              }
            } else if (evo_programsolution !== 100000000 && evo_client_riskid) {
              clientRisk = evo_client_riskid;
            }
          }
        }
        // get clientRisk

        // recalc fields
        let vehicleTaxInYear = quote['evo_vehicle_tax_year'];
        let leaseObjectCount = quote.evo_object_count;
        let requirementTelematic = quote.evo_req_telematic;
        if (recalcWithRevision) {
          requirementTelematic = quote.evo_req_telematic_accept;
          if (quote['evo_vehicle_tax_approved']) {
            vehicleTaxInYear = quote['evo_vehicle_tax_approved'];
          }
          if (quote.evo_recalc_limit) {
            leaseObjectCount = quote.evo_recalc_limit;
          }
          // telematic/tracker
          addProducts.telematic = undefined;
          addProducts.tracker = undefined;
          const add_product_types = calculationStore.getStaticData(
            'evo_addproduct_type',
          );
          const targetAddproduct = add_product_types.find(
            x =>
              x.evo_addproduct_typeid ===
              quote.evo_accept_control_addproduct_typeid,
          );
          if (targetAddproduct?.evo_product_type) {
            const targetAddProductValueName = invert(
              map_add_product_types_to_values,
            )[targetAddproduct?.evo_product_type];
            addProducts[targetAddProductValueName] =
              targetAddproduct.evo_addproduct_typeid;
          }
        }
        // recalc fields

        // regions & towns
        let legalClientRegion;
        let regionRegistration;
        let legalClientTown;
        let townRegistration;
        const objectRegistration = getObjectRegistration(
          recalcWithRevision,
          quote,
        );

        {
          const lead = calculationStore.getOption('selectLead');
          const opportunity = calculationStore.getOption('selectOpportunity');

          const evo_region_fias_id = get(
            lead?.accountidData || opportunity?.accountidData,
            'evo_address_legalidData.evo_region_fias_id',
            undefined,
          );

          // legalClientRegion
          if (evo_region_fias_id) {
            const region = calculationStore.getOption(
              'selectLegalClientRegion',
              {
                evo_fias_id: evo_region_fias_id,
              },
            );
            legalClientRegion = region?.evo_regionid;
            calculationStore.setStatus(
              'selectLegalClientRegion',
              ElementStatus.Disabled,
            );
          } else {
            legalClientRegion = quote.evo_legal_regionid;
            calculationStore.setStatus(
              'selectLegalClientRegion',
              ElementStatus.Default,
            );
          }
          // legalClientRegion

          // regionRegistration
          if (objectRegistration === 100000001) {
            regionRegistration = quote.evo_regionid;

            const filter = regions =>
              regions.filter(x => x.evo_businessunit_evolution === true);

            calculationStore.setFilter('selectRegionRegistration', filter);

            /**
             * TODO: Для нового калькулятора:
             * костыль: скидываем значение поля selectRegionRegistration
             * после фильтрации чтобы не ставилось значение из КП которого нет в отфильтрованном списке
             */
            if (
              !calculationStore
                .getOptions('selectRegionRegistration', undefined, true)
                ?.find(x => x.value === regionRegistration)
            ) {
              regionRegistration = null;
            }
            calculationStore.setStatus(
              'selectRegionRegistration',
              ElementStatus.Default,
            );
          } else {
            calculationStore.setFilter('selectRegionRegistration', undefined);
            if (evo_region_fias_id) {
              const region = calculationStore.getOption(
                'selectRegionRegistration',
                {
                  evo_fias_id: evo_region_fias_id,
                },
              );

              regionRegistration = region?.evo_regionid;
              calculationStore.setStatus(
                'selectRegionRegistration',
                ElementStatus.Disabled,
              );
            } else {
              regionRegistration = quote.evo_regionid;
              calculationStore.setStatus(
                'selectRegionRegistration',
                ElementStatus.Default,
              );
            }
          }
          // regionRegistration

          const secondaryOptions = await CrmService.getCRMOptions<
            ElementsNames,
            IEvoTown
          >({
            query: secondaryOptionsForQuoteQuery,
            variables: {
              statecode: 0,
              evo_regionid: regionRegistration || NIL,
              evo_legal_regionid: legalClientRegion || NIL,
            },
          });

          calculationStore.applyOptions(secondaryOptions);

          const evo_city_fias_id = get(
            lead?.accountidData || opportunity?.accountidData,
            'evo_address_legalidData.evo_city_fias_id',
            undefined,
          );

          // legalClientTown
          if (evo_city_fias_id) {
            const town = calculationStore.getOption('selectLegalClientTown', {
              evo_fias_id: evo_city_fias_id,
            });
            legalClientTown = town?.evo_townid;
            calculationStore.setStatus(
              'selectLegalClientTown',
              ElementStatus.Disabled,
            );
          } else {
            if (
              (
                secondaryOptions?.selectLegalClientTown as IEvoTown[]
              )?.findIndex(x => x.evo_townid === 'quote?.evo_legal_townid') > -1
            ) {
              legalClientTown = quote.evo_legal_townid;
            }
            calculationStore.setStatus(
              'selectLegalClientTown',
              ElementStatus.Default,
            );
          }
          // legalClientTown

          //townRegistration
          if (objectRegistration === 100000001) {
            if (
              (
                secondaryOptions?.selectTownRegistration as IEvoTown[]
              )?.findIndex(x => x.evo_townid === quote.evo_townid) > -1
            ) {
              townRegistration = quote.evo_townid;
            }
            calculationStore.setFilter('selectTownRegistration', towns =>
              towns.filter(x => x.evo_businessunit_evolution === true),
            );
            calculationStore.setStatus(
              'selectTownRegistration',
              ElementStatus.Default,
            );
          } else {
            calculationStore.setFilter('selectTownRegistration', undefined);
            if (evo_city_fias_id) {
              const town = calculationStore.getOption(
                'selectTownRegistration',
                {
                  evo_fias_id: evo_city_fias_id,
                },
              );

              townRegistration = town?.evo_townid;
              calculationStore.setStatus(
                'selectTownRegistration',
                ElementStatus.Disabled,
              );
            } else {
              if (
                (
                  secondaryOptions?.selectTownRegistration as IEvoTown[]
                )?.findIndex(x => x.evo_townid === quote.evo_townid) > -1
              ) {
                townRegistration = quote.evo_townid;
              }
              calculationStore.setStatus(
                'selectTownRegistration',
                ElementStatus.Default,
              );
            }
          }
          //townRegistration
        }

        // redemptionPayment
        let redemptionPaymentSum =
          quote.evo_payment_redemption_sum ||
          initialValues.redemptionPaymentSum;
        // redemptionPayment

        // engineHours
        const engineHours = quote?.evo_engine_hours || 0;
        // engineHours

        const finalValues = {
          ...initialValues,
          ...newValues,
          product,
          ...addProducts,
          rate,
          lead,
          opportunity,
          quote: quoteId,
          recalcWithRevision,
          leaseObjectCount,
          clientRisk,
          calcType,
          totalPayments: evo_graph.evo_sumpay_withnds,
          indAgent,
          vehicleTaxInYear,
          INNForCalc,
          creditRate,
          infuranceOPF,
          legalClientRegion,
          regionRegistration,
          legalClientTown,
          townRegistration,
          calcBroker,
          calcFinDepartment,
          requirementTelematic,
          balanceHolder,
          redemptionPaymentSum,
          ...agentsValues,
          engineHours,
          leasingPeriod,
          objectRegistration,
          dealerPerson,
        };

        // check min max number values
        let fixedElementsNames: ElementsNames[] = [];
        (Object.keys(numberElementsProps) as ElementsNames[]).forEach(
          elementName => {
            const elementProps = numberElementsProps[elementName];
            const valueName = getValueName(elementName);

            if (
              finalValues[valueName] &&
              ((elementProps?.min &&
                finalValues[valueName] < parseFloat(elementProps?.min)) ||
                (elementProps?.max &&
                  finalValues[valueName] > parseFloat(elementProps?.max)))
            ) {
              finalValues[valueName] = initialValues[valueName];
              fixedElementsNames.push(elementName);
            }
          },
        );
        if (fixedElementsNames.length > 0) {
          const fieldsTitles = fixedElementsNames
            .map(x => getTitle(x))
            .join(', ');
          openNotification({
            type: 'warning',
            message: 'Внимание',
            description: 'При подгрузке КП были сброшены поля: ' + fieldsTitles,
          });
        }
        // check min max number values

        calculationStore.setValues(finalValues, true);

        message.success({
          content: `КП ${quote?.evo_quotename || ''} загружено!`,
        });

        const { ELTStore } = calculationStore.stores;
        // ELT KASKO
        {
          resetIns.call(calculationStore, 'kasko');
          const kaskoIndex = ELTStore.kasko.list.findIndex(
            x => x.accountid === quote.evo_kasko_accountid,
          );

          if (kaskoIndex >= 0) {
            const mapQuoteToELTKasko = {
              key: 'evo_kasko_accountid',
              accountid: 'evo_kasko_accountid',
              kaskoSum: 'evo_kasko_price',
              requestId: 'evo_id_elt_kasko',
              skCalcId: 'evo_id_kasko_calc',
              totalFranchise: 'evo_franchise',
            };

            let row = {};
            Object.keys(mapQuoteToELTKasko).forEach(rowFieldName => {
              const quoteFieldName = mapQuoteToELTKasko[rowFieldName];
              const quoteValue = get(quote, quoteFieldName);
              if (!isNil(quoteValue)) row[rowFieldName] = quoteValue;
            });
            if (
              Object.keys(mapQuoteToELTKasko).length === Object.keys(row).length
            ) {
              ELTStore.addToCompanyRes('kasko', kaskoIndex, row);
              ELTStore.kasko.setKey(quote.evo_kasko_accountid);
            }
          }
        }

        // ELT OSAGO
        {
          resetIns.call(calculationStore, 'osago');
          const osagoIndex = ELTStore.osago.list.findIndex(
            x => x.accountid === quote.evo_osago_accountid,
          );
          if (osagoIndex >= 0) {
            const mapQuoteToELTOsago = {
              key: 'evo_osago_accountid',
              accountid: 'evo_osago_accountid',
              numCalc: 'evo_id_elt_osago',
              premiumSum: 'evo_osago_price',
            };

            let row = {};
            Object.keys(mapQuoteToELTOsago).forEach(rowFieldName => {
              const quoteFieldName = mapQuoteToELTOsago[rowFieldName];
              const quoteValue = get(quote, quoteFieldName);
              if (!isNil(quoteValue)) row[rowFieldName] = quoteValue;
            });

            if (row['numCalc']) {
              row['numCalc'] = parseInt(row['numCalc']);
            }

            if (isEqual(Object.keys(row), Object.keys(mapQuoteToELTOsago))) {
              ELTStore.addToCompanyRes('osago', osagoIndex, row);
              ELTStore.osago.setKey(quote.evo_osago_accountid);
            }
          }
        }
      })
      .catch(err => {
        openNotification({
          type: 'error',
          message: `Ошибка во время загрузки КП `,
          description: `${err}`,
        });
        throw err;
      })
      .finally(() => {
        calculationStore.setStatus('selectQuote', ElementStatus.Default);
        calculationStore.setStatus('btnCalculate', ElementStatus.Default);
        calculationStore.setStatus('btnCreateKP', ElementStatus.Default);
        calculationProcess.deleteProcess(Process.LoadKp);
      });
  },
});

export default loadKpReaction;
