import { ICalculationStore } from 'core/types/Calculation/Store';
import { Process } from 'core/types/Calculation/Store/process';
import { isEmpty } from 'lodash';
import initialOptions from '../config/initialOptions';
import initialValues from '../config/initialValues';
import { composeRequests } from './requests';

export default async function (this: ICalculationStore) {
  const { calculationProcess } = this.stores;
  calculationProcess.addProcess(Process.Init);

  const {
    ownerOptionsRequest,
    mainOptionsRequest,
    staticDataRequest,
    systemUserRequest,
    insuranceRequest,
  } = composeRequests();

  const { systemuser } = await systemUserRequest;
  const staticEntities = await staticDataRequest;
  this.applyStaticData(
    Object.assign({ systemuser: [systemuser] }, staticEntities),
  );

  const ownerOptions = await ownerOptionsRequest;

  const mainOptions = await mainOptionsRequest;
  let selectProduct = mainOptions?.selectProduct?.filter(
    x =>
      isEmpty(x.systemusers) ||
      x?.systemusers?.some(u => u?.systemuserid === systemuser?.systemuserid),
  );
  this.applyOptions(
    Object.assign(initialOptions, ownerOptions, mainOptions, { selectProduct }),
  );

  const insuranceData = await insuranceRequest;
  this.setTableColumns('tableInsurance')({
    options: insuranceData,
  });

  this.setValues(initialValues, true);

  const supplierCurrency = this.options.selectSupplierCurrency?.find(
    x => x.isocurrencycode === 'RUB',
  );
  this.setValue('supplierCurrency', supplierCurrency?.transactioncurrencyid);

  const evo_sot_coefficient_type =
    staticEntities?.evo_sot_coefficient_type?.find(
      x => x.evo_id === 'BONUS_LEASING',
    );

  const evo_coefficient_bonuses = staticEntities?.evo_coefficient?.filter(
    x =>
      x.evo_job_titleid === systemuser?.evo_job_titleid &&
      x.evo_sot_coefficient_typeid ===
        evo_sot_coefficient_type?.evo_sot_coefficient_typeid,
  );

  const max_bonus = Math.max(
    ...evo_coefficient_bonuses.map(x => x.evo_sot_coefficient || 0),
  );

  this.setValue('saleBonus', max_bonus * 100);

  calculationProcess.deleteProcess(Process.Init);
}
