import { $t } from '@/locales';

/**
 * Transform record to option
 *
 * @example
 *   ```ts
 *   const record = {
 *     key1: 'label1',
 *     key2: 'label2'
 *   };
 *   const options = transformRecordToOption(record);
 *   // [
 *   //   { value: 'key1', label: 'label1' },
 *   //   { value: 'key2', label: 'label2' }
 *   // ]
 *   ```;
 *
 * @param record
 */
export function transformRecordToOption<T extends Record<string, string>>(record: T) {
  return Object.entries(record).map(([value, label]) => ({
    value,
    label
  })) as CommonType.Option<keyof T>[];
}

/**
 * Translate options
 *
 * @param options
 */
export function translateOptions(options: CommonType.Option<string>[]) {
  return options.map(option => ({
    ...option,
    label: $t(option.label as App.I18n.I18nKey)
  }));
}

/**
 * Toggle html class
 *
 * @param className
 */
export function toggleHtmlClass(className: string) {
  function add() {
    document.documentElement.classList.add(className);
  }

  function remove() {
    document.documentElement.classList.remove(className);
  }

  return {
    add,
    remove
  };
}

/**
 * 返回多层嵌套数据中的某个值:比如imageProductList.0.productInfoList，返回imageProductList[0].productInfoList
 *
 * @param data
 * @param keyArr
 * @param index
 */
export function returnMapData(
  data: Record<string, any> | Array<Record<string, any>>,
  keyArr: string[],
  index: number = 0
): any {
  const comData = Array.isArray(data) ? data[Number(keyArr[index])] : data[keyArr[index]];
  if (index === keyArr.length - 1) {
    return comData;
  }
  return returnMapData(comData, keyArr, index + 1);
}
