import { gql } from '@apollo/client';
import {
  fillCalcBroker,
  fillCalcDoubleAgent,
  fillFinDepartment,
  fillIndAgent,
} from 'client/process/agents/fill-elements';
import CrmService from 'core/services/CrmService';
import { quotesByLeadQuery } from 'core/services/CrmService/graphql/query/quote';
import {
  IAccount,
  IEvoEquipment,
  IEvoGPSModel,
  IEvoModel,
  IEvoRewardCondition,
  IEvoTown,
  IQuote,
  ISalonProvider,
} from 'core/services/CrmService/types/entities';
import { currentISODate } from 'core/tools/date';
import { IReactionEffect } from 'core/types/Calculation/Store/effect';
import { Process } from 'core/types/Calculation/Store/process';
import { ElementStatus } from 'types/elements';

export default [
  (calculationStore, calculationProcess) => ({
    expression: () => calculationStore.getOption('selectLead'),
    effect: async lead => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }
      if (!lead) {
        calculationStore.setValue('opportunity', null);
        calculationStore.setFilter('selectOpportunity', undefined);
        calculationStore.setValue('quote', null);
        calculationStore.setOptions('selectQuote', []);
        return;
      }

      if (lead?.evo_opportunityid) {
        calculationStore.setValue('opportunity', lead.evo_opportunityid);
        calculationStore.setFilter('selectOpportunity', opportunities =>
          opportunities.filter(x => x.opportunityid === lead.evo_opportunityid),
        );
      } else {
        calculationStore.setFilter('selectOpportunity', () => []);
        calculationStore.setValue('opportunity', null);
      }

      if (lead?.leadid) {
        CrmService.getCRMOptions<'quotes', IQuote>({
          query: quotesByLeadQuery,
          variables: {
            leadid: lead?.leadid,
          },
        }).then(({ quotes }) => {
          if (quotes && quotes.length > 0) {
            calculationStore.setOptions('selectQuote', quotes);
            calculationStore.setValue('quote', null);
          } else {
            calculationStore.setOptions('selectQuote', []);
            calculationStore.setValue('quote', null);
          }
        });
      } else {
        calculationStore.setOptions('selectQuote', []);
        calculationStore.setValue('quote', null);
      }

      fillIndAgent.call(calculationStore, lead);
      fillCalcDoubleAgent.call(calculationStore, lead);
      fillCalcBroker.call(calculationStore, lead);
      fillFinDepartment.call(calculationStore, lead);
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { lead, opportunity } = calculationStore.values;
      return { leadid: lead, opportunityid: opportunity };
    },
    effect: ({ leadid, opportunityid }) => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }
      if (opportunityid) {
        const opportunity = calculationStore.getOption('selectOpportunity', {
          opportunityid,
        });
        if (opportunity) {
          if (opportunity.evo_client_riskid) {
            calculationStore.setValue(
              'clientRisk',
              opportunity.evo_client_riskid,
            );
          } else {
            if (opportunity.parentaccountid)
              CrmService.getCRMEntities<'account', IAccount>({
                query: gql`
                  query clientRisk_1($accountid: Uuid!) {
                    account(accountid: $accountid) {
                      evo_client_riskid
                    }
                  }
                `,
                variables: { accountid: opportunity.parentaccountid },
              }).then(({ account }) => {
                if (account?.evo_client_riskid)
                  calculationStore.setValue(
                    'clientRisk',
                    account.evo_client_riskid,
                  );
              });
          }
        }
      } else if (leadid && !opportunityid) {
        const lead = calculationStore.getOption('selectLead', {
          leadid,
        });
        if (lead && lead.customerid) {
          CrmService.getCRMEntities<'account', IAccount>({
            query: gql`
              query clientRisk_2($customerid: Uuid!) {
                account(accountid: $customerid) {
                  evo_client_riskid
                }
              }
            `,
            variables: { customerid: lead.customerid },
          }).then(({ account }) => {
            if (account?.evo_client_riskid)
              calculationStore.setValue(
                'clientRisk',
                account.evo_client_riskid,
              );
          });
        }
      } else {
        calculationStore.setValue('clientRisk', null);
      }
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { indAgent } = calculationStore.values;
      return indAgent;
    },
    effect: indAgentId => {
      if (!indAgentId) {
        calculationStore.setValue('indAgentRewardCondition', null);
        calculationStore.setStatus(
          'selectIndAgentRewardCondition',
          ElementStatus.Disabled,
        );
      } else {
        calculationStore.setValue('indAgentRewardCondition', null);
        calculationStore.setStatus(
          'selectIndAgentRewardCondition',
          ElementStatus.Default,
        );

        if (indAgentId && !calculationProcess.hasProcess(Process.LoadKp))
          CrmService.getCRMOptions<
            'evo_reward_conditions',
            IEvoRewardCondition
          >({
            query: gql`
              query selectIndAgentRewardCondition(
                $statecode: Int
                $currentDate: DateTime
                $evo_agent_accountid: Uuid
                $evo_agency_agreementid_param: GuidParamInput
              ) {
                evo_reward_conditions(
                  evo_agent_accountid: $evo_agent_accountid
                  evo_datefrom_param: { lte: $currentDate }
                  evo_dateto_param: { gte: $currentDate }
                  statecode: $statecode
                  evo_agency_agreementid_param: $evo_agency_agreementid_param
                ) {
                  evo_reward_conditionid
                  evo_name
                  evo_double_agent_accountid
                  evo_reward_summ
                  evo_reduce_reward
                  evo_agency_agreementid
                  evo_agency_agreementidData {
                    evo_reward_without_other_agent
                    evo_required_reward
                    evo_leasingobject_price
                  }
                  evo_min_reward_summ
                  evo_calc_reward_rules
                }
              }
            `,
            variables: {
              evo_agent_accountid: indAgentId,
              currentDate: currentISODate,
              statecode: 0,
              evo_agency_agreementid_param: { has: true },
            },
          }).then(({ evo_reward_conditions }) => {
            if (evo_reward_conditions)
              calculationStore.setOptions(
                'selectIndAgentRewardCondition',
                evo_reward_conditions,
              );
          });
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { calcDoubleAgent } = calculationStore.values;
      return calcDoubleAgent;
    },
    effect: doubleAgentId => {
      if (!doubleAgentId) {
        calculationStore.setValue('calcDoubleAgentRewardCondition', null);
        calculationStore.setStatus(
          'selectCalcDoubleAgentRewardCondition',
          ElementStatus.Disabled,
        );
      } else {
        calculationStore.setValue('calcDoubleAgentRewardCondition', null);
        calculationStore.setStatus(
          'selectCalcDoubleAgentRewardCondition',
          ElementStatus.Default,
        );

        if (doubleAgentId && !calculationProcess.hasProcess(Process.LoadKp))
          CrmService.getCRMOptions<
            'evo_reward_conditions',
            IEvoRewardCondition
          >({
            query: gql`
              query selectCalcDoubleAgentRewardCondition(
                $statecode: Int
                $currentDate: DateTime
                $evo_agent_accountid: Uuid
                $evo_agency_agreementid_param: GuidParamInput
              ) {
                evo_reward_conditions(
                  evo_agent_accountid: $evo_agent_accountid
                  evo_datefrom_param: { lte: $currentDate }
                  evo_dateto_param: { gte: $currentDate }
                  statecode: $statecode
                  evo_agency_agreementid_param: $evo_agency_agreementid_param
                ) {
                  evo_reward_conditionid
                  evo_name
                  evo_reward_summ
                  evo_reduce_reward
                  evo_agency_agreementid
                  evo_agency_agreementidData {
                    evo_reward_without_other_agent
                    evo_required_reward
                    evo_leasingobject_price
                  }
                  evo_min_reward_summ
                  evo_calc_reward_rules
                }
              }
            `,
            variables: {
              evo_agent_accountid: doubleAgentId,
              currentDate: currentISODate,
              statecode: 0,
              evo_agency_agreementid_param: { has: true },
            },
          }).then(({ evo_reward_conditions }) => {
            if (evo_reward_conditions)
              calculationStore.setOptions(
                'selectCalcDoubleAgentRewardCondition',
                evo_reward_conditions,
              );
          });
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { calcFinDepartment } = calculationStore.values;
      return calcFinDepartment;
    },
    effect: calcFinDepartmentId => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }
      if (!calcFinDepartmentId) {
        calculationStore.setValue('finDepartmentRewardCondtion', null);
        calculationStore.setStatus(
          'selectFinDepartmentRewardCondtion',
          ElementStatus.Disabled,
        );
      } else {
        calculationStore.setValue('finDepartmentRewardCondtion', null);
        calculationStore.setStatus(
          'selectFinDepartmentRewardCondtion',
          ElementStatus.Default,
        );
        if (calcFinDepartmentId)
          CrmService.getCRMOptions<
            'evo_reward_conditions',
            IEvoRewardCondition
          >({
            query: gql`
              query selectFinDepartmentRewardCondtion(
                $statecode: Int
                $currentDate: DateTime
                $evo_agent_accountid: Uuid
                $evo_agency_agreementid_param: GuidParamInput
              ) {
                evo_reward_conditions(
                  evo_agent_accountid: $evo_agent_accountid
                  evo_datefrom_param: { lte: $currentDate }
                  evo_dateto_param: { gte: $currentDate }
                  statecode: $statecode
                  evo_agency_agreementid_param: $evo_agency_agreementid_param
                ) {
                  evo_reward_conditionid
                  evo_name
                  evo_reward_summ
                  evo_reduce_reward
                  evo_agency_agreementid
                  evo_agency_agreementidData {
                    evo_reward_without_other_agent
                    evo_required_reward
                    evo_leasingobject_price
                  }
                  evo_min_reward_summ
                  evo_calc_reward_rules
                }
              }
            `,
            variables: {
              evo_agent_accountid: calcFinDepartmentId,
              currentDate: currentISODate,
              statecode: 0,
              evo_agency_agreementid_param: { has: true },
            },
          }).then(({ evo_reward_conditions }) => {
            if (evo_reward_conditions)
              calculationStore.setOptions(
                'selectFinDepartmentRewardCondtion',
                evo_reward_conditions,
              );
          });
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { calcBroker } = calculationStore.values;
      return calcBroker;
    },
    effect: calcBrokerId => {
      if (!calcBrokerId) {
        calculationStore.setValue('calcBrokerRewardCondition', null);
        calculationStore.setStatus(
          'selectCalcBrokerRewardCondition',
          ElementStatus.Disabled,
        );
      } else {
        calculationStore.setValue('calcBrokerRewardCondition', null);
        calculationStore.setStatus(
          'selectCalcBrokerRewardCondition',
          ElementStatus.Default,
        );

        if (calcBrokerId && !calculationProcess.hasProcess(Process.LoadKp))
          CrmService.getCRMOptions<
            'evo_reward_conditions',
            IEvoRewardCondition
          >({
            query: gql`
              query selectCalcBrokerRewardCondition(
                $statecode: Int
                $currentDate: DateTime
                $evo_agent_accountid: Uuid
                $evo_agency_agreementid_param: GuidParamInput
              ) {
                evo_reward_conditions(
                  evo_agent_accountid: $evo_agent_accountid
                  evo_datefrom_param: { lte: $currentDate }
                  evo_dateto_param: { gte: $currentDate }
                  statecode: $statecode
                  evo_agency_agreementid_param: $evo_agency_agreementid_param
                ) {
                  evo_reward_conditionid
                  evo_name
                  evo_reward_summ
                  evo_reduce_reward
                  evo_agency_agreementid
                  evo_agency_agreementidData {
                    evo_reward_without_other_agent
                    evo_required_reward
                    evo_leasingobject_price
                  }
                  evo_min_reward_summ
                  evo_calc_reward_rules
                }
              }
            `,
            variables: {
              evo_agent_accountid: calcBrokerId,
              currentDate: currentISODate,
              statecode: 0,
              evo_agency_agreementid_param: { has: true },
            },
          }).then(({ evo_reward_conditions }) => {
            if (evo_reward_conditions)
              calculationStore.setOptions(
                'selectCalcBrokerRewardCondition',
                evo_reward_conditions,
              );
          });
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { dealer } = calculationStore.values;
      return dealer;
    },
    effect: dealerId => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }
      if (dealerId) {
        const dealer = calculationStore.getOption('selectDealer', {
          accountid: dealerId,
        });
        if (dealer && !dealer.evo_return_leasing_dealer) {
          CrmService.getCRMOptions<'salon_providers', ISalonProvider>({
            query: gql`
              query selectDealerPerson(
                $statecode: Int
                $salonaccountid: Uuid!
              ) {
                salon_providers(
                  statecode: $statecode
                  salonaccountid: $salonaccountid
                ) {
                  accountid
                  name
                  evo_broker_accountid
                  evo_kpp
                  evo_inn
                }
              }
            `,
            variables: {
              salonaccountid: dealerId,
              statecode: 0,
            },
          }).then(({ salon_providers }) => {
            if (salon_providers && salon_providers.length > 0) {
              calculationStore.setOptions(
                'selectDealerPerson',
                salon_providers,
              );
              calculationStore.setValue(
                'dealerPerson',
                salon_providers[0].accountid,
              );
              calculationStore.setStatus(
                'selectDealerPerson',
                ElementStatus.Default,
              );
            }
          });
        }
      }

      calculationStore.setOptions('selectDealerPerson', []);
      calculationStore.setValue('dealerPerson', null);
      calculationStore.setStatus('selectDealerPerson', ElementStatus.Disabled);
    },
    options: {
      fireImmediately: true,
    },
  }),

  //TODO: maybe refactor
  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { dealerPerson } = calculationStore.values;
      return dealerPerson;
    },
    effect: dealerPersonId => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }
      calculationStore.setOptions('selectDealerBroker', []);
      calculationStore.setValue('dealerBroker', null);
      calculationStore.setStatus('selectDealerBroker', ElementStatus.Disabled);
      if (dealerPersonId) {
        const dealerPerson = calculationStore.getOption('selectDealerPerson', {
          accountid: dealerPersonId,
        });
        if (dealerPerson && dealerPerson.evo_broker_accountid) {
          CrmService.getCRMOptions<'accountOptions', IAccount>({
            query: gql`
              query selectDealerBroker($accountid: Uuid!) {
                accountOptions: account(accountid: $accountid) {
                  accountid
                  name
                }
              }
            `,
            variables: {
              accountid: dealerPerson.evo_broker_accountid,
            },
          }).then(({ accountOptions }) => {
            if (accountOptions && accountOptions.length > 0) {
              calculationStore.setOptions('selectDealerBroker', accountOptions);
              calculationStore.setValue(
                'dealerBroker',
                accountOptions[0].accountid,
              );
              calculationStore.setStatus(
                'selectDealerBroker',
                ElementStatus.Default,
              );
            }
          });
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { dealerBroker } = calculationStore.values;
      return dealerBroker;
    },
    effect: dealerBrokerId => {
      if (dealerBrokerId) {
        const dealerBroker = calculationStore.getOption('selectDealerBroker', {
          accountid: dealerBrokerId,
        });
        if (dealerBroker) {
          calculationStore.setStatus(
            'selectDealerBrokerRewardCondition',
            ElementStatus.Default,
          );

          if (!calculationProcess.hasProcess(Process.LoadKp))
            CrmService.getCRMOptions<
              'evo_reward_conditions',
              IEvoRewardCondition
            >({
              query: gql`
                query selectDealerBrokerRewardCondition(
                  $statecode: Int
                  $currentDate: DateTime
                  $evo_agent_accountid: Uuid
                  $evo_agency_agreementid_param: GuidParamInput
                ) {
                  evo_reward_conditions(
                    evo_agent_accountid: $evo_agent_accountid
                    evo_datefrom_param: { lte: $currentDate }
                    evo_dateto_param: { gte: $currentDate }
                    statecode: $statecode
                    evo_agency_agreementid_param: $evo_agency_agreementid_param
                  ) {
                    evo_reward_conditionid
                    evo_name
                    evo_reward_summ
                    evo_reduce_reward
                    evo_agency_agreementid
                    evo_agency_agreementidData {
                      evo_reward_without_other_agent
                      evo_required_reward
                      evo_leasingobject_price
                    }
                    evo_min_reward_summ
                    evo_calc_reward_rules
                  }
                }
              `,
              variables: {
                evo_agent_accountid: dealerBrokerId,
                currentDate: currentISODate,
                statecode: 0,
                evo_agency_agreementid_param: { has: true },
              },
            }).then(({ evo_reward_conditions }) => {
              if (evo_reward_conditions)
                calculationStore.setOptions(
                  'selectDealerBrokerRewardCondition',
                  evo_reward_conditions,
                );
            });
        }
      } else {
        calculationStore.setValue('dealerBrokerRewardCondition', null);
        calculationStore.setStatus(
          'selectDealerBrokerRewardCondition',
          ElementStatus.Disabled,
        );
        calculationStore.setOptions('selectDealerBrokerRewardCondition', []);
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { dealerBroker, dealerPerson } = calculationStore.values;
      return [dealerBroker, dealerPerson];
    },
    effect: ([dealerBrokerId, dealerPersonId]) => {
      if (dealerPersonId && !dealerBrokerId) {
        calculationStore.setStatus(
          'selectDealerRewardCondition',
          ElementStatus.Default,
        );
        if (!calculationProcess.hasProcess(Process.LoadKp))
          CrmService.getCRMOptions<
            'evo_reward_conditions',
            IEvoRewardCondition
          >({
            query: gql`
              query selectDealerRewardCondition(
                $statecode: Int
                $currentDate: DateTime
                $evo_agent_accountid: Uuid
                $evo_agency_agreementid_param: GuidParamInput
              ) {
                evo_reward_conditions(
                  evo_agent_accountid: $evo_agent_accountid
                  evo_datefrom_param: { lte: $currentDate }
                  evo_dateto_param: { gte: $currentDate }
                  statecode: $statecode
                  evo_agency_agreementid_param: $evo_agency_agreementid_param
                ) {
                  evo_reward_conditionid
                  evo_name
                  evo_reward_summ
                  evo_reduce_reward
                  evo_agency_agreementid
                  evo_agency_agreementidData {
                    evo_reward_without_other_agent
                    evo_required_reward
                    evo_leasingobject_price
                  }
                  evo_min_reward_summ
                  evo_calc_reward_rules
                }
              }
            `,
            variables: {
              evo_agent_accountid: dealerPersonId,
              currentDate: currentISODate,
              statecode: 0,
              evo_agency_agreementid_param: { has: true },
            },
          }).then(({ evo_reward_conditions }) => {
            if (evo_reward_conditions)
              calculationStore.setOptions(
                'selectDealerRewardCondition',
                evo_reward_conditions,
              );

            calculationStore.setValue('dealerRewardCondition', null);
          });
      } else {
        calculationStore.setValue('dealerRewardCondition', null);
        calculationStore.setStatus(
          'selectDealerRewardCondition',
          ElementStatus.Disabled,
        );
        calculationStore.setOptions('selectDealerRewardCondition', []);
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

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

      calculationStore.setOptions('selectModel', []);
      calculationStore.setValue('model', null);

      if (brandId) {
        CrmService.getCRMOptions<'evo_models', IEvoModel>({
          query: gql`
            query selectModel($statecode: Int, $evo_brandid: Uuid) {
              evo_models(statecode: $statecode, evo_brandid: $evo_brandid) {
                evo_id
                evo_name
                evo_modelid
                evo_leasingobject_risk
                evo_importer_reward_perc
                evo_importer_reward_rub
                evo_impairment_groupid
                evo_vehicle_type
                evo_gps
                evo_vehicle_body_typeidData {
                  evo_id_elt
                }
                evo_running_gear
              }
            }
          `,
          variables: {
            statecode: 0,
            evo_brandid: brandId,
          },
        }).then(({ evo_models }) => {
          if (evo_models) {
            calculationStore.setOptions('selectModel', evo_models);
            calculationStore.setValue('model', null);
          }
        });
      }
    },
    options: { fireImmediately: true },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { model } = calculationStore.values;
      return model;
    },
    effect: modelId => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }
      calculationStore.setStatus('selectConfiguration', ElementStatus.Disabled);
      calculationStore.setOptions('selectConfiguration', []);
      calculationStore.setValue('configuration', null);

      if (modelId) {
        const model = calculationStore.getOptions('selectModel', {
          evo_modelid: modelId,
        });
        if (model) {
          CrmService.getCRMOptions<'evo_equipments', IEvoEquipment>({
            query: gql`
              query selectConfiguration($statecode: Int, $evo_modelid: Uuid) {
                evo_equipments(
                  statecode: $statecode
                  evo_modelid: $evo_modelid
                ) {
                  evo_equipmentid
                  evo_name
                  evo_impairment_groupid
                  evo_leasingobject_risk
                  evo_start_production_year
                }
              }
            `,
            variables: {
              statecode: 0,
              evo_modelid: modelId,
            },
          }).then(({ evo_equipments }) => {
            if (evo_equipments) {
              calculationStore.setStatus(
                'selectConfiguration',
                ElementStatus.Default,
              );
              calculationStore.setOptions(
                'selectConfiguration',
                evo_equipments,
              );
            }
          });
        }
      }
    },
    options: {
      fireImmediately: true,
    },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      const { GPSBrand } = calculationStore.values;
      return GPSBrand;
    },
    effect: GPSBrandId => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }
      calculationStore.setStatus('selectGPSModel', ElementStatus.Disabled);
      calculationStore.setOptions('selectGPSModel', []);
      calculationStore.setValue('GPSModel', null);

      if (GPSBrandId) {
        const gpsBrand = calculationStore.getOption('selectGPSBrand', {
          evo_gps_brandid: GPSBrandId,
        });
        if (gpsBrand) {
          CrmService.getCRMOptions<'evo_gps_models', IEvoGPSModel>({
            query: gql`
              query selectGPSModel($statecode: Int, $evo_gps_brandid: Uuid) {
                evo_gps_models(
                  statecode: $statecode
                  evo_gps_brandid: $evo_gps_brandid
                ) {
                  evo_name
                  evo_gps_modelid
                  evo_moto
                }
              }
            `,
            variables: {
              statecode: 0,
              evo_gps_brandid: GPSBrandId,
            },
          }).then(({ evo_gps_models }) => {
            if (evo_gps_models) {
              calculationStore.setStatus(
                'selectGPSModel',
                ElementStatus.Default,
              );
              calculationStore.setOptions('selectGPSModel', evo_gps_models);
              calculationStore.setValue('GPSModel', null);
            }
          });
        }
      }
    },
    options: { fireImmediately: true },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      return calculationStore.getValue('regionRegistration');
    },
    effect: regionRegistrationId => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }
      // calculationStore.setStatus(
      //   'selectTownRegistration',
      //   ElementStatus.Disabled,
      // );
      calculationStore.setOptions('selectTownRegistration', []);
      calculationStore.setValue('townRegistration', null);

      if (regionRegistrationId) {
        const regionRegistration = calculationStore.getOption(
          'selectRegionRegistration',
          {
            evo_regionid: regionRegistrationId,
          },
        );
        if (regionRegistration) {
          CrmService.getCRMOptions<'evo_towns', IEvoTown>({
            query: gql`
              query selectTownRegistration(
                $statecode: Int
                $evo_regionid: Uuid
              ) {
                evo_towns(statecode: $statecode, evo_regionid: $evo_regionid) {
                  evo_name
                  evo_townid
                  evo_fias_id
                  evo_kladr_id
                  evo_businessunit_evolution
                }
              }
            `,
            variables: {
              statecode: 0,
              evo_regionid: regionRegistrationId,
            },
          }).then(({ evo_towns }) => {
            if (evo_towns) {
              // calculationStore.setStatus(
              //   'selectTownRegistration',
              //   ElementStatus.Default,
              // );
              calculationStore.setOptions('selectTownRegistration', evo_towns);
              // calculationStore.setValue('townRegistration', null);
            }
          });
        }
      }
    },
    options: { fireImmediately: true },
  }),

  (calculationStore, calculationProcess) => ({
    expression: () => {
      return calculationStore.getValue('legalClientRegion');
    },
    effect: legalClientRegionId => {
      if (calculationProcess.hasProcess(Process.LoadKp)) {
        return;
      }
      // calculationStore.setStatus(
      //   'selectLegalClientTown',
      //   ElementStatus.Disabled,
      // );
      calculationStore.setOptions('selectLegalClientTown', []);
      calculationStore.setValue('legalClientTown', null);

      if (legalClientRegionId) {
        const regionRegistration = calculationStore.getOption(
          'selectLegalClientRegion',
          {
            evo_regionid: legalClientRegionId,
          },
        );
        if (regionRegistration) {
          CrmService.getCRMOptions<'evo_towns', IEvoTown>({
            query: gql`
              query selectLegalClientTown(
                $statecode: Int
                $evo_regionid: Uuid
              ) {
                evo_towns(statecode: $statecode, evo_regionid: $evo_regionid) {
                  evo_name
                  evo_townid
                  evo_fias_id
                  evo_kladr_id
                }
              }
            `,
            variables: {
              statecode: 0,
              evo_regionid: legalClientRegionId,
            },
          }).then(({ evo_towns }) => {
            if (evo_towns) {
              // calculationStore.setStatus(
              //   'selectLegalClientTown',
              //   ElementStatus.Default,
              // );
              calculationStore.setOptions('selectLegalClientTown', evo_towns);
              // calculationStore.setValue('legalClientTown', null);
            }
          });
        }
      }
    },
    options: { fireImmediately: true },
  }),
] as IReactionEffect[];
