import dayjs from 'dayjs';
import { request } from '@/service/request';
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, T[keyof T]>[];
}

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

/**
 * 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
  };
}

/**
 * 统一导出方法
 * @param url
 * @param params
 */
export function commonExport(url: string, params: any, filename: string) {
  if (!filename) {
    window.$message?.error('文件未命名');
    return false;
  }
  const newParams = { ...params };
  if (newParams.createTime) {
    newParams.startTime = newParams.createTime[0];
    newParams.endTime = newParams.createTime[1];
    delete newParams.createTime;
  }

  return new Promise((resolve, reject) => {
    request({
      url,
      method: 'get',
      params: newParams,
      responseType: 'blob'
    })
      .then(res => {
        const blob = new Blob([res.data as unknown as BlobPart], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const exportUrl = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = exportUrl;
        const nameWithoutExt = filename.substring(0, filename.lastIndexOf('.'));
        const ext = filename.substring(filename.lastIndexOf('.'));
        const time = dayjs().format('YYYY-MM-DD HH:mm:ss');
        link.download = `${nameWithoutExt}_${time}${ext}`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        window.$message?.success('导出成功');
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}
/** 判断是否为空 */
export function isNull(value: any) {
  return value === undefined || value === null || value === '';
}
/** 判断是否为空 */
export function isNotNull(value: any) {
  return value !== undefined && value !== null && value !== '';
}
