import CryptoJS from 'crypto-js';
import { HOST_R } from '@/api/evn'

const FILE_MODEL = 'i5tWsbYNQ91' // 文件预览数据应用

/**
 * 文件上传（新）
 */
export const upload = (event: File) => {
    return new Promise((resolve, reject) => {
        // 计算hash值
        var reader = new FileReader();
        reader.onload = (e: any) => {
            var fileData = e?.target.result;
            var wordArray = CryptoJS.lib.WordArray.create(fileData);
            var hash = CryptoJS.SHA1(wordArray).toString();
            uploadFile(event, event.name, { privacy: 0, isFolder: 0, parentId: 0 }, hash).then((res) => {
                resolve(res);
            }).catch((err) => {
                reject(err);
            })
        };
        reader.readAsArrayBuffer(event);
    })
};

const uploadFile = (file: File, fileName: string, data = { privacy: 0, isFolder: 0, parentId: 0 }, hash: string) => {
    return new Promise((resolve, reject) => {
        let contentType = '' as any;
        fetch(`/api/upload/${fileName}?privacy=${data.privacy}&isFolder=${data.isFolder}&parentId=${data.parentId}&signature=${hash}`, {
            method: 'POST',
            body: file,
        })
            .then(response => {
                if (!response.ok) {
                    reject(new Error('文件上传失败！'));
                    throw new Error('文件上传失败！');
                }
                contentType = response.headers.get('Content-Type')
                return response.text();
            })
            .then(responseText => {
                let id = '' as any;
                if (contentType.includes('application/json')) {
                    id = JSON.parse(responseText).data.id
                } else if (contentType.includes('text/event-stream')) {
                    const idRegex = /id: ([\w-]+)/;
                    const match = responseText.match(idRegex);
                    id = match && match[1];
                }
                // state.fileList = [{
                //     name: fileName,
                //     hash: hash,
                //     id,
                // }];
                resolve(id)
            })
            .catch(error => {
                reject(error);
                console.log('文件上传失败4！', error);
            });
    })
}



/**
 *  获取文件url
 */

export const getFileUrl = (id: string, isAsync = false) => {
    if (isAsync) {
        return new Promise((resolve, reject) => {
            fetch(`/api/x/${id}?t=${FILE_MODEL}`, {
                method: 'GET',
            })
                .then(response => response.json())
                .then(res => {
                    const filePath = res?.data?.[0]?.filePath
                    resolve(filePath?.includes('http')?filePath:`${HOST_R}${res?.data?.[0]?.filePath}`)
                })
                .catch(error => {
                    reject(error);
                    console.log('文件上传失败5！', error);
                });
        })
    }
    return `${HOST_R}/uploads/${id}`
}
