import http, { checkStatus } from '@/utils/http';
import { Client, FileDownloadSheetAction } from '@/enums/api'
import { LoginReqParams, LoginResParams, PermissonListResParams, SelfInfoResParams } from '@/types/client';


/**
 * 小程序注册到系统
 * @param code 小程序提供的code，用于换取openid
 */
export const login = (data: LoginReqParams) => {
    const url = Client.LOGIN;
    return http.post<LoginResParams>(url, data)
}

/**
 * 获取当前登录用户权限集
 */
export const getPermissions = async () => {
    const url = Client.GET_PERMISSIONS
    return http.post<PermissonListResParams>(url, {})
}

export const postUserInfo = async (data: { code: string, mobile: { iv: string, encryptedData: string } }) => {
    const url = Client.AUTHORIZE_MOBILE
    return http.post<PermissonListResParams>(url, data)
}

/**
 * 获取当前登录用户个人信息
 */
export const getSelfInfo = () => {
    return http.post<SelfInfoResParams>(
        Client.GET_SELF_INFO,
        {}
    )
}

/**
 * 设置当前登录用户个人信息
 * @param params
 */
export const setSelfInfo = (params: {
    name?: string
    mobile?: string
    email?: string
    old_pass?: string
    new_pass?: string
}) => {
    return http.post<BaseResParams>(
        Client.SET_SELF_INFO,
        params
    )
}



/**
 * 上传
 * @param url
 * @param params
 * @returns
 */
export const uploadFile =  (params: {
    url: string,
    object_name: string,
    headers?: { [key: string]: any },
    formData?: { [key: string]: any },
    filePath: string,
    uploadProgress?: (progressEvent: UniApp.OnProgressUpdateResult, otherParams: any) => void,
    timeout?: number | 36000
    name?: string
    otherParams?: any
}) => {
    return new Promise((resolve, reject) => {
        try {
            const { 
                headers,
                object_name,
                url, //仅为示例，并非真实接口地址。
                formData,
                uploadProgress,
                filePath,
                name,
                timeout,
                otherParams
            } = params;
            const customFilename = name || 'file'
            var uploadTask = uni.uploadFile({
                url, //仅为示例，并非真实接口地址。
                formData: {
                    key: object_name,
                    ...formData
                },
                headers,
                filePath,
                timeout,
                name: customFilename,
                fail: (e) => {
                    uni.showModal({
                        title: '上传失败',
                        content: `${e.errMsg}`
                    })
                },
                success: (uploadFileRes) => {
                    checkStatus(uploadFileRes.statusCode)
                    return resolve(uploadFileRes.data)
                }
            });
            uploadProgress ? uploadTask.onProgressUpdate(res => uploadProgress(res, otherParams)) : null
        } catch (e) {
            reject(e)
        }
    })
}


/**
 * 下载
 * @param url
 * @param params
 * @returns
 */
export const downloadFile = (params: {
    url: string,
    downloadProgress?: (progressEvent: UniApp.OnProgressDownloadResult, otherParams: any) => void,
    timeout?: number | 36000
    otherParams?: any,
    filename?: string
}) => {
    return new Promise<{ savedFilePath: string }>((resolve, reject) => {
        try {
            const { url, downloadProgress, timeout, otherParams, filename
            } = params;
            var downloadTask = uni.downloadFile({
                url, //仅为示例，并非真实接口地址。
                timeout,
                fail: (e) => {
                    uni.showModal({
                        title: '下载失败',
                        content: `${e.errMsg}`
                    })
                },
                success: (downloadFileRes: UniApp.DownloadSuccessData) => {
                    checkStatus(downloadFileRes.statusCode)
                    return resolve({
                        savedFilePath: downloadFileRes.tempFilePath
                    })

                }
            });
            downloadProgress ? downloadTask.onProgressUpdate(res => downloadProgress(res, otherParams)) : null
        } catch (e) {
            return reject(e)
        }
    })
}


export const saveFile = async (savedFilePath: string, filename?: string, sheetIndex?: FileDownloadSheetAction) => {
    if (sheetIndex === FileDownloadSheetAction.SHARE) {
        uni.shareFileMessage({
            filePath: savedFilePath,
            fileName: filename,
            success: () => {
                uni.showModal({
                    title: `分享成功`
                })
                console.log('成功')
            },
            fail: (err: UniApp.GeneralCallbackResult) => {
                uni.showModal({
                    title: `分享失败`,
                    content: err.errMsg
                })
                throw new Error(`分享失败：${err.errMsg}`)
            }
        })

    } else {
        uni.addFileToFavorites({
            filePath: savedFilePath,
            fileName: filename,
            success: () => {
                uni.showModal({
                    title: `收藏成功`
                })
            },
            fail: (err: UniApp.GeneralCallbackResult) => {
                uni.showModal({
                    title: `收藏失败`,
                    content: err.errMsg
                })
                throw new Error(`收藏失败：${err.errMsg}`)
            }
        })
    }
}

// export const collectFile = async (savedFilePath: string, filename?: string) => {
//     uni.addFileToFavorites({
//         filePath: savedFilePath,
//         fileName: filename,
//         success: () => {
//             return uni.showModal({
//                 title: `收藏成功`
//             })
//         },
//         fail: (err: UniApp.GeneralCallbackResult) => {
//             uni.showModal({
//                 title: `收藏失败：${err.errMsg}`
//             })
//         }
//     });
// }