export default {
    // imgUrls 需要下载的全部图片  num 每次同时下载张数（最大为7）
    downfiles(imgUrls, num = 3) {
        return new Promise((resolve, reject) => {
            let lsit = []
            let imgUrlsLength = imgUrls.length

            let downList = []
            let spliceIndex = 0
            const spliceFunction = () => {
                downList[spliceIndex] = imgUrls.splice(0, num)
                if (imgUrls.length == 0) {
                    return
                } else {
                    spliceIndex++
                    spliceFunction()
                }
            }
            // 切割url数组
            spliceFunction()

            const final = []
            let downIndex = 0
            const downFunction = (arr) => {
                const list = []
                console.log(arr[downIndex])
                if(arr[downIndex]){
                    arr[downIndex].map((item,index) => {
                        uni.downloadFile({
                            url: item,
                            success: (res) => {
                                list.push({url:res.tempFilePath,index:index})
                                if (list.length === arr[downIndex].length) {
                                    downIndex++
                                    // 对每一批下载完成的图片进行重新排序 避免动画混乱
                                    list.sort((a,b)=>{
                                        return a.index - b.index
                                    })
                                    list.map(item=>{
                                        final.push(item.url)
                                    })
                                    downFunction(downList)
                                } else {
                                    return
                                }
                            }
                        });
                    })
                }
                if(final.length===imgUrlsLength){
                    resolve(final)
                }
            }
            // 执行批量下载任务
            downFunction(downList)
        })
    }
}