quanwei
2025-10-29 76ed09d116f484b261d44219de300b79eb2013b3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/*
 * 分会活动文件下载
 */
import Vue from 'vue';
const _that = new Vue();
export class ActivityFile {
    static async downloadFile(file_id, file_path, file_type, points) {
        try {
            if (points) {
                // 检查用户积分
                const hasEnoughPoints = await this.checkUserPoints(points);
                if (!hasEnoughPoints) {
                    await this.showPointsNotEnough()
                    return false;
                }
 
                // 显示积分确认弹窗
                const confirm = await this.showPointsConfirm(points)
                if (!confirm) {
                    return false;
                }
            }
 
            // 执行下载
            await this.executeDownload(file_id, file_path, file_type, points)
            return true;
 
        } catch (error) {
            console.error('下载失败:', error)
            uni.showToast({
                title: '下载失败',
                icon: 'none'
            })
            return false;
        }
    }
 
    static async getFilePath(file_id) {
        return new Promise((resolve) => {
            _that._get(
                'branch.activity/getFilePath', {
                    file_id: file_id,
                    is_original: 1 // 获取原图
                },
                function(res) {
                    resolve(res.data.file_path);
                }
            );
        })
    }
 
    // 检查用户积分 
    static async checkUserPoints(points) {
        return new Promise((resolve) => {
            _that._get(
                'branch.activity/checkUserPoints', {
                    points: points
                },
                function(res) {
                    resolve(res.data.is_enough);
                }
            );
        })
    }
 
    static async showPointsConfirm(points) {
        return new Promise((resolve) => {
            uni.showModal({
                title: '下载确认',
                content: `需要花费${points}个${_that.points_name()},确认下载吗?`,
                success: (res) => {
                    resolve(res.confirm)
                }
            })
        })
    }
 
    static async showPointsNotEnough() {
        return new Promise((resolve) => {
            uni.showModal({
                title: `${_that.points_name()}不足`,
                content: `您的${_that.points_name()}不足,无法下载`,
                showCancel: false,
                success: resolve
            })
        })
    }
 
    static async executeDownload(file_id, file_path, file_type = 'image', points) {
        await uni.showLoading({
            title: '下载中,请稍后...'
        })
        // 如果文件路径为空,需要从服务器获取
        if (!file_path) {
            file_path = await this.getFilePath(file_id);
        }
        // 生成文件名
        const file_name = new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14) + 
            Math.random().toString().slice(2, 6);
            
        // #ifdef H5
        // 在H5环境中使用Blob方式下载
        return await this.downloadViaBlob(file_path, file_name, points);
        // #endif
        
        // #ifdef APP-PLUS || MP-WEIXIN
        // 在App和微信环境中使用uni.downloadFile
        return await this.downloadInApp(file_path, points);
        // #endif
    }
    
    /**
     * H5环境下的安全下载
     */
    static async downloadViaBlob(file_path, file_name, points) {
        try {
            const response = await fetch(file_path);
            const blob = await response.blob();
            const objectUrl = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = objectUrl;
            a.download = file_name;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            
            setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
            
            await uni.hideLoading();
                    
            // 扣除积分
            await this.deductPoints(points);
            
            uni.showToast({
                title: '下载成功',
                icon: 'success'
            })
            
        } catch (error) {
            await uni.hideLoading();
            throw new Error(`下载失败: ${error.message}`);
        }
    }
    
    static async downloadInApp(file_path, points) {
        try {
            // 下载文件到临时路径
            const downloadResult = await uni.downloadFile({
                url: file_path
            })
        
            if (downloadResult.statusCode !== 200) {
                throw new Error('下载文件失败')
            }
        
            const { tempFilePath } = downloadResult;
            
            // 检查相册权限
            const hasPermission = await this.checkPhotoAlbumPermission()
            if (!hasPermission) {
                throw new Error('无相册权限')
            }
        
            if (file_type = 'image') {
                // 保存到相册
                await uni.saveImageToPhotosAlbum({
                    filePath: tempFilePath
                })
            } else {
                // 保存到相册
                await uni.saveVideoToPhotosAlbum({
                    filePath: tempFilePath
                })
            }
            
            await uni.hideLoading();
        
            // 扣除积分
            await this.deductPoints(points);
        
            uni.showToast({
                title: '下载成功',
                icon: 'success'
            })
        
        } catch (error) {
            await uni.hideLoading();
            throw error
        }
    }
 
    static async checkPhotoAlbumPermission() {
        return new Promise((resolve) => {
            // #ifdef MP-WEIXIN
            uni.getSetting({
                success: (res) => {
                    if (res.authSetting['scope.writePhotosAlbum']) {
                        resolve(true)
                    } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
                        // 首次尝试授权
                        uni.authorize({
                            scope: 'scope.writePhotosAlbum',
                            success: () => resolve(true),
                            fail: () => {
                                this.showAuthGuide()
                                resolve(false)
                            }
                        })
                    } else {
                        this.showAuthGuide()
                        resolve(false)
                    }
                }
            })
            // #endif
 
            // #ifdef APP-PLUS || H5
            resolve(true)
            // #endif
        })
    }
 
    static showAuthGuide() {
        uni.showModal({
            title: '权限申请',
            content: '需要您授权相册权限才能保存图片或视频',
            success: (res) => {
                if (res.confirm) {
                    uni.openSetting()
                }
            }
        })
    }
 
    // 扣除积分
    static async deductPoints(points) {
        return new Promise((resolve) => {
            _that._get(
                'branch.activity/deductPoints', {
                    points: points
                },
                function(res) {
                    resolve();
                }
            );
        })
    }
}