import { message } from 'antd';
import { AxiosError } from 'axios';
import { openNotification } from 'client/Elements/Notification';
import UserStore from 'client/stores/UserStore';
import { CRM_PROXY_URL } from 'core/constants/urls';
import CrmService from 'core/services/CrmService';
import { quotesByLeadQuery } from 'core/services/CrmService/graphql/query/quote';
import { IQuote } from 'core/services/CrmService/types/entities';
import { ICalculationStore } from 'core/types/Calculation/Store';
import { toJS } from 'mobx';
import { insKaskoPriceLeasePeriod } from '../computed';
import calculate from './calculate';

async function composeRequest(this: ICalculationStore) {
  const calculationRes = await calculate.call(this);

  if (!calculationRes) return;

  const insurance = this.tables.tableInsurance.rows.map(insuranceRow => {
    const values = Object.keys(insuranceRow).reduce((row, propName) => {
      row[propName] = toJS(insuranceRow[propName].value);
      return row;
    }, {});

    return {
      ...values,
      key: insuranceRow.key,
    };
  }, {});

  const elt = Object.assign(
    {},
    ...['osago', 'kasko'].map(insType => ({
      [insType]: toJS(this.stores.ELTStore[insType].getCompany()),
    })),
  );

  const finGAP = this.stores.$finGAP.getSelectedRisks();

  const insKaskoPriceLeasePeriodValue = insKaskoPriceLeasePeriod.call(this);
  //@ts-ignore
  const importProgramSum = this.importProgramSum();
  const calculationValues = Object.assign({}, toJS(this.values), {
    insKaskoPriceLeasePeriod: insKaskoPriceLeasePeriodValue,
    importProgramSum,
  });

  const domainname = UserStore.getDomainName();
  const payload = {
    domainName: domainname,
    calculation: {
      calculationValues,
      ...calculationRes,
    },
    insurance,
    finGAP,
    elt,
  };
  return payload;
}

export default async function (this: ICalculationStore) {
  try {
    this.stores.calculationUrls.setUrl({ name: 'kpUrl', url: undefined });
    const payload = await composeRequest.call(this);
    if (!payload) return;

    const { data: newKP } = await CrmService.createKP(payload);
    message.success({
      content: 'КП создано! ' + newKP?.evo_quotename,
    });
    if (newKP?.offerprintformapi)
      this.stores.calculationUrls.setUrl({
        name: 'kpUrl',
        url: String.prototype.concat(CRM_PROXY_URL, newKP?.offerprintformapi),
      });

    this.setValue('recalcWithRevision', false);

    const leadid = this.getValue('lead');
    CrmService.getCRMOptions<'quotes', IQuote>({
      query: quotesByLeadQuery,
      variables: {
        leadid,
      },
      fetchPolicy: 'network-only',
    }).then(({ quotes }) => {
      if (!quotes || quotes?.length === 0) throw new Error();
      this.setOptions('selectQuote', quotes);
    });
  } catch (err) {
    openNotification({
      type: 'error',
      message: 'Ошибка во время создания КП!',
    });

    const { response } = err as AxiosError;
    const error = response?.data || err;
    throw JSON.stringify(error);
  }
}
