import { serviceURL } from "@/services/request";
import { message } from "ant-design-vue";
import { ref } from "vue";
import { FileInfo, FileItem } from "./interface";

function getBase64(file: File) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

function handleIsJSON(val: string) {
    try {
        const str = JSON.parse(val)
        return str
    } catch (e) {
        return val
    }
}

function getImg(imgURl: string) {
    let result = '';
    if (imgURl) {
        result = serviceURL.uploadUrl.replace('/upload', '') + imgURl.replace('./', '/');
    }
    return result;
}

function getImgName(value: string) {
    let result = '--'
    if (value) {
        // const str = JSON.parse(value).replace(/\"/g, "");
        const str = value.replace(/\"/g, "");
        const lastIndex = str.lastIndexOf('/') + 1;
        result = str.slice(lastIndex, str.length)
    }
    return result

}
export function handleUplodImg(limitSize = 1) {
    // 上传地址
    const uploadUrl = ref<string>('')
    // 图片列表
    const uploadImgList = ref<FileItem[]>([])

    /**
     * 获取上传地址，记住此方法需要在初始化数据加载完成（initData)之后 调用
     */
    function getUploadUrl() {
        uploadUrl.value = serviceURL.uploadUrl
    }

    /**
     * 上传图片变更
     * @param param0
     */
    function uploadChange({ file, fileList }: FileInfo) {
        let resFileList = [...fileList];
        // 1. Limit the number of uploaded files
        resFileList = resFileList.slice(-limitSize);
        // 2. 处理上传异常
        if (file.status === 'error') {
            if (file.response) {
                message.error(`服务器返回状态: ${file.response.code},${file.response.message}`)
            } else {
                message.error(`服务器无响应}`)
            }
        }
        if (file.status === 'done') {
            resFileList.forEach(el => {
                if (el.response) {
                    el.name = el.response[0].fileName
                }
            })
        }
        uploadImgList.value = resFileList;
        return Promise.resolve(uploadImgList.value)
    }
    /**
     * 获取图片的filePath
     * @returns
     */
    function getUploadResultUrl(): string[] {
        const result: string[] = []
        uploadImgList.value.forEach(el => {
            if (Array.isArray(el.response)) {
                el.response.forEach(e => {
                    result.push(e.filePath)
                })
            } else {
                console.warn('ant-design获取服务返回图片的数据发生变化，请在控制台查看')
                console.log(el)
            }
        })
        return result;
    }

    return { uploadUrl, uploadImgList, uploadChange, getUploadUrl, getUploadResultUrl }
}

/**
 * 预览图片
 */
export function handlePreviewImg() {
    // 是否查看附件
    const previewVisible = ref<boolean>(false)
    // 预览图片地址
    const previewImage = ref<string | undefined>('');
    /**
     * 关闭查看图片
     */
    function cancelImg() {
        previewVisible.value = false;
    }
    /**
    * 预览图片
    */
    async function previewImg(file: FileItem | string) {
        if (typeof file === 'string') {
            if (file && file !== '--') {
                // 处理服务的脏数据，时而反而JSON格式，时而返回string格式，
                // fuck
                const temp = handleIsJSON(file).replace(/\"/g, "")
                previewImage.value = getImg(temp)
                previewVisible.value = true;
            }
        } else {
            if (!file.url && !file.preview) {
                file.preview = (await getBase64(file.originFileObj)) as string;
            }
            previewImage.value = file.url || file.preview;
            previewVisible.value = true;
        }
    }
    return { previewVisible, previewImage, cancelImg, previewImg, getImgName }
}

/**
 * 获取上传好的图片地址
 * @returns
 */
export function getUploadImg() {
    // 存储上传的图片
    const imgs = ref<string[]>([])
    // 存储从服务获取的图片信息，用于展示
    const uploadImgList = ref<FileItem[]>([])
    // 上传图片
    function uploadImgAction(value: string[]) {
        imgs.value = value
    }
    // 用于处理从服务获取的图片
    function handleImg(value: string) {
        const arr = value.split(',')
        return arr.map((e, i) => {
            const str = handleIsJSON(e);
            return {
                uid: i.toString(),
                name: getImgName(e),
                url: getImg(str),
            };
        });

    }
    // 获取上传的第一张图片
    function getFirstImg() {
        return imgs.value.length ? imgs.value[0] : ''
    }
    return { imgs, uploadImgAction, uploadImgList, handleImg, getFirstImg }
}