import html2canvas from 'html2canvas'
import JsPDF from 'jsPDF'
import {
    showLoading,
    hideLoading
} from '@/assets/utils/loading'

// 根据数组key值去重 console.log(removeRepeatByKey(arr, 'id'));
export function removeRepeatByKey (arr, name) {
    let hash = {}
    return arr.reduce(function (item, next) {
        // eslint-disable-next-line no-unused-expressions
        hash[next[name]] ? '' : hash[next[name]] = true && item.push(next)
        return item
    }, [])
}
// 数组去重
export function unique (arr) {
    return Array.from(new Set(arr))
}

// 格式化日期
export function formatDate (year, month, day) {
    let y = year
    let m = month
    if (m < 10) m = '0' + m
    let d = day
    if (d < 10) d = '0' + d
    return y + '-' + m + '-' + d
}

// 日期格式化
// now 为时间 例如 new Date()
// type为1：YYYY-MM-DD； type为2： YYYY-MM-DD HH:mm
// txt为1：显示的格式为2019-10-01； txt为2：2019年10月01日
export function currentTime (now, type, txt) {
    // let now = new Date()
    let year = now.getFullYear() // 年
    let month = now.getMonth() + 1 // 月
    let day = now.getDate() // 日
    let hh = now.getHours() // 时
    let mm = now.getMinutes() // 分
    let clock = txt === 1 ? year + '-' : year + '年'
    if (month < 10) {
        clock += '0'
    }
    clock += txt === 1 ? month + '-' : month + '月'
    if (day < 10) {
        clock += '0'
    }
    clock += txt === 1 ? day + ' ' : day + '日'
    if (type === 1) {
        return (clock)
    }
    if (hh < 10) {
        clock += '0'
    }
    clock += txt === 1 ? hh + ':' : hh + '时'
    if (mm < 10) clock += '0'
    clock += txt === 1 ? mm : mm + '秒'
    return (clock)
}

// 图片域名
export function globalImageHost () {
    let [globalImageHost, nodeEnv] = ['', process.env.NODE_ENV]
    if (nodeEnv === 'production') {
        globalImageHost = 'http://image.vschool100.com'
    } else {
        globalImageHost = 'http://test.vschool100.com:8888'
    }
    return globalImageHost
}

export function getFilePath (url, type = 1) {
    if (!url || /^https?:\/\/|^blob:|^data:/.test(url) || !/^[12]$/.test(type)) {
        return url
    } else {
        return type === 1 ? 'https://file.vschool100.com' + url
            : type === 2 ? 'https://static.vschool100.com' + url : ''
    }
}

// 导出excel域名
export function exportHostName () {
    let [exportHostName, nodeEnv] = ['', process.env.NODE_ENV]
    if (nodeEnv === 'development') {
        exportHostName = 'localhost:8080'
    } else if (nodeEnv === 'testing') {
        exportHostName = 'https://test.vschool100.com'
    } else if (nodeEnv === 'production') {
        exportHostName = 'https://oa.vschool100.com'
    }
    return exportHostName
}

// dom导出pdf , name = 'download', padding = 0
export const domToPDF = (el, name = 'download') => {
    showLoading()
    if (el) {
        html2canvas(el, {
            useCORS: true,
            allowTaint: true
        }).then(canvas => {
            // 未生成pdf的html页面高度
            var leftHeight = canvas.height
            var a4Width = 595.28
            var a4Height = 841.89
            // 一页pdf显示html页面生成的canvas高度;
            var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height)
            // pdf页面偏移
            var position = 0
            var pageData = canvas.toDataURL('image/jpeg', 1.0)
            var pdf = new JsPDF('x', 'pt', 'a4')
            // eslint-disable-next-line no-unused-vars
            var index = 1
            var canvas1 = document.createElement('canvas')
            var height
            pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen')

            var pdfName = name // 设置导出文件的名称
            function createImpl (canvas) {
                if (leftHeight > 0) {
                    index++
                    var checkCount = 0
                    if (leftHeight > a4HeightRef) {
                        var i = position + a4HeightRef
                        for (i = position + a4HeightRef; i >= position; i--) {
                            var isWrite = true
                            for (var j = 0; j < canvas.width; j++) {
                                var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data
                                if (c[0] !== 0xff || c[1] !== 0xff || c[2] !== 0xff) {
                                    isWrite = false
                                    break
                                }
                            }
                            if (isWrite) {
                                checkCount++
                                if (checkCount >= 10) {
                                    break
                                }
                            } else {
                                checkCount = 0
                            }
                        }
                        height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef)
                        if (height <= 0) {
                            height = a4HeightRef
                        }
                    } else {
                        height = leftHeight
                    }

                    canvas1.width = canvas.width
                    canvas1.height = height
                    // console.log(index, 'height:', height, 'pos', position);
                    var ctx = canvas1.getContext('2d')
                    ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height)

                    // var pageHeight = Math.round(a4Width / canvas.width * height)
                    // pdf.setPageSize(null, pageHeight)
                    if (position !== 0) {
                        pdf.addPage()
                    }
                    pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 0, a4Width, a4Width / canvas1.width * height)
                    leftHeight -= height
                    position += height
                    if (leftHeight > 0) {
                        setTimeout(createImpl, 500, canvas)
                    } else {
                        pdf.save(pdfName + '.pdf')
                        hideLoading()
                    }
                }
            }

            // 当内容未超过pdf一页显示的范围，无需分页
            if (leftHeight < a4HeightRef) {
                pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, a4Width / canvas.width * leftHeight)
                pdf.save(pdfName + '.pdf')
                hideLoading()
            } else {
                try {
                    pdf.deletePage(0)
                    setTimeout(createImpl, 500, canvas)
                } catch (err) {
                    console.log(err)
                }
            }
        })

    /*  const base64 = canvas.toDataURL()
      const pdf = new JsPDF()
      const A4Width = 210 - padding * 2 // PDF按照A4纸大小
      const elHeight = A4Width * el.offsetHeight / el.offsetWidth - padding * 2
      const position = 0
      pdf.addImage(base64, 'PNG', padding, padding, A4Width, elHeight)
      if (elHeight > 290) {
        pdf.addImage(base64, 'PNG', padding, padding - 290, A4Width, elHeight)
        pdf.addPage()
      }
      pdf.save(name + '.pdf') */
    } else {
        throw new Error('public.js > domToPDF 方法的 el 参数不能为空')
    }
}

// 将参数对象转换成查询字符串
export const formatParams = params => '?' + Object.keys(params).map(item => item + '=' + params[item]).join('&')
