/*
 * 根据某个属性进行分组
 */
import JSONPath from 'jsonpath'
function groupBy(array, key) {
    const groups = {}
    array.forEach(function (item) {
        const group = JSON.stringify(item[key])
        groups[group] = groups[group] || []
        groups[group].push(item)
    })
    return Object.keys(groups).map(function (group) {
        return groups[group]
    })
}
/*
 * 判断两个对象是否相等
 */
function isObjEqual(o1, o2) {
    var props1 = Object.keys(o1)
    var props2 = Object.keys(o2)
    if (props1.length != props2.length) {
        return false
    }
    for (var i = 0, max = props1.length; i < max; i++) {
        var propName = props1[i]
        if (o1[propName] !== o2[propName]) {
            return false
        }
    }
    return true
}
/*
 * 获取对象在对象数组的index
 */
function getIndex(_arr, _obj) {
    var len = _arr.length
    for (let i = 0; i < len; i++) {
        if (isObjEqual(_arr[i], _obj)) {
            return parseInt(i)
        }
    }
    return -1
}
/*
 * 产生某个范围的随机数
 */
function getBtwRandom(start, end) {
    return Math.floor(Math.random() * (end - start)) + start
}
/*
 * 根据学段编码获取对应学段信息
 */
function getPeriod(data, periodCode) {
    if (data == undefined) {
        return {
            name: '暂无数据',
            id: '00',
            grades: [],
            subjects: []
        }
    } else {
        let result = JSONPath.query(data, "$..[?(@.id=='" + periodCode + "')]")
        if (result.length == 0) {
            return {
                name: '暂无数据',
                id: '00',
                grades: [],
                subjects: []
            }
        } else {
            return result[0]
        }
    }
}
/*
 * 根据年级编码获取对应Name
 */
function getGradeName(data, gradeCode) {
    let result = JSONPath.query(data, "$..[?(@.id=='" + gradeCode + "')]")
    if (result.length == 0) {
        return '暂无数据'
    } else {
        return result[0].name
    }
}
/*
 * 根据学科编码获取对应Name
 */
function getSubjectName(data, subjectCode) {
    let result = JSONPath.query(data, "$..[?(@.id=='" + subjectCode + "')]")
    if (result.length == 0) {
        return '暂无数据'
    } else {
        return result[0].name
    }
}
/*
 * 根据学科编码获取对应Name
 */
function getClassroomByCode(data, classroomCode) {
    let result = JSONPath.query(data, "$..[?(@.classroomCode=='" + classroomCode + "')]")
    if (result.length == 0) {
        return {}
    } else {
        return result[0]
    }
}

/*
 *根据图片链接压缩图片得到缩略图 
 * @params url: 文件url
 */
function compressImgByUrl(url, name, quality) {
    return new Promise((r, j) => {
        try {
            let img = new Image()
            img.setAttribute('crossOrigin', 'Anonymous')
            img.src = url
            img.onload = function () {
                let canvas = document.createElement('canvas')
                canvas.width = 200
                canvas.height = 200 * img.height / img.width
                let ctx = canvas.getContext('2d')
                ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height)
                let newImgData = canvas.toDataURL('image/png', quality)
                //let resultFile = dataURLtoFile(newImgData, name)
                //r(resultFile)
                r(newImgData)
            }
        }
        catch (err) {
            j(err)
        }
    })
}
/*
 *根据视频链接创建封面图
 * @params url: 文件url
 */
function createVideoPoster(url, name, quality) {
    return new Promise(
        (r, j) => {
            try {
                let video = document.createElement('video')
                video.setAttribute('crossOrigin', 'Anonymous')
                video.setAttribute('width', '300')
                video.setAttribute('controls', 'controls')
                video.setAttribute('crossOrigin', 'Anonymous')
                video.setAttribute('src', url)
                video.currentTime = 1
                video.addEventListener('loadeddata', () => {
                    let canvas = document.createElement('canvas')
                    canvas.width = 300
                    canvas.height = 300 * video.videoHeight / video.videoWidth
                    let ctx = canvas.getContext('2d')
                    ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, canvas.width, canvas.height)
                    let newVideoData = canvas.toDataURL('image/png', quality)
                    //let resultFile = dataURLtoFile(newVideoData, name)
                    r(newVideoData)
                })
            }
            catch (err) {
                j(err)
            }
        }
    )
}

/*
 *dataUrl转文件 
 */
function dataURLtoFile(dataurl, filename) {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], filename, { type: mime })
}
/*
 *文件转dataUrl
 */
function fileToURL(file) {
    return new Promise((r, j) => {
        try {
            var reader = new FileReader()
            reader.onloadend = function (e) {
                r(e.target.result)
            }
            reader.readAsDataURL(file)
        } catch (e) {
            j(e)
        }
    })

}

/*
 * 函数防抖
 */
function debounce(func, delay) {
    return function () {
        window.clearTimeout(window.timeout)
        window.timeout = setTimeout(() => {
            clearTimeout(window.timeout)
            func.apply(this, arguments)
        }, delay)
    }
}

/*
 * 函数节流
 */
function throttle(func, delay) {
    let run = true
    return function () {
        if (!run) {
            return  // 如果开关关闭了，那就直接不执行下边的代码
        }
        run = false // 持续触发的话，run一直是false，就会停在上边的判断那里
        setTimeout(() => {
            func.apply(this, arguments)
            run = true // 定时器到时间之后，会把开关打开，我们的函数就会被执行
        }, delay)
    }
}
//转换bytes
function formatBytes(bytes) {
    return bytes / 1024 < 1024 ? (bytes / 1024).toFixed(1) + 'KB' : bytes / 1024 / 1024 < 1024 ? (bytes / 1024 / 1024).toFixed(1) + 'M' : (bytes / 1024 / 1024 / 1024).toFixed(1) + 'G'
}
//生成uuid
function uuid() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }
    return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
}
// 获取某个字符在字符串中第num次出现的index
function findChartIndex(str, cha, num) {
    var x = str.indexOf(cha);
    for (var i = 0; i < num; i++) {
        x = str.indexOf(cha, x + 1);
    }
    return x;
}

/**
 * 根据班级学年年级名称
 * @param data 学校基础数据 schoolProfile.school_base
 * @param curPd 当前学段id
 * @param year 学年
 */
function getGradeNameByYear(data, curPd, year) {
    if (year && data && data.period && curPd) {
        let pData = data.period.find(item => {
            return item.id == curPd
        })
        if (pData) {
            let date = new Date()
            let curYear = date.getFullYear()
            let month = date.getMonth() + 1
            let start = pData.semesters.find(item => {
                return item.start == 1
            })
            // 根据入学月份确定当前年级和学级的关系
            if (start && month < start.month) {
                curYear--
            }
            let res = pData.grades[curYear - year]
            if (curYear - year >= pData.grades.length) {
                return '已毕业'
            }
            return res ? res : '未到入学时间'
        } else {
            return '- -'
        }
    } else {
        // console.error('参数错误：Func getGradeNameByYear')
        return '- -'
    }
}

export default {
    groupBy,
    isObjEqual,
    getIndex,
    getBtwRandom,
    getPeriod,
    getGradeName,
    getSubjectName,
    getClassroomByCode,
    compressImgByUrl,
    createVideoPoster,
    dataURLtoFile,
    fileToURL,
    debounce,
    throttle,
    formatBytes,
    uuid,
    findChartIndex,
    getGradeNameByYear
}
