import { storeToRefs } from "pinia";
import { QRBookFileInfoRequset } from "./QRBookDto";
import {ContentType, HttpClient, RequestParams} from "/@/api/admin/http-client";
import {AxiosResponse} from "axios";
import { useUserInfo } from "/@/stores/userInfo";
import { number } from "echarts";

export class QRBookApi<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {
    /**
     * 分页查询
     * @param data 
     * @returns 
     */
    getPage = (query:any ,params: RequestParams = {}) : any  => 
        this.request<AxiosResponse,any>({
            path:'/api/app/qr-book/get-page',
            method: 'GET',
            query:query,
            secure: true,
            format: 'json',
            ...params
          })
    

    /**
     * 上传/修改文件信息
     * @param data 
     * @returns 
     */
    uploadFile = (data:QRBookFileInfoRequset) => 
        this.request<AxiosResponse,any>({
            path: `/api/app/qr-book/upload`,
            method: 'POST',
            body: data,
            secure: true,
            type: ContentType.Json,
            format: 'json',
        })

    /**
     * 下载文件
     * @param id 下载文件对应 id
     * @param type 下载类型—— 0：文件；1：二维码
     * @param FileName 下载文件名
     */
    donwloadFile = (id:string, type:number,fileName:string) => {
        const { userInfos } = storeToRefs(useUserInfo());
        const accessToken = userInfos.value.token
        const token = `Bearer ${accessToken}`
        var myHeaders = new Headers();
        myHeaders.append("Authorization", token);

        const requestOptions: RequestInit = {
            method: 'GET',
            headers: myHeaders,
            redirect: 'follow', // 此处使用枚举值 'follow'
        };

        const fileUrl = import.meta.env.VITE_API_URL +'/api/app/qr-book/download?id='+id+'&type='+type; // 替换为实际文件URL
        fetch(fileUrl,requestOptions)
            .then(response => response.blob())
            .then(blob => {
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = fileName;
                link.click();
            }).catch(error => {
                console.error('下载失败：', error);
            });
    }
}