import { NetManager } from "../libs/tw/manager/NetManager";
import { DataManager } from "../libs/tw/manager/DataManager";

const getToken = () => {
    return new Promise((r) => {
        const oauth_consumer_key = 'DBAndroidClient';
        const clientid = 'AndroidClient';
        const clientsecret = '123456';
        const oauth_consumer_secret = '12e390c3d9c1469c7ad9799cdc471e82';
        const sign = window['duiba_md5'](oauth_consumer_key + clientid + clientsecret + oauth_consumer_secret).toUpperCase();
        const sendData = {
            oauth_consumer_key: oauth_consumer_key,
            oauth_consumer_sig: sign,
            clientid: clientid,
            reqEncryptType: "-1",
            clientsecret: clientsecret
        };
        window['$'].ajax({
            url: "https://csapi.tingmall.com/ContentServiceWS/OAuth/getAccessTokenSig",
            type: 'get',
            async: true,//异步请求
            cache: false,
            contentType: "application/x-www-form-urlencoded",
            data: sendData,//使用变量sendData
            //执行成功的回调函数
            success: (data) => {
                r(data.response.docs.access_token);
            },
            //执行失败或错误的回调函数
            error: (data) => {
                console.log("认证失败");
            }
        });
    })

}

const getCategoryItem = (oauth_token, categoryid) => {
    return new Promise((r) => {
        const sendData = {
            categoryid: categoryid
        };
        window['$'].ajax({
            url: "https://csapi.tingmall.com/ContentServiceWS/CategoryExInfo/getCategoryItem",
            type: 'get',
            async: true,//异步请求
            cache: false,
            contentType: "application/x-www-form-urlencoded",
            data: sendData,//使用变量sendData
            //执行成功的回调函数
            success: (data) => {
                r(data);
            },
            //执行失败或错误的回调函数
            error: (data) => {
                console.log("认证失败");
            },
            beforeSend: (xhr) => {
                xhr.setRequestHeader("oauth_token", oauth_token);
            }
        });
    });
}

const requestMusicUrl = (oauth_token, itemid, songlistid) => {
    const date = new Date();
    const y = date.getFullYear();
    const m = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1);
    const d = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate();
    const h = date.getHours() >= 10 ? date.getHours() : '0' + date.getHours();
    const min = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes();
    const ms = date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds();
    const startdate = `${y}-${m}-${d}T${h}:${min}:${ms}Z`;
    const enddate = `${y + 1}-${m}-${d}T00:00:00Z`;
    console.log(startdate, enddate);
    return new Promise((r) => {
        const sendData = {
            apimode: "2",
            uid: CFG.uid,
            eventmode: "1Y",
            itemid: itemid,
            startdate: startdate,
            enddate: enddate,
            songlistid: songlistid
        };
        window['$'].ajax({
            url: "https://csapi.tingmall.com/ContentServiceWS/H5EventInfo/requestMusicUrl",
            type: 'get',
            async: true,//异步请求
            cache: false,
            contentType: "application/x-www-form-urlencoded",
            data: sendData,//使用变量sendData
            //执行成功的回调函数
            success: (data) => {
                r(data);
            },
            //执行失败或错误的回调函数
            error: (data) => {
                console.log("认证失败");
            },
            beforeSend: (xhr) => {
                xhr.setRequestHeader("oauth_token", oauth_token);
            }
        });
    });
}
const getKey = () => {
    return `qqtme-${DataManager.ins.customCfgData.actId}`
};
let _songListId = 0;
let _songId = 0;
let _songDuration = 0;
//播放循环结束的时候发接口，上线的时候发接口
let times = 0;
let timer = -1;
let _bitrate;
export const doRecord = () => {
    if (!_ele || !_songDuration) return;
    if (timer == -1) timer = Date.now();
    const secondsPassed = Math.floor((Date.now() - timer) / 1000);
    const data = {
        durationOfPlay: _songDuration * times + secondsPassed,
        songListId: _songListId,
        songId: _songId,
        playCount: times,
        bitrate: _bitrate,
        songDuration: _songDuration
    }
    localStorage.setItem(getKey(), JSON.stringify(data));
};

export const sendLastData = () => {
    let data: any = localStorage.getItem(getKey());
    if (!data) return;
    localStorage.removeItem(getKey());
    if (data) data = JSON.parse(data);

    const date = new Date();
    const y = date.getFullYear();
    const m = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1);
    const d = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate();
    const h = date.getHours() >= 10 ? date.getHours() : '0' + date.getHours();
    const min = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes();
    const ms = date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds();
    const timestamp = `${y}-${m}-${d} ${h}:${min}:${ms}`;

    NetManager.ins.reportMusic(() => { }, data.durationOfPlay, data.songListId, data.songId,
        data.playCount, timestamp, data.bitrate, data.songDuration);
}

const sendDataOnLoopEnd = () => {
    const date = new Date();
    const y = date.getFullYear();
    const m = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1);
    const d = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate();
    const h = date.getHours() >= 10 ? date.getHours() : '0' + date.getHours();
    const min = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes();
    const ms = date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds();
    const startdate = `${y}-${m}-${d} ${h}:${min}:${ms}`;

    const durationOfPlay = _songDuration * times;
    const songListId = _songListId;
    const songId = _songId;;
    const playCount = times;
    const timestamp = startdate;
    const bitrate = _bitrate = getBitrate(window['musciURL']);
    const songDuration = _songDuration;
    NetManager.ins.reportMusic(() => { }, durationOfPlay, songListId, songId,
        playCount, timestamp, bitrate, songDuration);

};

const getBitrate = (url: string) => {
    if (url.indexOf('MP3-512K-FTD') != -1) return 512;
    if (url.indexOf('MP3-256K-FTD') != -1) return 256;
    return 128;
}
let _ele;
// export const setSongDuration = () => {
//     _songDuration = Math.floor(_ele.duration);
// }
export default () => {
    return new Promise(async (r) => {
        NetManager.ins.getMusicCategory((success, result) => {
            const songListId = _songListId = result.data.categoryID;
            const itemid = _songId = result.data.stationItems[0].itemID;
            NetManager.ins.getMusicItem((success, result) => {
                const url = result.data.playURL;
                const ele = document.createElement('audio');
                ele.setAttribute('autoplay', '');
                ele.setAttribute('preload', '');
                ele.setAttribute('id', 'bgmusic');
                ele.setAttribute('src', url);
                ele.loop = false;
                _ele = ele;

                // setInterval(()=>{_songDuration = Math.floor(_ele.duration);},1000);
                ele.oncanplay = () => {
                    _songDuration = Math.floor(_ele.duration);
                }
                ele.addEventListener('ended', () => {
                    times++;
                    timer = Date.now();
                    doRecord();
                    sendDataOnLoopEnd();
                    ele.play();
                }, false);


                window['musciURL'] = url;
                _bitrate = getBitrate(window['musciURL'])
                document.body.append(ele);

            }, songListId, itemid);
        }, window['categoryid']);

    })
}