/* eslint-disable @typescript-eslint/naming-convention */
import { gql } from '@apollo/client';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import type * as CRMTypes from 'gql/crm.types';
import { reaction } from 'mobx';
import type { ReactionsContext } from 'process/types';
import { sift } from 'radash';
import { normalizeOptions } from 'tools/entity';
import * as createReactions from '../lib/create-reactions';
import * as query from '../lib/query';

dayjs.extend(utc);

export function commonReactions({ store, apolloClient }: ReactionsContext) {
  const { $calculation, $process } = store;

  /**
   * Заполняем selectDealerPerson
   * На изменение Салон приобретения формируем список в поле ЮЛ поставщика - записи Контрагент,
   * у которых статус = активный И Поставщик = Да И Тип поставщика = Юридическое лицо
   * И связаны с карточкой Контрагент из поля "Салон приобретения" по связи Салон-ЮЛ
   */

  const QUERY_GET_DEALER_PERSON = gql`
    query GetDealerPerson($dealerId: Uuid!) {
      salon_providers(statecode: 0, salonaccountid: $dealerId) {
        label: name
        value: accountid
        evo_inn
        evo_kpp
      }
    }
  `;

  reaction(
    () => $calculation.element('selectDealer').getValue(),
    async (dealerId) => {
      if (!dealerId) {
        $calculation.element('selectDealerPerson').reset();
        $calculation.element('selectDealerBroker').reset();

        return;
      }

      const {
        data: { salon_providers },
      } = await apolloClient.query<
        CRMTypes.GetDealerPersonQuery,
        CRMTypes.GetDealerPersonQueryVariables
      >({
        query: QUERY_GET_DEALER_PERSON,
        variables: {
          dealerId,
        },
      });

      if (salon_providers && salon_providers.length > 0) {
        $calculation.element('selectDealerPerson').setOptions(
          normalizeOptions(
            salon_providers.map((dp) => ({
              ...dp,
              label: `${dp?.label} ${sift([dp?.evo_inn, dp?.evo_kpp]).join(' | ')}`,
            }))
          )
        );

        const value = salon_providers.at(0)?.value;
        if (!$process.has('LoadKP') && value) {
          $calculation.element('selectDealerPerson').setValue(value);
        }
      } else {
        $calculation.element('selectDealerPerson').reset();
      }
    }
  );

  /**
   * Заполняем selectDealerBroker
   */

  const QUERY_GET_BROKER_ACCOUNTID_FROM_DEALER = gql`
    query GetBrokerAccountIdFromDealer($dealerId: Uuid!) {
      dealer: account(accountid: $dealerId) {
        evo_broker_accountid
      }
    }
  `;

  reaction(
    () => $calculation.element('selectDealerPerson').getValue(),
    async (dealerPersonId) => {
      if (!dealerPersonId) {
        return;
      }

      const {
        data: { dealer },
      } = await apolloClient.query<
        CRMTypes.GetBrokerAccountIdFromDealerQuery,
        CRMTypes.GetBrokerAccountIdFromDealerQueryVariables
      >({
        query: QUERY_GET_BROKER_ACCOUNTID_FROM_DEALER,
        variables: {
          dealerId: dealerPersonId,
        },
      });

      if (dealer?.evo_broker_accountid) {
        const {
          data: { agent: dealerBroker },
        } = await apolloClient.query<CRMTypes.GetAgentQuery, CRMTypes.GetAgentQueryVariables>({
          query: query.QUERY_GET_AGENT,
          variables: {
            agentid: dealer?.evo_broker_accountid,
          },
        });

        if (dealerBroker) {
          $calculation.element('selectDealerBroker').setOptions(normalizeOptions([dealerBroker]));

          if (!$process.has('LoadKP')) {
            $calculation.element('selectDealerBroker').setValue(dealerBroker.value);
          }
        }
      } else {
        $calculation.element('selectDealerBroker').reset();
      }
    }
  );

  // Заполняем selectDealerRewardCondition
  createReactions.fillAgentRewardReaction(store, apolloClient, {
    agentField: 'selectDealerPerson',
    rewardConditionField: 'selectDealerRewardCondition',
  });

  // Заполняем tbxDealerRewardSumm
  createReactions.fillAgentRewardSummReaction(store, apolloClient, {
    rewardConditionField: 'selectDealerRewardCondition',
    rewardSummField: 'tbxDealerRewardSumm',
  });

  // Заполняем selectDealerBrokerRewardCondition
  createReactions.fillAgentRewardReaction(store, apolloClient, {
    agentField: 'selectDealerBroker',
    rewardConditionField: 'selectDealerBrokerRewardCondition',
  });

  // Заполняем tbxDealerBrokerRewardSumm
  createReactions.fillAgentRewardSummReaction(store, apolloClient, {
    rewardConditionField: 'selectDealerBrokerRewardCondition',
    rewardSummField: 'tbxDealerBrokerRewardSumm',
  });

  reaction(
    () => $calculation.element('selectDealerRewardCondition').getValue(),
    (dealerRewardConditionId) => {
      if (dealerRewardConditionId) {
        $calculation.element('selectDealerBroker').resetValue();
      }
    }
  );

  reaction(
    () => $calculation.element('selectDealerBrokerRewardCondition').getValue(),
    (dealerBrokerRewardConditionId) => {
      if (dealerBrokerRewardConditionId) {
        $calculation.element('selectDealerPerson').resetValue();
      }
    }
  );
}

export function validationReactions({ store, apolloClient }: ReactionsContext) {
  createReactions.validateAgentRewardSumm(store, apolloClient, {
    rewardConditionField: 'selectDealerRewardCondition',
    rewardSummField: 'tbxDealerRewardSumm',
  });

  createReactions.validateAgentRewardSumm(store, apolloClient, {
    rewardConditionField: 'selectDealerBrokerRewardCondition',
    rewardSummField: 'tbxDealerBrokerRewardSumm',
  });
}
