// 常用的方法
import gsap from 'gsap'
import { Howl, Howler } from 'howler';
import { Toast } from 'vant';
import { createVNode, render } from 'vue'


// 初始化
const btnEnable = ref(true)  //按钮可点击状态

// 音效初始化
const sound = new Howl({
    src: [new URL(`@/assets/media/click.mp3`, import.meta.url).href]
});

// 背景音乐
export function createBGM() {
    const musicNode = createVNode(
        'div',
        {
            class: 'music-icon',
            id: 'musicBtn',
            onClick: () => {
                let auduoEle = document.querySelector("#audio")
                let musicBox = document.querySelector("#musicBtn")
                if (auduoEle.paused) {
                    auduoEle.play()
                    audioAni.play()
                    musicBox.classList.add('music-on')
                    musicBox.classList.remove('music-off')
                } else {
                    gsap.set('#musicBtn', { rotation: '0deg' })
                    auduoEle.pause()
                    audioAni.pause()
                    musicBox.classList.add('music-off')
                    musicBox.classList.remove('music-on')
                }
            },

        },
    )
    const audioNode = createVNode(
        'audio',
        {
            class: 'audio-icon',
            id: 'audio',
            src: new URL(`@/assets/media/bgm.mp3`, import.meta.url).href,
            autoPlay: true,
            loop: true,
        },
    )

    render(musicNode, document.querySelector('.home'));
    render(audioNode, document.querySelector("#musicBtn"));
    document.querySelector("#musicBtn").classList.add('music-on')
    let audioAni = gsap.timeline({ paused: true })
    audioAni.to('#musicBtn', { duration: 10, rotation: "+=360", repeat: -1, ease: 'none' })
    setTimeout(() => {
        audioAni.play()
    }, 1000)
}


//是否在微信环境
export function isWX() {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {

        return true;
    } else {

        return false;
    }
}

// 判断是否移动端
export function isMobile() {
    let userAgentInfo = navigator.userAgent;
    let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
    let getArr = Agents.filter(i => userAgentInfo.includes(i));
    return getArr.length ? true : false;
}


// 判断微博环境
export function isWeibo() {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/WeiBo/i) == "weibo") {
        console.log("微博环境");
        return true;
    } else {
        console.log("非微博环境");
        return false;
    }

}

// 判断Safari环境
export function isSafari() {
    var ua = window.navigator.userAgent.toLowerCase();
    if ((/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent))) {
        console.log("Safari环境");
        return true;
    } else {
        console.log("非Safari环境");
        return false;
    }

}

//是否为安卓
export function isAndriod() {
    var naviga = navigator.userAgent;
    if (naviga.indexOf('Android') > -1 || naviga.indexOf('Adr') > -1) {
        console.log("Andriod环境");
        return true;
    } else {
        console.log("非Andriod环境");

        return false;

    }
}
//路径获取关键字
export function getQueryString(name) {
    //截取页面传递字符串
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

// 判断全面屏和非全面屏，true为全面屏 
export function judgeBigScreen() {
    let result = false;
    const rate = window.screen.height / window.screen.width;
    let limit = window.screen.height == window.screen.availHeight ? 1.8 : 1.65; // 临界判断值 
    // window.screen.height为屏幕高度
    // window.screen.availHeight 为浏览器 可用高度
    if (rate > limit) {
        // console.log("全面屏");

        result = true;
        return result;
    }
    // console.log("非面屏");
    return result;
}

// 获取url html名称
export function getUrlHtml() {
    //获取url地址
    var ts_href = window.location.href;
    var ts_mainText = "";
    //获取地址最后一个“/”的下标
    var ts_indexof = ts_href.lastIndexOf("/");
    //获取地址“/”之后的的内容
    var ts_indexText = ts_href.substring(ts_indexof + 1);
    //获取地址“.html”的下标
    var ts_htmlBeforeText = ts_indexText.indexOf(".html");
    //获取 “/”到".html"之间的内容
    ts_mainText = ts_indexText.substring(0, ts_htmlBeforeText);

    console.log("当前入口：", ts_mainText);
    return ts_mainText;

}

// 获取cookie中的值
export function getSetCookie(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};

        if (value === null) {
            value = '';
            options = this._extend({}, options, true);
            options.expires = -1;
        }

        var expires = '';

        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;

            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + options.expires * 24 * 60 * 60 * 1000);
            } else {
                date = options.expires;
            }

            expires = '; expires=' + date.toUTCString();
        }

        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;

        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');

            for (var i = 0; i < cookies.length; i++) {
                // var cookie = $.trim(cookies[i]);
                var cookie = cookies[i].trim();

                if (cookie.substring(0, name.length + 1) == name + '=') {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }

        return cookieValue;
    }
}

