export function getPosByAngle(angle, len) {

    const radian = angle * Math.PI / 180;
    const x = Math.sin(radian) * len;
    const y = Math.cos(radian) * len;

    return { x, y };

}

export function getAngleByPos(px, py, mx, my) {

    const x = Math.abs(px - mx);
    const y = Math.abs(py - my);

    const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
    const cos = y / z;
    const radina = Math.acos(cos); // 用反三角函数求弧度
    let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度

    if (mx > px && my > py) {// 鼠标在第四象限
        angle = 180 - angle;
    }
    if (mx === px && my > py) {// 鼠标在y轴负方向上
        angle = 180;
    }
    if (mx > px && my === py) {// 鼠标在x轴正方向上
        angle = 90;
    }
    if (mx < px && my > py) {// 鼠标在第三象限
        angle = 180 + angle;
    }
    if (mx < px && my === py) {// 鼠标在x轴负方向
        angle = 270;
    }
    if (mx < px && my < py) {// 鼠标在第二象限
        angle = 360 - angle;
    }

    // console.log('angle: ', angle);
    return angle;

}

export function exchangeNodePos(baseNode, targetNode) {
    return baseNode.convertToNodeSpaceAR(targetNode._parent.convertToWorldSpaceAR(cc.v2(targetNode.x, targetNode.y)));
}

export function RandomInt(a, b = 0) {
    let max = Math.max(a, b);
    let min = Math.min(a, b);
    return Math.floor(Math.random() * (max - min) + min);
}

export function Between(a, b, c) {
    return [a, b, c].sort((a, b) => a - b)[1];
}

export function randomSortByArr(arr) {
    const newArr = [];
    const tmpArr = arr.concat();
    while (tmpArr.length > 0) {
        const randomIndex = Math.floor(tmpArr.length * Math.random());
        newArr.push(tmpArr[randomIndex]);
        tmpArr.splice(randomIndex, 1);
    }
    return newArr;
}

export async function asyncTweenTo(node, duration, obj, ease = undefined) {
    return new Promise((resolve, reject) => {
        cc.tween(node)
            .to(duration, obj, ease)
            .call(() => {
                resolve();
            })
            .start();
    });
}

export async function asyncPlayDragonBoneAnimation(node, animationName, time = 1) {
    return new Promise((resolve, reject) => {
        node.getComponent(dragonBones.ArmatureDisplay)
            .once(dragonBones.EventObject.COMPLETE, () => {
                resolve();
            });
        node.getComponent(dragonBones.ArmatureDisplay)
            .playAnimation(animationName, time);
    });
}

export async function asyncPlayEffectByUrl(url, loop = false) {
    return new Promise((resolve, reject) => {
        cc.assetManager.loadRemote(url, (err, clip) => {
            console.log(clip);
            cc.audioEngine.playEffect(clip, loop);
        });
    });
}

export async function jelly(node) {
    return new Promise((resolve, reject) => {
        cc.tween(node)
            .to(0.1, { scaleX: 0.9, scaleY: 1.1 })
            .to(0.1, { scaleX: 1.1, scaleY: 0.9 })
            .to(0.1, { scaleX: 1, scaleY: 1 })
            .call(resolve)
            .start();
    });
}

// YYYY-mm-dd HH:MM表示2019-06-06 19:45
export function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}

export function formatSeconds(value) {
    var theTime = parseInt(value);// 秒
    var theTime1 = 0;// 分
    var theTime2 = 0;// 小时
    if (theTime > 60) {
        theTime1 = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (theTime1 > 60) {
            theTime2 = parseInt(theTime1 / 60);
            theTime1 = parseInt(theTime1 % 60);
        }
    }

    var result = "" + parseInt(theTime);//秒
    if (10 > theTime > 0) {
        result = "0" + parseInt(theTime);//秒
    } else {
        result = "" + parseInt(theTime);//秒
    }

    if (10 > theTime1 > 0) {
        result = "0" + parseInt(theTime1) + ":" + result;//分，不足两位数，首位补充0，
    } else {
        result = "" + parseInt(theTime1) + ":" + result;//分
    }
    if (theTime2 > 0) {
        result = "" + parseInt(theTime2) + ":" + result;//时
    }
    return result;
}

export async function http(type, url, data) {
    console.log(' in http ');
    console.log(' type: ', type);
    console.log(' url: ', url);
    console.log(' data: ', data);

    return new Promise((resolve, reject) => {

        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                console.log(response);
                resolve(response)
            } else {
                console.log('xhr: ', xhr);
            }
        };
        xhr.open(type, url, true);
        xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        xhr.send(JSON.stringify(data));
    });
}
