# useUtils 工具函数

提供常用的工具函数集合，包括时间处理、文件操作、Cookie管理等。

## 基本用法

```vue
<script setup lang="ts">
import { useUtils } from 'el-plus'

const {
  getUnifyTime,
  dayjs,
  importFile,
  downloadFile,
  previewFile,
  Cookies
} = useUtils()

// 时间格式化
const time = getUnifyTime('2024-01-01')
const formatted = dayjs().format('YYYY-MM-DD HH:mm:ss')

// 文件导入
importFile().then(file => {
  console.log('导入的文件:', file)
})

// 文件下载
downloadFile({ api: '/api/download', fileName: 'test.xlsx' })

// 文件预览
previewFile('/files/document.pdf')

// Cookie 操作
Cookies.set('token', 'xxx')
const token = Cookies.get('token')
</script>
```

## 返回值

| 属性 | 说明 | 类型 |
|------|------|------|
| getUnifyTime | 统一时间处理函数 | `(time: string \| number \| Date) => string` |
| dayjs | Day.js 实例 | `typeof dayjs` |
| importFile | 文件导入函数 | `() => Promise<File>` |
| downloadFile | 文件下载函数 | `(config: DownloadConfig) => Promise<void>` |
| previewFile | 文件预览函数 | `(url: string) => void` |
| Cookies | Cookie 操作对象 | `CookiesStatic` |

## 功能说明

### getUnifyTime 时间处理

统一时间格式处理函数。

```ts
// 时间戳转格式化字符串
const time1 = getUnifyTime(1609459200000)

// Date对象转格式化字符串
const time2 = getUnifyTime(new Date())

// 字符串转格式化字符串
const time3 = getUnifyTime('2024-01-01')
```

### dayjs 日期处理

提供 Day.js 的所有功能，用于日期格式化和计算。

```ts
// 格式化当前时间
const now = dayjs().format('YYYY-MM-DD HH:mm:ss')

// 日期计算
const tomorrow = dayjs().add(1, 'day')
const lastMonth = dayjs().subtract(1, 'month')

// 日期比较
const isBefore = dayjs('2024-01-01').isBefore(dayjs())
```

### importFile 文件导入

打开文件选择器，返回选择的文件对象。

```ts
importFile().then(file => {
  console.log('文件名:', file.name)
  console.log('文件大小:', file.size)
  console.log('文件类型:', file.type)
})
```

### downloadFile 文件下载

触发文件下载，支持直接链接下载和 Blob 流式下载。

```ts
// 直接链接下载
downloadFile({
  src: '/files/document.pdf',
  fileName: '文档.pdf'
})

// 接口下载（非 Blob，接口返回文件地址）
downloadFile({
  api: '/api/export',
  fileName: '导出数据.xlsx',
  data: { id: '123' }
})

// Blob 流式下载（接口返回二进制流）
downloadFile({
  api: '/api/export',
  blob: true,
  fileName: '导出数据.xlsx',
  data: { id: '123' }
})
```

当 `blob` 为 `true` 时，会以 `responseType: 'blob'` 发起请求，自动从响应头 `Content-Disposition` 中提取文件名，并创建 Blob URL 触发下载，下载完成后自动释放内存。

### previewFile 文件预览

在新窗口中预览文件。

```ts
// PDF预览
previewFile('/files/document.pdf')

// 图片预览
previewFile('/images/photo.jpg')
```

### Cookies Cookie管理

提供 Cookie 的增删改查操作。

```ts
// 设置 Cookie
Cookies.set('token', 'xxx', { expires: 7 }) // 7天后过期

// 获取 Cookie
const token = Cookies.get('token')

// 删除 Cookie
Cookies.remove('token')

// 获取所有 Cookie
const allCookies = Cookies.get()
```

## 注意事项

- `importFile` 会打开系统文件选择器
- `downloadFile` 支持跨域下载，会自动处理 blob 响应
- `downloadFile` 的 `blob` 模式适用于接口直接返回二进制流的场景，会自动从 `Content-Disposition` 响应头提取文件名；若未指定 `fileName` 且响应头中也无文件名信息，可能导致文件名缺失
- `previewFile` 会打开新窗口或标签页
- `Cookies` 基于 js-cookie 库，支持所有其配置选项
