import $api from '@/api'
import sha1 from 'js-sha1'
import tools from '@/utils/public.js'
import { blob } from 'd3'
import GLOBAL from '@/static/Global.js';
const { BlobServiceClient } = require("@azure/storage-blob")

let sasString = ''
let blobContainer = ''
let urlString = ''
let folder = ''
let containerClient  = null

/**
 * 初始化Blob,需要先调用授权API
 * @param {string} blobUrl blob地址
 * @param {string} container 容器名称
 * @param {string} sasString 授权
 * 
 * @return {ContainerClient} ContainerClient
 * */
function initBlob(blobUrl, container, sasString) {
    if (blobUrl && container && sasString) {
        const blobService = new BlobServiceClient(blobUrl + sasString)
        return blobService.getContainerClient(container);
    } else {
        return null
    }
}

/**
 * 上传文件方法,带回调上传进度
 * @param {any} file 文件对象
 * @param {any} path 文件夹路径
 * @param {any} containerClient initBlob返回数据
 * @param {any} option 官方可配置项
 */
async function upload(containerClient, file, path, option){
    return new Promise(async (r, j) => {
        const blockBlobClient = containerClient.getBlockBlobClient(path + "/" + file.name)
        blockBlobClient.uploadBrowserData(file, option).then(
            res => {
                let url = res._response.request.url
                url = url.substring(0, url.lastIndexOf('?'))
                let info = getExAndType(file.name)
                r({
                    url: url,
                    name: file.name,
                    size: res._response.request.body.size,
                    createTime: res.lastModified.getTime(),
                    extension: info.ex,
                    type: info.type
                })
            },
            err => {
                j(err)
            }
        )
    })
}
/**
 * 列出（查询）
 * @param {ContainerClient} containerClient initBlob返回数据
 * @param {Object} option ContainerListBlobsOptions
 * eg: option.prefix = 'res' 只查res文件夹下的blob
 * @param {Object} pageInfo 
 * eg: pageInfo.maxPageSize 当前请求条数
 * eg: pageInfo.continuationToken 首次请求不需要，后面需要（首次请求会返回，下次需要传入）
 * 
 * @returns {object} {blobList, continuationToken}
 */
async function listBlob(containerClient, option, pageInfo) {
    return new Promise(async (r, j) => {
        let page = {}
        let blobList = []
        if (pageInfo) {
            page.maxPageSize = pageInfo.maxPageSize ? pageInfo.maxPageSize : 50
            if (pageInfo.continuationToken) {
                page.continuationToken = pageInfo.continuationToken ? pageInfo.continuationToken : ''
            }
        }
        if (containerClient) {
            let iterator = containerClient.listBlobsFlat(option ? option : {}).byPage(page)
            let response = (await iterator.next()).value
            for (const blob of response.segment.blobItems) {
                let info = getExAndType(blob.name)
                blobList.push(
                    {
                        url: response.serviceEndpoint + response.containerName + '/' + blob.name,
                        name: blob.name.substring(response.prefix.length + 1),
                        size: blob.properties.contentLength,
                        createTime: blob.properties.lastModified.getTime(),
                        extension: info.ex,
                        type: info.type
                    }
                )
            }
            let continuationToken = response.continuationToken
            r({
                blobList,
                continuationToken
            })
        } else {
            j('containerClient 错误')
        }
    })
}
//获取文件后缀和类型
function getExAndType(fileName) {
    let ex = fileName.substring(fileName.lastIndexOf('.') + 1)
    let type = 'other'
    ex = ex.toUpperCase()
    for (let key in CONTENT_TYPES) {
        if (CONTENT_TYPES[key].indexOf(ex) != -1) {
            type = key
            break
        }
    }
    return {
        ex, type
    }
}
/**
 * 删除Blob
 * @param {containerClient} containerClient initBlob返回结果
 * @param {string} filePath 文件url + 容器 之后的路径
 */
function deleteBlob(containerClient,filePath) {
    return new Promise((r, j) => {
        containerClient.deleteBlob(filePath).then(
            res => {
                r(res)
            },
            err => {
                j(err)
            }
        )

    })
}

/**
 * 暴露的上传文件方法
 * @param {any} file 文件对象
 * @param {any} folder 文件夹路径
 * @param {any} type 个人/校本
 */
async function uploadFile(file, f, type) {
    return new Promise(async (r, j) => {
        let sasRes = undefined
        folder = f
        if (type == 'school') {
            sasRes = await tools.getSchoolSas()
        } else {
            sasRes = await tools.getPrivateSas()
        }
        sasString = sasRes.sas
        blobContainer = sasRes.name
        urlString = sasRes.url
        initBlob()
        let result = await uploadToBlob(file)
        r(result)
    })
}



/**
 * 上传文件到Blob
 * @param {any} file 文件对象
 */
function uploadToBlob(file) {
    return new Promise((r, j) => {
        //v12
        const blockBlobClient = containerClient.getBlockBlobClient(folder + "/" + file.name)
        blockBlobClient.uploadBrowserData(file).then(
            res => {
                r(res)
            },
            err => {
                j(err)
            }
        )

    })
    
}


export default {
    initBlob,
    uploadFile,
    upload,
    listBlob,
    deleteBlob
}