import { CRMEntity } from 'core/services/CrmService/types/entities';
import { ICalculationStore } from 'core/types/Calculation/Store';
import { pick } from 'lodash';
import { sources } from './requests';

const mapInsType = {
  kasko: 100000000,
  osago: 100000001,
};

export const map_evo_id_elt_FieldName = {
  kasko: (calculationStore: ICalculationStore) => {
    const leaseObjectType = calculationStore.getOption('selectLeaseObjectType');
    if (
      leaseObjectType?.evo_id &&
      ['6', '9', '10'].includes(leaseObjectType?.evo_id)
    ) {
      return 'evo_id_elt_smr';
    }
    return 'evo_id_elt';
  },
  osago: (_: ICalculationStore) => 'evo_id_elt_osago',
};

export const initFields = [
  'evo_id_elt_osago',
  'evo_id_elt_smr',
  'evo_id_elt',
  'name',
  'accountid',
  'evo_legal_region_calc',
];

export function initIns(this: ICalculationStore, insType) {
  const insuranceCompanies = this.getTableOptions(
    'tableInsurance',
    'insuranceCompany',
  );
  if (insuranceCompanies === undefined) {
    return;
  }
  const { ELTStore } = this.stores;
  const list: CRMEntity[] = [];
  const evo_id_elt_fieldName = map_evo_id_elt_FieldName[insType](this);
  insuranceCompanies.forEach(company => {
    if (
      company &&
      company[evo_id_elt_fieldName] &&
      company?.evo_type_ins_policy?.includes(mapInsType[insType])
    ) {
      const companyData = pick(company, initFields, '');
      list.push(companyData);
    }
  });
  ELTStore[insType].list.replace(list);
}

export function resetIns(this: ICalculationStore, insType) {
  sources[insType] && sources[insType].cancel();

  const { ELTStore } = this.stores;

  const list: CRMEntity[] = [];
  ELTStore[insType].list.forEach(x => {
    const picked = pick(x, initFields, '');
    list.push(picked);
  });
  ELTStore[insType].reset(list);
}
