import { getKKFileViewURLFromMinioApi } from '@/api/data/data';
import { getFormConfigureApi } from '@/api/system/systemData';
import { ElMessage } from 'element-plus';
import * as XLSX from 'xlsx';
import { cloneDeep } from 'lodash-es';
import { CommonStore } from '@/stores/common';
import dayjs from 'dayjs';

const env = import.meta.env;

export const formatFileSize = (sizeInBytes: number): string => {
  if (sizeInBytes === undefined || sizeInBytes === null) {
    return '';
  }
  if (sizeInBytes < 0) {
    return '0 B';
  }
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let size = sizeInBytes;
  let unitIndex = 0;

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }

  return `${size.toFixed(2)} ${units[unitIndex]}`;
};

export const openTabReviewFile = async (fileId: number) => {
  const res: any = await getKKFileViewURLFromMinioApi({ fileId });
  if (res.code === 200) {
    window.open(env.VITE_API_FILE_PREVIEW_URL + '?' + res.data.encodeKKFileViewURL, '_blank');
    // return res.data.encodeKKFileViewURL;
  } else {
    ElMessage.error('获取文件预览地址失败!');
    return '';
  }
};

export class FileUtil {

  // 判断是否是图片
  static isPicture(fileUrl: string) {
    return (
      fileUrl.endsWith('.png') ||
      fileUrl.endsWith('.jpg') ||
      fileUrl.endsWith('.jpeg') ||
      fileUrl.endsWith('.webp') ||
      fileUrl.endsWith('.ico') ||
      fileUrl.endsWith('.bmp') ||
      fileUrl.endsWith('.svg') ||
      fileUrl.endsWith('.gif')
    );
  }
  /** 获取文件名后缀 */
  static getSuffixName(fileName: string) {
    const index = fileName.lastIndexOf('.');
    if (index > 0) {
      return fileName.substring(index + 1);
    }
    return fileName;
  }
  /** 获取无后缀的文件名 */
  static getNameByFileName(fileName: string) {
    return fileName.substring(0, fileName.lastIndexOf('.'));
  }

  /**
   * 根据文件id获取文件静态资源路径
   * @param fileId
   * @returns
   */
  static getFilePreviewImgPathUrl = (fileId: any) => {
    const url = `${env.VITE_API_IMAGE_PREVIEW_URL}/data/previewImage?fileId=${fileId}`;
    return url;
  };

  /**
   * 解析xlsx文件
   * @param file
   * @returns
   */
  static parsingExcelFile = (file: File) => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onload = (e) => {
        const workbook = XLSX.read(e.target?.result, { type: 'array' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const arrData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        resolve(arrData);
      };
    });
  };

  /**
     * 将tableData转换为xlsx文件导出
     * @param tableData 表格数据
     * @param excelName 导出表格名称
     * @param titleArr  表头标题（不传就导出所有属性）模版 [{ chineseName: '中文名',
      englishName: '英文属性',}]
     */
  static exportExcel(tableData: any, excelName: string, titleArr?: any) {
    const data: any = [];
    const keyArray = [];
    if (titleArr) {
      const englishTitle = titleArr.map((item: any) => {
        return item.englishName;
      });

      for (let i = 0; i < tableData.length; i++) {
        for (const key in tableData[i]) {
          if (!englishTitle.includes(key)) {
            delete tableData[i][key];
          }
        }
      }
    }
    const getLength = function (obj: any) {
      let count = 0;
      for (const i in obj) {
        if (obj.hasOwnProperty(i)) {
          count++;
        }
      }
      return count;
    };
    for (const key1 in tableData) {
      if (tableData.hasOwnProperty(key1)) {
        const element = tableData[key1];
        const rowDataArray: any = [];
        for (const key2 in element) {
          if (element.hasOwnProperty(key2)) {
            const element2 = element[key2];
            rowDataArray.push(element2);
            if (keyArray.length < getLength(element)) {
              keyArray.push(key2);
            }
          }
        }
        data.push(rowDataArray);
      }
    }
    // keyArray为英文字段表头
    const newArr = cloneDeep(keyArray);
    // 传了中英文表头列表就用中文表头
    if (titleArr) {
      for (let i = 0; i < newArr.length; i++) {
        for (let j = 0; j < titleArr.length; j++) {
          if (newArr[i] === titleArr[j].englishName) {
            newArr[i] = titleArr[j].chineseName;
          }
        }
      }
    }
    data.unshift(newArr);
    // data.splice(0, 0, keyArray, newArr);
    const ws = XLSX.utils.aoa_to_sheet(data);
    const wb = XLSX.utils.book_new();
    // 此处隐藏英文字段表头
    const wsrows: any = [{ hidden: false }];

    const cols = keyArray.map(() => {
      return {
        wch: 20,
      };
    });

    ws['!rows'] = wsrows; // ws - worksheet
    ws['!cols'] = cols; // ws - worksheet
    XLSX.utils.book_append_sheet(wb, ws, 'sheet');
    /* generate file and send to client */
    // const nowTime = moment().format('YYYY-MM-DD HH:mm:ss');
    XLSX.writeFile(wb, `${excelName}.xlsx`);
  }
}

// 导出文件
export const exportFile = (api: any, tableName: string, fileName: string, params: any, dict: any) => {
  getFormConfigureApi({ formName: tableName }).then((res: any) => {
    if (res.code === 200) {
      const formConfig = JSON.parse(res.data.formConfig);
      const listData = formConfig.filter((item: any) => item.isShow).map((item: any) => {
        const val: any = {
          key: item.key,
          title: item.title,
        };
        if (dict[item.key] && CommonStore().getDictData(dict[item.key])) {
          val.dictCode = dict[item.key];
          val.dictData = CommonStore().getDictData(dict[item.key]).O;
        }
        return val;
      });
      api({
        excelHeaders: listData,
        params,
      }, `${dayjs().format('YYYYMMDDHHmmss')}_${fileName || tableName}.xlsx`);
    }
  });
};

/**
  * 根据文件id下载文件
  * @param fileId
 */
export const downloadFileById = (fileId: number) => {
  const link = document.createElement('a');
  link.href = `${env.VITE_API_FILE_URL}/data/downloadFile?fileId=${fileId}`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
