import moment from 'moment';
import { Notify } from 'quasar';
import { error_msg } from '../boot/axios';

export function decimal(val, len) {
  if (val !== undefined) {
    return val.toLocaleString(undefined, {
      minimumFractionDigits: len,
      maximumFractionDigits: len,
    });
  }
  return '-';
}

export function date(val) {
  return moment(val).format('DD-MM-YYYY');
}

export const formatCodPedido = (COD_PEDIDO) => {
  if (!COD_PEDIDO) {
    return '~';
  }

  return COD_PEDIDO.substr(0, 3) + ' ' + COD_PEDIDO.substr(3, 3) + ' ' + COD_PEDIDO.substr(6, 50);
};

export const generateCsv = (data, fields, columnNames, filename) => {
  let csv = 'data:text/csv;charset=utf-8,';
  csv += '"' + columnNames.join('","') + '"\n';
  data.forEach((row) => {
    let csvrow = '';
    fields.forEach((col) => {
      csvrow += `"${row[col]}",`;
    });
    csv += csvrow.substr(0, csvrow.length - 1).replace(/[";]/g, '') + '\n';
  });
  const link = document.createElement('a');
  link.setAttribute('href', csv);
  link.setAttribute('download', filename.replace('.csv', '') + '.csv');
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

export function ff(type, value = 0) {
  if (type == '€' || type == '$') return formatPrice(value, type);
  else if (type == 'km') return formatKm(value);
  else if (type == '%') return formatPercent(value);
  else return value;
}
export function formatPrice(value, type) {
  if (type == '$') {
    let val = (value / 1).toFixed(2);
    return type + ' ' + val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  } else {
    let val = (value / 1).toFixed(2).replace('.', ',');
    return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.') + ' ' + type;
  }
}
export function formatKm(value) {
  return Math.round(value / 100) / 10 + ' Km';
}
export function formatPercent(value) {
  return (value / 1).toFixed(2) + ' %';
}

export function isValidIBANNumber(iban) {
  iban = iban.replace(/[^a-zA-Z0-9]/g, '').toUpperCase(); // eliminar caracteres no alfanuméricos y convertir a mayúsculas

  // Verificar longitud y formato del IBAN
  if (iban.length !== 24 || !iban.match(/^[A-Z]{2}\d{22}$/)) {
    return false;
  }

  // Reordenar los caracteres del IBAN
  const reordenado = iban.slice(4) + iban.slice(0, 4);

  // Convertir letras a números según el estándar ISO 13616
  const letraAValor = (letra) => letra.charCodeAt(0) - 55;
  const numeros = reordenado
    .split('')
    .map((caracter) => {
      return isNaN(caracter) ? letraAValor(caracter) : caracter;
    })
    .join('');

  // Verificar que el IBAN es válido usando el módulo 97
  let resto = 0;
  for (let i = 0; i < numeros.length; i += 7) {
    resto = parseInt(resto + numeros.slice(i, i + 7), 10) % 97;
  }

  return resto === 1;
}

export const formatDate = (date, time = false) => {
  if (!date) {
    return '-';
  }
  return moment(date).format(`DD/MM/YYYY${time ? ' HH:mm' : ''}`);
};

export function articulosProps() {
  return [
    { clave: '|GB_CLARO_DRIVE|', label: 'Espacio en GB de claro drive', valor: '' },
    { clave: '|MONTO_INCREMENTO_PAQUETE|', label: 'Monto de incremento de paquete', valor: '' },
    { clave: '|MONTO_ANTES_12_MESES|', label: 'Monto antes de los 12 meses', valor: '' },
    { clave: '|MONTO_LUEGO_12_MESES|', label: 'Monto luego de los 12 meses', valor: '' },
    { clave: '|SERVICIO_CONTRATADA|', label: 'Servicio contratado', valor: '' },
    { clave: '|COSTO_SERVICIO|', label: 'Importe del servicio contratado', valor: '' },
    { clave: '|RENTA_ACCESS_POIN|', label: 'Importe por access point', valor: '' },
    { clave: '|MESES_ACCESS_POIN|', label: 'Meses de acces point', valor: '' },
    { clave: '|DIAS_DISPONIBILIDAD|', label: 'Disponibilidad de días', valor: '' },
    { clave: '|EN_OTRA_COMPANIA|', label: 'Cliente en otra compañia', valor: '' },
    { clave: '|TIPO_LINEA|', label: 'Tipo de linea', valor: '' },
    { clave: '|VELOCIDAD|', label: 'Velocidad', valor: '' },
    {
      clave: '|GI_NOMBRE|',
      label: 'Nombre de gasto de instalación',
      valor: '',
    },
    {
      clave: '|GI_TARIFA|',
      label: 'Tarifa de gasto de instalación',
      valor: '',
    },
    {
      clave: '|GI_TARIFA_MES|',
      label: 'Tarifa mensual de instalación',
      valor: '',
    },
  ];
}

export const notifyError = (err, customMessage?: string) => {
  if (typeof err === 'string' && !customMessage) {
    customMessage = err;
    err = null;
  }
  Notify.create({
    message: error_msg(err, customMessage),
    icon: 'warning',
    color: 'negative',
  });
};

export const notifySuccess = (message: string) => {
  Notify.create({
    message,
    color: 'positive',
    icon: 'check',
  });
};