// 安卓机型自动播放音乐
export function BGMAutoPlayMgr(url) {
    this.audioContext = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
    this.sourceNode = null;
    this.buffer = null;
    this.isPlayingBGM = false;
    this.toggleBGM = function () {
        if (typeof this.sourceNode == 'object') {
            if (this.isPlayingBGM) {
                this.sourceNode.stop();
                this.isPlayingBGM = false;
            } else this._playSourceNode();
        }
    }
    this._playSourceNode = function () {
        const audioContext = this.audioContext;
        audioContext.resume();
        const _sourceNode = audioContext.createBufferSource();
        _sourceNode.buffer = this.buffer;
        _sourceNode.loop = true;
        _sourceNode.connect(audioContext.destination);
        _sourceNode.start(0);
        this.sourceNode = _sourceNode;
        this.isPlayingBGM = true;
    }
    let loadAndAutoPlay = (audioUrl) => {
        const audioContext = this.audioContext;
        const xhr = new XMLHttpRequest();
        xhr.open('GET', audioUrl, true);
        xhr.responseType = 'arraybuffer';
        xhr.onreadystatechange = () => {
            if (xhr.status < 400 && xhr.status >= 200 && xhr.readyState === 4) {
                audioContext.decodeAudioData(xhr.response, buffer => {
                    this.buffer = buffer;
                    WeixinJSBridge.invoke("getNetworkType", {}, () => this._playSourceNode());
                });
            }
        }
        xhr.send();
    }
    loadAndAutoPlay(url);
    loadAndAutoPlay = null;
}

// 金管家获取openid及openToken
export function getJGJId() {
    return new Promise(resolve => {
        // 获取openid
        PALifeOpen.getOpenId(
            {
                appId: '1aeedce2a31340e591a5d64080d6105b'  // 商户编号，区分⽣产和测试环境商户编号
            },
            rsp => {
                // 调⽤接⼝成功后的回调函数
                console.log('success', rsp.data);
                store.state.openId = rsp.data.openId
                store.state.openToken = rsp.data.openToken
                if (rsp.ret == 0) {
                    store.state.openId = rsp.data.openId
                    store.state.openToken = rsp.data.openToken
                    const data = {
                        id: store.state.openId,
                        token: store.state.openToken
                    };
                    resolve(data);
                    // console.log(`获取到金管家openid时间：${Math.abs(s_t - new Date().getTime())}`);
                }
                if (rsp.ret == -1) {
                    console.log(JSON.stringify(rsp));
                }
            },
            e => {
                // 调⽤接⼝异常的回调函数
                console.log('failed', e);
            }
        )
    })
}

// 金管家内部埋点
export function addPoint(page, spage, des = {}) {
    const activityId = process.env.VUE_APP_ACTIVITYID;
    PALifeOpen.invoke(
        "device",
        "addRecord",
        {
            eventId: `499${page}-${activityId}`, //必填，根据需求
            labelId: `499${page}${spage}-${activityId}`, //必填，根据需求
            // 扩展参数
            parameters: {
                ext: JSON.stringify(des)
            }
        },
        // 调用接口成功后的回调函数   // alert(JSON.stringify(rsp))
        rsp => console.debug("success ", rsp),
        // 调用接口异常的回调函数
        e => console.debug("failed ", e),
        {
            timeout: 86400000
        }
    );
    return this;
}

// 百度统计埋点
export function addPointByBd(des) {
    _hmt && _hmt.push(["_trackEvent", `${des}`, `${des} success`]);
    return this;
}

// 防抖函数
export function debounceTap(target, callbacks, timeScale = 1) {
    if (!btnEnable.value) return false
    btnEnable.value = false;
    let createAni = () => {
        let timeline = new gsap.timeline({
            onStart: () => {
                sound.play()
            },
            onComplete: () => {
                callbacks && callbacks();
                btnEnable.value = true;
                timeline.kill();
            }
        });
        timeline
            .to(target, { duration: timeScale * 0.2, scale: 0.8, })
            .to(target, { duration: timeScale * 0.5, scale: 1, })
    }
    createAni();
}

// 节流函数
export function throttle(fn, wait) {
    let inThrottle = false
    return (...args) => {
        // @ts-ignore
        const context = this
        if (!inThrottle) {
            inThrottle = true
            fn.apply(context, args)
            setTimeout(() => {
                inThrottle = false
            }, wait)
        }
    }
}


// vite环境引用图片
export function imgUrl(url) {
    return new URL(`../assets/images/${url}`, import.meta.url).href
}

