import config from "@/config";
import {useUserStore} from "@/hooks/useUserStore";

export const useChooseImage = function () {
    const {token} = useUserStore()

    /*
		 * @description 选择图片上传
		 * @param {successCallback} 上传图片成功后的回调
		 * @param {type} 可选参数，类型，默认为6
		 * @value 10	竞赛
		 * @value 8		临时文件本地路径
		 * @value 7		试题收藏
		 * @value 6		答题附件
		 * @value 5		微课文件库
		 * @value 4		app上传视频
		 * @value 3		校本资源库
		 * @value 2		云库
		 * @value 1 	个人资源库
		 * @value 0 	默认路径
		 * @param {count} 限制数量，默认为1
		 */
    const chooseImage = function (successCallback, type = 6, count = 1) {
        const uploadUrl = config.serverBaseUrl + '/common/uploadFile2OSS/' + type
        uni.chooseImage({
            count: count, //默认9
            sourceType: ['album', 'camera'],
            success: (res) => {
                const tempFilePaths = res.tempFilePaths;
                uni.showLoading();
                uni.uploadFile({
                    url: uploadUrl,
                    header: {
                        Authorization: 'Bearer ' + token.value,
                    },
                    filePath: tempFilePaths[0],
                    name: 'file',
                    success: (uploadFileRes) => {
                        const data = JSON.parse(uploadFileRes.data);
                        successCallback(data)
                    },
                    complete: () => {
                        uni.hideLoading();
                    }
                })
            }
        })
    }

    const chooseAvatar = function (successCallback) {
        const uploadUrl = config.serverBaseUrl + '/system/user/profile/avatar'
        uni.chooseImage({
            count: 1, //默认9
            sourceType: ['album', 'camera'],
            success: (res) => {
                const tempFilePaths = res.tempFilePaths;
                uni.showLoading();
                uni.uploadFile({
                    url: uploadUrl,
                    header: {
                        Authorization: 'Bearer ' + token.value,
                    },
                    filePath: tempFilePaths[0],
                    name: 'avatarfile',
                    success: (uploadFileRes) => {
                        const data = JSON.parse(uploadFileRes.data);
                        successCallback(data)
                    },
                    complete: () => {
                        uni.hideLoading();
                    }
                })
            }
        })
    }

    const previewImage = function (url, current = 0) {
        const urls = [].concat(url)
        uni.previewImage({
            urls: urls,
            current: current,
            indicator: urls.length > 1 ? 'number' : 'none',
            fail: function (e) {
                console.log('previewImage failed:', e)
            }
        })
    }

    return {chooseImage, chooseAvatar, previewImage}
}
