import { openNotification } from 'client/Elements/Notification';
import valuesConstants from 'core/constants/values';
import { pipe } from 'core/tools/func';
import { IReactionEffect } from 'core/types/Calculation/Store/effect';
import { Process } from 'core/types/Calculation/Store/process';
import { get, intersection } from 'lodash';
import { ElementStatus } from 'types/elements';

const reactionEffects: IReactionEffect[] = [
  calculationStore => ({
    expression: () => {
      const { opportunity } = calculationStore.values;
      return opportunity;
    },
    effect: opportunityid => {
      const opportunity = calculationStore.getOption('selectOpportunity', {
        opportunityid,
      });

      if (opportunity) {
        calculationStore.setValue('lead', opportunity.evo_leadid);
      }
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { indAgentRewardCondition } = calculationStore.values;
      return indAgentRewardCondition;
    },
    effect: indAgentRewardConditionId => {
      if (!indAgentRewardConditionId) {
        calculationStore.setValue('indAgentRewardSumm', 0);
        calculationStore.setStatus(
          'tbxIndAgentRewardSumm',
          ElementStatus.Disabled,
        );

        const lead = calculationStore.getOption('selectLead');
        if (lead && !lead.evo_double_agent_accountid) {
          calculationStore.setValue('calcDoubleAgent', null);
          calculationStore.setStatus(
            'selectCalcDoubleAgent',
            ElementStatus.Disabled,
          );
        }
      } else {
        const indAgentRewardCondition = calculationStore.getOption(
          'selectIndAgentRewardCondition',
          {
            evo_reward_conditionid: indAgentRewardConditionId,
          },
        );
        if (indAgentRewardCondition) {
          if (!calculationProcess.hasProcess(Process.LoadKp)) {
            calculationStore.setValue(
              'indAgentRewardSumm',
              indAgentRewardCondition.evo_reward_summ || 0,
            );
          }
          calculationStore.setStatus(
            'tbxIndAgentRewardSumm',
            ElementStatus.Default,
          );
          if (indAgentRewardCondition?.evo_double_agent_accountid) {
            calculationStore.setStatus(
              'selectCalcDoubleAgent',
              ElementStatus.Default,
            );

            const doubleAgent = calculationStore.getOption(
              'selectCalcDoubleAgent',
              {
                accountid: indAgentRewardCondition?.evo_double_agent_accountid,
              },
            );
            if (doubleAgent) {
              calculationStore.setOptions('selectCalcDoubleAgent', [
                doubleAgent,
              ]);
              calculationStore.setValue(
                'calcDoubleAgent',
                doubleAgent.accountid,
              );
            }
          } else {
            calculationStore.setValue('calcDoubleAgent', null);
            calculationStore.setStatus(
              'selectCalcDoubleAgent',
              ElementStatus.Disabled,
            );
          }
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { calcDoubleAgentRewardCondition } = calculationStore.values;
      return calcDoubleAgentRewardCondition;
    },
    effect: calcDoubleAgentRewardConditionId => {
      if (!calcDoubleAgentRewardConditionId) {
        calculationStore.setValue('calcDoubleAgentRewardSumm', 0);
        calculationStore.setStatus(
          'tbxCalcDoubleAgentRewardSumm',
          ElementStatus.Disabled,
        );
      } else {
        const calcDoubleAgentRewardCondition = calculationStore.getOption(
          'selectCalcDoubleAgentRewardCondition',
          {
            evo_reward_conditionid: calcDoubleAgentRewardConditionId,
          },
        );
        if (
          calcDoubleAgentRewardCondition &&
          calcDoubleAgentRewardCondition.evo_reward_summ
        ) {
          if (!calculationProcess.hasProcess(Process.LoadKp)) {
            calculationStore.setValue(
              'calcDoubleAgentRewardSumm',
              calcDoubleAgentRewardCondition.evo_reward_summ,
            );
          }
          calculationStore.setStatus(
            'tbxCalcDoubleAgentRewardSumm',
            ElementStatus.Default,
          );
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  //TODO: compose
  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { calcBrokerRewardCondition } = calculationStore.values;
      return calcBrokerRewardCondition;
    },
    effect: calcBrokerRewardConditionId => {
      if (!calcBrokerRewardConditionId) {
        calculationStore.setValue('calcBrokerRewardSum', 0);
        calculationStore.setStatus(
          'tbxCalcBrokerRewardSum',
          ElementStatus.Disabled,
        );
      } else {
        const calcBrokerRewardCondition = calculationStore.getOption(
          'selectCalcBrokerRewardCondition',
          {
            evo_reward_conditionid: calcBrokerRewardConditionId,
          },
        );
        if (
          calcBrokerRewardCondition &&
          calcBrokerRewardCondition.evo_reward_summ
        ) {
          if (!calculationProcess.hasProcess(Process.LoadKp)) {
            calculationStore.setValue(
              'calcBrokerRewardSum',
              calcBrokerRewardCondition.evo_reward_summ,
            );
          }
          calculationStore.setStatus(
            'tbxCalcBrokerRewardSum',
            ElementStatus.Default,
          );
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { finDepartmentRewardCondtion } = calculationStore.values;
      return finDepartmentRewardCondtion;
    },
    effect: finDepartmentRewardCondtionId => {
      if (!finDepartmentRewardCondtionId) {
        calculationStore.setValue('finDepartmentRewardSumm', 0);
        calculationStore.setStatus(
          'tbxFinDepartmentRewardSumm',
          ElementStatus.Disabled,
        );
      } else {
        const finDepartmentRewardCondtion = calculationStore.getOption(
          'selectFinDepartmentRewardCondtion',
          { evo_reward_conditionid: finDepartmentRewardCondtionId },
        );
        if (
          finDepartmentRewardCondtion &&
          finDepartmentRewardCondtion.evo_reward_summ
        ) {
          if (!calculationProcess.hasProcess(Process.LoadKp)) {
            calculationStore.setValue(
              'finDepartmentRewardSumm',
              finDepartmentRewardCondtion.evo_reward_summ,
            );
          }
          calculationStore.setStatus(
            'tbxFinDepartmentRewardSumm',
            ElementStatus.Default,
          );
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  calculationStore => ({
    expression: () => {
      const { leaseObjectUsed } = calculationStore.values;
      return leaseObjectUsed;
    },
    effect: leaseObjectUsed => {
      if (leaseObjectUsed) {
        calculationStore.setValue('leaseObjectCount', 1);
        calculationStore.setStatus(
          'tbxLeaseObjectCount',
          ElementStatus.Disabled,
        );
      } else {
        calculationStore.setStatus(
          'tbxLeaseObjectCount',
          ElementStatus.Default,
        );
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  calculationStore => ({
    expression: () => {
      const { lastPaymentRule } = calculationStore.values;
      return lastPaymentRule;
    },
    effect: lastPaymentRule => {
      switch (lastPaymentRule) {
        case 100_000_000: {
          calculationStore.setStatus(
            'tbxLastPaymentPerc',
            ElementStatus.Disabled,
          );
          calculationStore.setStatus(
            'tbxLastPaymentRub',
            ElementStatus.Default,
          );
          break;
        }
        case 100_000_001: {
          calculationStore.setStatus(
            'tbxLastPaymentPerc',
            ElementStatus.Default,
          );
          calculationStore.setStatus(
            'tbxLastPaymentRub',
            ElementStatus.Disabled,
          );
          break;
        }
        default: {
          calculationStore.setStatus(
            'tbxLastPaymentPerc',
            ElementStatus.Disabled,
          );
          calculationStore.setStatus(
            'tbxLastPaymentRub',
            ElementStatus.Disabled,
          );
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  calculationStore => ({
    expression: () => {
      return calculationStore.getValues(['lastPaymentRub', 'insNSIB']);
    },
    effect: ({ lastPaymentRub, insNSIB }) => {
      if (insNSIB && lastPaymentRub && lastPaymentRub < 3500) {
        calculationStore.setValidation('tbxLastPaymentRub', false);
        openNotification({
          type: 'error',
          message: 'Ошибка',
          description:
            'Последний платеж меньше 3500 руб. не может быть при наличии НСИБ, укажите большее значение',
        });
      } else {
        calculationStore.setValidation('tbxLastPaymentRub', true);
      }
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => calculationStore.values.graphType,
    effect: graphType => {
      if (!calculationProcess.hasProcess(Process.LoadKp)) {
        calculationStore.setValue('seasonType', null);
        calculationStore.setValue('highSeasonStart', null);
        calculationStore.setValue('parmentsDecreasePercent', 96);
      }

      switch (graphType) {
        case 100000001: {
          calculationStore.setStatus('selectSeasonType', ElementStatus.Default);

          calculationStore.setStatus(
            'tbxParmentsDecreasePercent',
            ElementStatus.Disabled,
          );
          calculationStore.setStatus(
            'selectHighSeasonStart',
            ElementStatus.Disabled,
          );
          break;
        }

        case 100000002: {
          calculationStore.setStatus(
            'selectSeasonType',
            ElementStatus.Disabled,
          );
          calculationStore.setStatus(
            'tbxParmentsDecreasePercent',
            ElementStatus.Default,
          );
          calculationStore.setStatus(
            'selectHighSeasonStart',
            ElementStatus.Disabled,
          );
          break;
        }

        case 100000003: {
          calculationStore.setStatus('selectSeasonType', ElementStatus.Default);

          calculationStore.setStatus(
            'tbxParmentsDecreasePercent',
            ElementStatus.Disabled,
          );
          calculationStore.setStatus(
            'selectHighSeasonStart',
            ElementStatus.Default,
          );
          break;
        }

        case null:
        default: {
          calculationStore.setStatus(
            'selectSeasonType',
            ElementStatus.Disabled,
          );
          calculationStore.setStatus(
            'tbxParmentsDecreasePercent',
            ElementStatus.Disabled,
          );
          calculationStore.setStatus(
            'selectHighSeasonStart',
            ElementStatus.Disabled,
          );
          break;
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  calculationStore => ({
    expression: () => calculationStore.getOption('selectSeasonType'),
    effect: ({ forbiddenHighSeasonStart }) => {
      if (forbiddenHighSeasonStart) {
        calculationStore.setFilter('selectHighSeasonStart', seasonStart =>
          seasonStart.filter(s => !forbiddenHighSeasonStart.includes(s.name)),
        );
      } else {
        calculationStore.setFilter('selectHighSeasonStart', undefined);
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  calculationStore => ({
    expression: () => {
      const { leasingPeriod } = calculationStore.values;
      return leasingPeriod;
    },
    effect: leasingPeriod => {
      if (leasingPeriod) {
        if (parseInt(leasingPeriod) < 12) {
          calculationStore.setValue('insNSIB', null);
          calculationStore.setStatus('selectInsNSIB', ElementStatus.Disabled);
        } else {
          calculationStore.setStatus('selectInsNSIB', ElementStatus.Default);
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  // calculationStore => ({
  //   expression: () => {
  //     const { leasingPeriod } = calculationStore.values;
  //     return leasingPeriod;
  //   },
  //   effect: leasingPeriod => {
  //     if (leasingPeriod) {
  //       if (parseInt(leasingPeriod) < 13) {
  //         calculationStore.setStatus(
  //           'radioBalanceHolder',
  //           ElementStatus.Disabled,
  //         );
  //         calculationStore.setValue('balanceHolder', 100000000);
  //       } else {
  //         calculationStore.setStatus(
  //           'radioBalanceHolder',
  //           ElementStatus.Default,
  //         );
  //       }
  //     }
  //   },
  //   options: {
  //     fireImmediately: true,
  //   },
  // }),

  calculationStore => ({
    expression: () => {
      const { balanceHolder } = calculationStore.values;
      return balanceHolder;
    },
    effect: balanceHolder => {
      if (balanceHolder) {
        if (balanceHolder === 100000001) {
          calculationStore.setStatus(
            'cbxLastPaymentRedemption',
            ElementStatus.Disabled,
          );
          calculationStore.setValue('lastPaymentRedemption', true);
        } else {
          calculationStore.setStatus(
            'cbxLastPaymentRedemption',
            ElementStatus.Default,
          );
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { dealerRewardCondition } = calculationStore.values;
      return dealerRewardCondition;
    },
    effect: dealerRewardConditionId => {
      if (!dealerRewardConditionId) {
        calculationStore.setValue('dealerRewardSumm', 0);
        calculationStore.setStatus(
          'tbxDealerRewardSumm',
          ElementStatus.Disabled,
        );
      } else {
        const dealerRewardContition = calculationStore.getOption(
          'selectDealerRewardCondition',
          { evo_reward_conditionid: dealerRewardConditionId },
        );
        if (dealerRewardContition) {
          if (dealerRewardContition.evo_reward_summ) {
            if (!calculationProcess.hasProcess(Process.LoadKp)) {
              calculationStore.setValue(
                'dealerRewardSumm',
                dealerRewardContition.evo_reward_summ,
              );
            }
            calculationStore.setStatus(
              'tbxDealerRewardSumm',
              ElementStatus.Default,
            );
          }
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  calculationStore => ({
    expression: () => {
      const { dealerRewardCondition, dealerPerson } = calculationStore.values;
      return [dealerRewardCondition, dealerPerson];
    },
    effect: ([dealerRewardConditionId, dealerPersonId]) => {
      if (!dealerRewardConditionId && dealerPersonId) {
        calculationStore.setStatus('selectDealerBroker', ElementStatus.Default);
      } else {
        calculationStore.setValue('dealerBroker', null);
        calculationStore.setStatus(
          'selectDealerBroker',
          ElementStatus.Disabled,
        );
      }
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { dealerBrokerRewardCondition } = calculationStore.values;
      return dealerBrokerRewardCondition;
    },
    effect: dealerBrokerRewardConditionId => {
      if (!dealerBrokerRewardConditionId) {
        calculationStore.setValue('dealerBrokerRewardSumm', 0);
        calculationStore.setStatus(
          'tbxDealerBrokerRewardSumm',
          ElementStatus.Disabled,
        );
      } else {
        const dealerBrokerRewardContition = calculationStore.getOption(
          'selectDealerBrokerRewardCondition',
          { evo_reward_conditionid: dealerBrokerRewardConditionId },
        );
        if (
          dealerBrokerRewardContition &&
          dealerBrokerRewardContition.evo_reward_summ
        ) {
          if (!calculationProcess.hasProcess(Process.LoadKp)) {
            calculationStore.setValue(
              'dealerBrokerRewardSumm',
              dealerBrokerRewardContition.evo_reward_summ,
            );
          }
          calculationStore.setStatus(
            'tbxDealerBrokerRewardSumm',
            ElementStatus.Default,
          );
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  calculationStore => ({
    expression: () => {
      const { dealerRewardSumm } = calculationStore.values;
      return dealerRewardSumm;
    },
    effect: dealerRewardSumm => {
      const dealerRewardCondition = calculationStore.getOption(
        'selectDealerRewardCondition',
      );
      if (dealerRewardCondition && dealerRewardCondition.evo_reward_summ) {
        if (
          parseFloat(dealerRewardSumm) > dealerRewardCondition.evo_reward_summ
        ) {
          calculationStore.setValidation('tbxDealerRewardSumm', false);
          openNotification({
            type: 'error',
            message: 'Ошибка',
            description:
              'Вознаграждение ЮЛ поставщика указано больше условия по агентскому договору! \nЗначение установлено по условию договора.',
          });
          return;
        } else if (
          !dealerRewardCondition.evo_reduce_reward &&
          dealerRewardCondition.evo_reward_summ
        ) {
          if (
            parseFloat(dealerRewardSumm) < dealerRewardCondition.evo_reward_summ
          ) {
            calculationStore.setValidation('tbxDealerRewardSumm', false);
            openNotification({
              type: 'error',
              message: 'Ошибка',
              description:
                'Вознаграждение ЮЛ поставщика указано меньше условия по агентскому договору! \nЗначение установлено по условию договора.',
            });
            return;
          }
        }
        calculationStore.setValidation('tbxDealerRewardSumm', true);
      }
    },
  }),

  calculationStore => ({
    expression: () => {
      const { configuration } = calculationStore.values;
      const { selectConfiguration } = calculationStore.options;
      return [configuration, selectConfiguration];
    },
    effect: ([configurationId, selectConfigurationOptions]) => {
      if (selectConfigurationOptions && selectConfigurationOptions.length) {
        if (!configurationId) {
          calculationStore.setValidation('selectConfiguration', false);
          return;
        }
      }
      calculationStore.setValidation('selectConfiguration', true);
    },
  }),

  calculationStore => ({
    expression: () => {
      const { model, configuration } = calculationStore.values;
      return [model, configuration];
    },
    effect: ([modelId, configurationId]) => {
      if (configurationId) {
        const configuration = calculationStore.getOption(
          'selectConfiguration',
          {
            evo_equipmentid: configurationId,
          },
        );
        if (configuration && configuration.evo_impairment_groupid) {
          const evo_impairment_groups = calculationStore.getStaticData(
            'evo_impairment_group',
          );
          const evo_impairment_group = evo_impairment_groups.find(
            x =>
              x.evo_impairment_groupid === configuration.evo_impairment_groupid,
          );
          calculationStore.setValue(
            'depreciationGroup',
            evo_impairment_group ? evo_impairment_group.evo_name : '',
          );
          return;
        }
      }
      const model = calculationStore.getOption('selectModel', {
        evo_modelid: modelId,
      });
      if (model && model.evo_impairment_groupid) {
        const evo_impairment_groups = calculationStore.getStaticData(
          'evo_impairment_group',
        );
        const evo_impairment_group = evo_impairment_groups.find(
          x => x.evo_impairment_groupid === model.evo_impairment_groupid,
        );
        calculationStore.setValue(
          'depreciationGroup',
          evo_impairment_group ? evo_impairment_group.evo_name : '',
        );
        return;
      }
      calculationStore.setValue('depreciationGroup', null);
    },
  }),

  calculationStore => ({
    expression: () => {
      const { leaseObjectCategory } = calculationStore.values;
      return leaseObjectCategory;
    },
    effect: leaseObjectCategory => {
      if (
        leaseObjectCategory === 100000001 ||
        leaseObjectCategory === 100000003
      ) {
        calculationStore.setValue('withTrailer', false);
        calculationStore.setStatus('cbxWithTrailer', ElementStatus.Disabled);
      } else {
        calculationStore.setStatus('cbxWithTrailer', ElementStatus.Default);
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  calculationStore => ({
    expression: () => {
      const { brand, model, leaseObjectUsed } = calculationStore.values;
      return [brand, model, leaseObjectUsed];
    },
    effect: ([brandId, modelId, leaseObjectUsed]) => {
      if (leaseObjectUsed === false) {
        const model = calculationStore.getOption('selectModel', {
          evo_modelid: modelId,
        });
        const brand = calculationStore.getOption('selectBrand', {
          evo_brandid: brandId,
        });

        if (
          model &&
          ((model.evo_importer_reward_perc &&
            model.evo_importer_reward_perc > 0) ||
            (model.evo_importer_reward_rub &&
              model.evo_importer_reward_rub > 0))
        ) {
          calculationStore.setValue(
            'importerRewardPerc',
            model.evo_importer_reward_perc || 0,
          );
          calculationStore.setValue(
            'importerRewardRub',
            model.evo_importer_reward_rub || 0,
          );
          return;
        }
        if (
          brand &&
          ((brand.evo_importer_reward_perc &&
            brand.evo_importer_reward_perc > 0) ||
            (brand.evo_importer_reward_rub &&
              brand.evo_importer_reward_rub > 0))
        ) {
          calculationStore.setValue(
            'importerRewardPerc',
            brand.evo_importer_reward_perc || 0,
          );
          calculationStore.setValue(
            'importerRewardRub',
            brand.evo_importer_reward_rub || 0,
          );
          return;
        }
      }
      calculationStore.setValue('importerRewardPerc', 0);
      calculationStore.setValue('importerRewardRub', 0);
    },
    options: { fireImmediately: true },
  }),

  calculationStore => ({
    expression: () => {
      const { graphType, leasingPeriod } = calculationStore.values;
      return { graphType, leasingPeriod };
    },
    effect: ({ graphType, leasingPeriod }) => {
      if (graphType === 100000003 && leasingPeriod < 14) {
        setTimeout(() => {
          calculationStore.setValue('leasingPeriod', 14);
        }, 0);
        openNotification({
          type: 'warning',
          message: 'Внимание!',
          description:
            'При сезонном графике срок лизинга должен быть больше 14 месяцев',
        });
      }
    },
  }),

  // // TODO
  // calculationStore => ({
  //   expression: () => {
  //     const { product } = calculationStore.values;
  //     return product;
  //   },
  //   effect: productId => {
  //     if (productId) {
  //       const product = calculationStore.getOption('selectProduct', {
  //         evo_id: productId,
  //       });
  //       if (
  //         product &&
  //         product.evo_leasingobject_types &&
  //         Array.isArray(product.evo_leasingobject_types)
  //       ) {
  //         calculationStore.setOptions(
  //           'selectLeaseObjectType',
  //           product.evo_leasingobject_types,
  //         );
  //       }
  //     }
  //   },
  // }),

  calculationStore => ({
    expression: () => {
      const { leasingPeriod, leaseObjectType } = calculationStore.values;
      return { leasingPeriod, leaseObjectType };
    },
    effect: ({ leasingPeriod, leaseObjectType }) => {
      calculationStore.setFilter('selectTechnicalCard', options =>
        options.filter(
          x =>
            x?.evo_max_period &&
            x?.evo_min_period &&
            x.evo_max_period >= leasingPeriod &&
            x.evo_min_period <= leasingPeriod &&
            x.evo_leasingobject_types?.find(
              x => x.evo_leasingobject_typeid === leaseObjectType,
            ),
        ),
      );
    },
    options: {
      fireImmediately: true,
    },
  }),

  /**
   * сделали здесь для экономии времени
   * перенести в отдельный процесс leasingWithoutKasko
   */

  calculationStore => ({
    expression: () => {
      //@ts-ignore
      const plPriceRub = calculationStore.plPriceRub();
      //@ts-ignore
      const discountRub = calculationStore.discountRub();
      //@ts-ignore
      const importProgramSum: number = calculationStore.importProgramSum();

      const {
        leasingPeriod,
        leaseObjectType,
        addEquipmentPrice,
        firstPaymentPerc,
        model,
      } = calculationStore.values;
      return {
        leasingPeriod,
        leaseObjectType,
        plPriceRub,
        discountRub,
        addEquipmentPrice,
        importProgramSum,
        firstPaymentPerc,
        modelId: model,
      };
    },
    effect: ({
      leasingPeriod = 0,
      leaseObjectType,
      plPriceRub = 0,
      discountRub = 0,
      addEquipmentPrice = 0,
      importProgramSum = 0,
      firstPaymentPerc = 0,
      modelId,
    }) => {
      calculationStore.setFilter('selectLeasingWithoutKasko', options =>
        options.filter(
          x =>
            x?.evo_max_period !== undefined &&
            x?.evo_min_period !== undefined &&
            x.evo_max_period >= leasingPeriod &&
            x.evo_min_period <= leasingPeriod &&
            x?.evo_max_price !== undefined &&
            x?.evo_min_price !== undefined &&
            x.evo_max_price >=
              plPriceRub - discountRub - importProgramSum + addEquipmentPrice &&
            x.evo_min_price <=
              plPriceRub - discountRub - importProgramSum + addEquipmentPrice &&
            x.evo_leasingobject_types?.find(
              x => x.evo_leasingobject_typeid === leaseObjectType,
            ) &&
            x.evo_visible_calc &&
            x.evo_min_first_payment_perc !== undefined &&
            x.evo_min_first_payment_perc <= firstPaymentPerc &&
            x.evo_max_first_payment_perc !== undefined &&
            x.evo_max_first_payment_perc >= firstPaymentPerc &&
            !x.evo_models?.map(x => x.evo_modelid).includes(modelId),
        ),
      );
    },
    options: {
      fireImmediately: true,
    },
  }),

  calculationStore => ({
    expression: () => {
      return {
        options: calculationStore.getOptions(
          'selectLeasingWithoutKasko',
          undefined,
          true,
        ),
        value: calculationStore.getValue('leasingWithoutKasko'),
      };
    },
    effect: (nextValues, prevValues) => {
      if (prevValues.value && !nextValues.value) {
        openNotification({
          type: 'warning',
          message: 'Внимание',
          description: 'Лизинг без КАСКО был сброшен',
        });
      }
    },
  }),

  calculationStore => ({
    expression: () => {
      return calculationStore.getValue('leasingWithoutKasko');
    },
    effect: leasingWithoutKasko => {
      if (leasingWithoutKasko) {
        calculationStore.setTableRow('tableInsurance', rows =>
          rows.findIndex(x => x?.key === 'finGAP'),
        )({
          insuranceCompany: {
            value: null,
            status: ElementStatus.Disabled,
          },
        });
      } else {
        calculationStore.setTableRow('tableInsurance', rows =>
          rows.findIndex(x => x?.key === 'finGAP'),
        )({
          insuranceCompany: {
            status: ElementStatus.Default,
          },
        });
      }
    },
  }),

  calculationStore => ({
    expression: () => {
      const { leasingPeriod, leaseObjectType } = calculationStore.values;
      return { leasingPeriod, leaseObjectType };
    },
    effect: ({ leasingPeriod, leaseObjectType }) => {
      calculationStore.setFilter('selectFuelCard', options =>
        options.filter(
          x =>
            x?.evo_max_period &&
            x?.evo_min_period &&
            x.evo_max_period >= leasingPeriod &&
            x.evo_min_period <= leasingPeriod &&
            x.evo_leasingobject_types?.find(
              x => x.evo_leasingobject_typeid === leaseObjectType,
            ),
        ),
      );
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { leaseObjectType } = calculationStore.values;
      return { leaseObjectType };
    },
    effect: () => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }
      calculationStore.setValue('technicalCard', null);
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { leasingPeriod } = calculationStore.values;
      return leasingPeriod;
    },
    effect: () => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }

      const technicalCard = calculationStore.getOption('selectTechnicalCard');

      if (technicalCard) {
        const selectTechnicalCard_filter = calculationStore.getFilter(
          'selectTechnicalCard',
        );

        const selectTechnicalCard_options = calculationStore.getOptions(
          'selectTechnicalCard',
        );

        if (selectTechnicalCard_filter && selectTechnicalCard_options) {
          const new_technicalCard = selectTechnicalCard_filter(
            selectTechnicalCard_options,
          ).find(
            x => x && x.evo_helpcard_type === technicalCard.evo_helpcard_type,
          );

          if (new_technicalCard) {
            calculationStore.setValue(
              'technicalCard',
              new_technicalCard.evo_addproduct_typeid,
            );
          }
        }
      }
    },
  }),

  calculationStore => ({
    expression: () => {
      const {
        leaseObjectType: leaseObjectTypeId,
        countSeats,
        maxMass,
      } = calculationStore.values;
      return { leaseObjectTypeId, countSeats, maxMass };
    },
    effect: ({ leaseObjectTypeId, countSeats, maxMass }) => {
      calculationStore.setValidation('tbxCountSeats', undefined);
      calculationStore.setValidation('tbxMaxMass', undefined);

      // calculationStore.setFilter('selectLeaseObjectCategory', undefined);

      if (!leaseObjectTypeId) {
        return;
      }

      const leaseObjectType = calculationStore.getOption(
        'selectLeaseObjectType',
        {
          evo_leasingobject_typeid: leaseObjectTypeId,
        },
      );

      if (leaseObjectType) {
        switch (leaseObjectType.evo_id) {
          case '1': {
            const { countSeats } = calculationStore.values;
            if (countSeats && countSeats >= 9) {
              calculationStore.setValidation('tbxCountSeats', false);
              openNotification({
                type: 'error',
                message: 'Ошибка',
                description: 'Количество мест должно быть меньше 9',
              });
            }
            break;
          }

          case '2': {
            const { maxMass } = calculationStore.values;
            if (!maxMass) {
              calculationStore.setValidation('tbxMaxMass', false);
              openNotification({
                type: 'error',
                message: 'Ошибка',
                description:
                  'Разрешенная максимальная масса должна быть больше 0',
              });
            }
            break;
          }

          case '4':
          case '5': {
            const { countSeats } = calculationStore.values;
            if (countSeats <= 8) {
              calculationStore.setValidation('tbxCountSeats', false);
              openNotification({
                type: 'error',
                message: 'Ошибка',
                description: 'Кол-во мест должно быть больше 8',
              });
            }
            break;
          }
        }
      }
    },
  }),

  calculationStore => ({
    expression: () => {
      const { priceWithDiscount } = calculationStore.values;
      return priceWithDiscount;
    },
    effect: priceWithDiscount => {
      if (priceWithDiscount === true) {
        calculationStore.setValue('fullPriceWithDiscount', false);
      }
    },
  }),

  calculationStore => ({
    expression: () => {
      const { fullPriceWithDiscount } = calculationStore.values;
      return fullPriceWithDiscount;
    },
    effect: fullPriceWithDiscount => {
      if (fullPriceWithDiscount === true) {
        calculationStore.setValue('priceWithDiscount', false);
      }
    },
  }),

  calculationStore => ({
    expression: () => {
      const { calcType } = calculationStore.values;
      return calcType;
    },
    effect: calcType => {
      switch (calcType) {
        default:
        case 100000000: {
          calculationStore.setStatus('tbxIRR_Perc', ElementStatus.Default);
          calculationStore.setStatus(
            'tbxTotalPayments',
            ElementStatus.Disabled,
          );
          break;
        }
        case 100000001: {
          calculationStore.setStatus('tbxIRR_Perc', ElementStatus.Disabled);
          calculationStore.setStatus('tbxTotalPayments', ElementStatus.Default);
          break;
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  // TODO: revert to validator
  calculationStore => ({
    expression: () => {
      const { graphType, seasonType } = calculationStore.values;
      return [graphType, seasonType];
    },
    effect: ([graphType, seasonType]) => {
      calculationStore.setValidation(
        'selectSeasonType',
        !([100000001, 100000003].includes(graphType) && seasonType === null),
      );
    },
  }),

  calculationStore => ({
    expression: () => {
      const { graphType, highSeasonStart } = calculationStore.values;
      return [graphType, highSeasonStart];
    },
    effect: ([graphType, highSeasonStart]) => {
      calculationStore.setValidation(
        'selectHighSeasonStart',
        !(graphType === 100000003 && highSeasonStart === null),
      );
    },
  }),

  calculationStore => ({
    expression: () => calculationStore.getValue('leaseObjectType'),
    effect: leaseObjectType => {
      !leaseObjectType && calculationStore.setValue('brand', null);
    },
  }),

  calculationStore => ({
    expression: () => {
      return {
        leaseObjectType: calculationStore.getOption('selectLeaseObjectType'),
        product: calculationStore.getOption('selectProduct'),
        subsidy: calculationStore.getOption('selectSubsidy'),
        importProgram: calculationStore.getOption('selectImportProgram'),
      };
    },
    effect: ({ leaseObjectType, product, subsidy, importProgram }) => {
      calculationStore.setStatus(
        'selectBrand',
        leaseObjectType ? ElementStatus.Default : ElementStatus.Disabled,
      );

      calculationStore.setFilter('selectBrand', brands =>
        brands.filter(
          pipe(
            brand =>
              (!product?.evo_brands?.length ||
                product.evo_brands.filter(
                  x => x.evo_brandid === brand?.evo_brandid,
                )?.length) &&
              brand,

            brand =>
              brand?.evo_vehicle_type?.length &&
              intersection(
                brand.evo_vehicle_type?.filter(x => x > 0),
                leaseObjectType.evo_vehicle_type,
              ).length > 0 &&
              brand,

            brand =>
              brand &&
              (!subsidy?.evo_brands?.length ||
                subsidy?.evo_brands?.filter(
                  x => x.evo_brandid === brand.evo_brandid,
                )?.length) &&
              brand,
            brand =>
              brand &&
              (!importProgram?.evo_brands?.length ||
                importProgram?.evo_brands?.filter(
                  x => x.evo_brandid === brand.evo_brandid,
                )?.length),
          ),
        ),
      );
    },
    options: {
      fireImmediately: true,
    },
  }),

  calculationStore => ({
    expression: () => {
      return {
        selectBrandOptions: calculationStore.getOption('selectBrand'),
        selectBrandFilter: calculationStore.getFilter('selectBrand'),
        subsidy: calculationStore.getOption('selectSubsidy'),
        importProgram: calculationStore.getOption('selectImportProgram'),
      };
    },
    effect: ({ subsidy, importProgram }) => {
      const leaseObjectType = calculationStore.getOption(
        'selectLeaseObjectType',
      );
      calculationStore.setFilter('selectModel', options =>
        options.filter(
          pipe(
            model =>
              model.evo_vehicle_type &&
              leaseObjectType?.evo_vehicle_type?.includes(
                model.evo_vehicle_type,
              ) &&
              model,
            model =>
              model &&
              (!subsidy?.evo_models?.length ||
                subsidy?.evo_models?.filter(
                  x => x.evo_modelid === model.evo_modelid,
                )?.length) &&
              model,
            model =>
              model &&
              (!importProgram?.evo_models?.length ||
                importProgram?.evo_models?.filter(
                  x => x.evo_modelid === model.evo_modelid,
                )?.length),
          ),
        ),
      );
    },
  }),

  calculationStore => ({
    expression: () => {
      return {
        lead: calculationStore.getOption('selectLead'),
        opportnity: calculationStore.getOption('selectOpportunity'),
      };
    },
    effect: ({ lead, opportunity }) => {
      const inn = get(lead, 'evo_inn', '');
      calculationStore.setValue('INNForCalc', inn);
    },
  }),

  calculationStore => ({
    expression: () => {
      return calculationStore.getOption('selectRate');
    },
    effect: ({ evo_base_rate }) => {
      calculationStore.setValue(
        'creditRate',
        evo_base_rate !== undefined ? evo_base_rate : valuesConstants.RATE,
      );
    },
  }),

  calculationStore => ({
    expression: () => {
      return calculationStore.getOption('selectTarif');
    },
    effect: tarif => {
      const ratesOptions = calculationStore.getOptions('selectRate');
      if (!ratesOptions) {
        return;
      }

      let rates = ratesOptions.filter(
        rate =>
          rate?.evo_tarifs?.filter(
            evo_tarif => evo_tarif?.evo_tarifid === tarif?.evo_tarifid,
          ).length,
      );

      if (!rates?.length) {
        rates = ratesOptions.filter(rate => rate.evo_id === 'BASE');
      }

      calculationStore.setValue('rate', rates[0].evo_id);
    },
  }),

  calculationStore => ({
    expression: () => calculationStore.getOption('selectLeaseObjectType'),
    effect: leaseObjectType => {
      if (leaseObjectType.evo_id === '7') {
        calculationStore.setValue('withTrailer', true);
      } else {
        calculationStore.setValue('withTrailer', false);
      }
    },
  }),
];

export default reactionEffects;