// 计算两个日期之间的天数(开始日期,结束日期)
export function getDaysBetween(date1, date2) {
    let day1 = new Date(date1.join('-'))
    let day2 = new Date(date2.join('-'))
    let oneDay = 24 * 60 * 60 * 1000;
    let diffDays = Math.round(Math.abs((day2 - day1) / oneDay));
    return diffDays;
}

// 计算星座
export function getAstro(month, day) {
    var s = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
    var arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22];
    return s.substr(month * 2 - (day < arr[month - 1] ? 2 : 0), 2);
}

// 洗牌算法：打乱数组顺序
export function FYShuffle(arr) {
    let len = arr.length;

    while (len > 1) {
        let rand = Math.floor(Math.random() * len);
        len--;
        [arr[len], arr[rand]] = [arr[rand], arr[len]] // 采用的数组的结构赋值
    }

    return arr;
}


// 选出数组中出现次数最多的值
export function mostValue(arr) {
    // 创建一个空对象用于存储值及其出现的次数  
    let counter = {};

    // 遍历数组中的每个元素  
    for (let i = 0; i < arr.length; i++) {
        // 如果值已经在counter对象中，增加其计数  
        // 如果值不在counter对象中，设置计数为1  
        if (counter[arr[i]]) {
            counter[arr[i]]++;
        } else {
            counter[arr[i]] = 1;
        }
    }

    // 找出出现次数最多的值及其出现的次数  
    let mostFrequentValue = null;
    let maxCount = 0;
    for (let key in counter) {
        if (counter[key] > maxCount) {
            mostFrequentValue = key;
            maxCount = counter[key];
        }
    }

    // 返回出现次数最多的值和其出现的次数  
    return { value: mostFrequentValue, count: maxCount };
}


// 海报生成
export function posterCreate(option, imageArr, textArr, theme,eqcode) {
    let posterUrl = ''
    const { width, height } = option
    Toast.loading({
        message: '海报生成中',
        duration: 0,
        forbidClick: true
    })
    console.log('theme', theme);

    let mycanvas = document.createElement('canvas') // 创建一个canvas画布元素 
    let ctx = mycanvas.getContext('2d')
    mycanvas.style.width = '750px'; //设置canvas的宽
    mycanvas.style.height = '1500px'; //设置canvas的高
    mycanvas.width = width
    mycanvas.height = height
    console.log('imgs:', imageArr);
    //Promise对象加载资源
    let loader_p = [];
    imageArr.map((item) => {
        const _p = new Promise(resolve => {
            const img = new Image();
            img.crossOrigin = 'Anonymous'
            img.onload = () => {
                resolve(img)
            };
            img.src = item.src;
        });
        loader_p.push(_p);
    })
    //Promise的.all方法，当所有预加载的图像加载好的回调函数 
    Promise.all(loader_p)
        .then(imgList => {

            imgList.map((item, index) => {
                // console.log('item',imageArr[index]);
                if (imageArr[index].name != 'eqcode') {
                ctx.drawImage(item, imageArr[index].pos.x, imageArr[index].pos.y, imageArr[index].pos.w, imageArr[index].pos.h); //原生canvas的绘制图片方法，直接百度搜索 `js drawImage`查看方法的参数
                    
                }
            })

            ctx.rotate(-4.3 * (Math.PI / 180));

            // console.log('imgList[2]',imgList[2]);
            ctx.drawImage(imgList[2], imageArr[2].pos.x, imageArr[2].pos.y, imageArr[2].pos.w, imageArr[2].pos.h)

            // 画签文
            // ctx.rotate(-4 * (Math.PI / 180));
            ctx.textAlign = 'start'; //type2
            ctx.textBaseline = 'top'
            textArr.map((item, index) => {
                const { x, y } = textArr[index].style.pos
                ctx.font = textArr[index].style.font; // normal bold

                // title绘制描边
                if (index == 0) {
                    ctx.lineWidth = 5
                    ctx.strokeStyle = 'white'
                    ctx.strokeText(textArr[index].content, x, y);
                }


                ctx.fillStyle = textArr[index].style.color ? textArr[index].style.color : theme; //原生canvas的绘制文字方法,属性类似css，确定好文字颜色、粗细、字号、字体、对齐方式
                ctx.fillText(textArr[index].content, x, y); //绘制文字
            })

            


            //海报绘制完 ，转成图片对象
            return mycanvas.toDataURL('image/jpeg', 1);
        })
        .then(baseURL => {
            //返回的图片地址，就是最后海报的地址，可以放在DOM显示
            let posterImg = document.querySelector('#poster')
            posterImg.src = baseURL
            setTimeout(() => {
                Toast.success({ message: '生成成功！' })
                gsap.to('.posterPop', { duration: 0.5, autoAlpha: 1 })

            }, 500)
        })

    return posterUrl
}