/*
领京豆额外奖励&抢京豆
脚本自带助力码，介意者可将 29行 helpAuthor 变量设置为 false
活动入口：京东APP首页-领京豆
更新地址：https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_home.js
已支持IOS双京东账号, Node.js支持N个京东账号
脚本兼容: QuantumultX, Surge, Loon, 小火箭，JSBox, Node.js
============Quantumultx===============
[task_local]
#领京豆额外奖励
10 7 * * * https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_home.js, tag=领京豆额外奖励, img-url=https://raw.githubusercontent.com/58xinian/icon/master/jd_bean_home.png, enabled=true

================Loon==============
[Script]
cron "10 7 * * *" script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_home.js, tag=领京豆额外奖励

===============Surge=================
领京豆额外奖励 = type=cron,cronexp="10 7 * * *",wake-system=1,timeout=3600,script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_home.js

============小火箭=========
领京豆额外奖励 = type=cron,script-path=https://gitee.com/lxk0301/jd_scripts/raw/master/jd_bean_home.js, cronexpr="10 7 * * *", timeout=3600, enable=true
 */
const notify = $.isNode() ? require('./sendNotify') : '';
//Node.js用户请在jdCookie.js处填写京东ck;
const jdCookieNode = $.isNode() ? require('./jdCookie.js') : '';
let jdNotify = true;//是否关闭通知，false打开通知推送，true关闭通知推送
const helpAuthor = false; // 是否帮助作者助力，false打开通知推送，true关闭通知推送
//IOS等用户直接用NobyDa的jd cookie
let cookiesArr = [], cookie = '', message = "";
let newShareCodes = []
let roleMap = {
    "jd_4521b375ebb5d": "锟子怪",
    "jd_542c10c0222bc": "康子怪",
    "jd_66dcb31363ef6": "涛子怪",
    "jd_45d917547c763": "跑腿小怪",
    "417040678_m": "斌子怪",
    "jd_73d88459d908e": "杰杰子",
    "381550701lol": "漪漪子",
    "jd_4333d5dc1ac5f": "舒楠子",
    "jd_66ea783827d30": "军子",
    "jd_4311ac0ff4456": "居子"
}
let dingtalk = "https://oapi.dingtalk.com/robot/send?access_token=d2b6042cb38f0df63e20797c002208d2710104750c18a1dc84d54106a859a3f0"
let username = ""


if ($.isNode()) {
    Object.keys(jdCookieNode).forEach((item) => {
        cookiesArr.push(jdCookieNode[item])
    })
    if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') that.log = () => {
    };
} else {
    cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jsonParse($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item);
}
const JD_API_HOST = 'https://api.m.jd.com/';
!(async () => {

    if (!cookiesArr[0]) {
        $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/bean/signIndex.action', { "open-url": "https://bean.m.jd.com/bean/signIndex.action" });
        return;
    }
    message += "<font color=\'#FFA500\'>[通知] </font><font color=\'#006400\' size='3'>额外领京豆</font> \n\n"

    for (let i = 0; i < cookiesArr.length; i++) {
        if (cookiesArr[i]) {
            cookie = cookiesArr[i];
            $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1])
            $.index = i + 1;
            $.isLogin = true;
            $.nickName = '';
            await TotalBean();

            if (roleMap[username] != undefined) {
                username = roleMap[username]
            }
            //加上名称
            message = message + "<font color=\'#778899\' size=2>【羊毛姐妹】<font color=\'#FFA500\' size=3>" + username + " </font> </font> \n\n "

            that.log(`\n******开始【京东账号${$.index}】${$.nickName || $.UserName}*********\n`);
            if (!$.isLogin) {
                $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, { "open-url": "https://bean.m.jd.com/bean/signIndex.action" });

                if ($.isNode()) {
                    await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`);
                }
                continue
            }
            await jdBeanHome();
        }

        message += "----\n\n"
    }

    console.log(message)
    postToDingTalk(message)
    message = "<font color=\'#FFA500\'>[通知] </font><font color=\'#006400\' size='3'>额外领京豆</font> \n\n"

    for (let i = 0; i < cookiesArr.length; i++) {
        if (cookiesArr[i]) {
            cookie = cookiesArr[i];
            $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1])
            that.log(`${$.UserName}去帮助下一个人`)
            cookie = cookiesArr[i];
            for (let j = 0; i < newShareCodes.length; j++) {
                let code = newShareCodes[j]
                await help(code[0], code[1])
            }
        }
    }
})()
    .catch((e) => {
        $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '')
    })
    .finally(() => {

        console.log(message)
        postToDingTalk(message)
        $.done();
    })

async function jdBeanHome() {
    $.doneState = false
    do {
        await doTask2()
        await $.wait(3000)
    } while (!$.doneState)
    await $.wait(1000)
    await award("feeds")
    await $.wait(1000)
    await getUserInfo()
    await $.wait(1000)
    await getTaskList();
    await receiveJd2();
    await showMsg();
}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min;
}
function doTask2() {
    return new Promise(resolve => {
        const body = { "awardFlag": false, "skuId": `${getRandomInt(10000000, 20000000)}`, "source": "feeds", "type": '1' };
        $.post(taskUrl('beanHomeTask', body), (err, resp, data) => {
            try {
                if (err) {
                    that.log(`${JSON.stringify(err)}`)
                    that.log(`${$.name} API请求失败，请检查网路重试`)
                } else {
                    if (safeGet(data)) {
                        data = JSON.parse(data);
                        if (data.code === '0' && data.data) {
                            that.log(`任务完成进度：${data.data.taskProgress} / ${data.data.taskThreshold}`)
                            if (data.data.taskProgress === data.data.taskThreshold)
                                $.doneState = true
                        } else if (data.code === '0' && data.errorCode === 'HT201') {
                            $.doneState = true
                        } else {
                            //HT304风控用户
                            $.doneState = true
                            that.log(`做任务异常：${JSON.stringify(data)}`)
                        }
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve();
            }
        })
    })
}


function getUserInfo() {
    return new Promise(resolve => {
        let body = {}
        $.post(taskUrl('signBeanGroupStageIndex', body), async (err, resp, data) => {
            try {
                if (err) {
                    that.log(`${JSON.stringify(err)}`)
                    that.log(`${$.name} API请求失败，请检查网路重试`)
                } else {
                    if (safeGet(data)) {
                        data = JSON.parse(data);
                        if (data.data.jklInfo) {
                            $.actId = data.data.jklInfo.keyId
                            let { shareCode, groupCode } = data.data
                            if (!shareCode) {
                                that.log(`未获取到助力码，去开团`)
                                await hitGroup()
                            } else {
                                that.log(shareCode, groupCode)
                                // 去做逛会场任务
                                if (data.data.beanActivityVisitVenue && data.data.beanActivityVisitVenue.taskStatus === '0') {
                                    await help(shareCode, groupCode, 1)
                                }
                                newShareCodes.push([shareCode, groupCode])
                            }
                        }
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve();
            }
        })
    })
}

function hitGroup() {
    return new Promise(resolve => {
        const body = { "activeType": 2, };
        $.get(taskGetUrl('signGroupHit', body), async (err, resp, data) => {
            try {
                if (err) {
                    that.log(`${JSON.stringify(err)}`)
                    that.log(`${$.name} API请求失败，请检查网路重试`)
                } else {
                    if (safeGet(data)) {
                        data = JSON.parse(data);
                        if (data.data.respCode === "SG150") {
                            let { shareCode, groupCode } = data.data.signGroupMain
                            if (shareCode) {
                                newShareCodes.push([shareCode, groupCode])
                                that.log('开团成功')
                                await help(shareCode, groupCode, 1)
                            } else {
                                that.log(`为获取到助力码，错误信息${JSON.stringify(data.data)}`)
                            }
                        } else {
                            that.log(`开团失败，错误信息${JSON.stringify(data.data)}`)
                        }
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve();
            }
        })
    })
}

function help(shareCode, groupCode, isTask = 0) {
    return new Promise(resolve => {
        const body = {
            "activeType": 2,
            "groupCode": groupCode,
            "shareCode": shareCode,
            "activeId": $.actId,
        };
        if (isTask) {
            that.log(`【抢京豆】做任务获取助力`)
            body['isTask'] = "1"
        } else {
            that.log(`【抢京豆】去助力好友${shareCode}`)

            body['source'] = "guest"
        }
        $.get(taskGetUrl('signGroupHelp', body), async (err, resp, data) => {
            try {
                if (err) {
                    that.log(`${JSON.stringify(err)}`)
                    that.log(`【抢京豆】${$.name} API请求失败，请检查网路重试`)
                } else {
                    if (safeGet(data)) {
                        data = JSON.parse(data);
                        that.log(`【抢京豆】${data.data.helpToast}`)
                        message = message + "<font color=\'#778899\' size=2>【羊毛姐妹】<font color=\'#FFA500\' size=3>" + `【抢京豆】去助力好友${shareCode}` + " </font> </font> \n\n "
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve(data);
            }
        })
    })
}

function showMsg() {
    return new Promise(resolve => {
        if (message) $.msg($.name, '', `【京东账号${$.index}】${$.nickName}\n${message}`);
        resolve()
    })
}

function getTaskList() {
    return new Promise(resolve => {
        const body = { "rnVersion": "4.7", "rnClient": "2", "source": "AppHome" };
        $.post(taskUrl('findBeanHome', body), async (err, resp, data) => {
            try {
                if (err) {
                    that.log(`${JSON.stringify(err)}`)
                    that.log(`${$.name} API请求失败，请检查网路重试`)
                } else {
                    if (safeGet(data)) {
                        data = JSON.parse(data);
                        let beanTask = data.data.floorList.filter(vo => vo.floorName === "种豆得豆定制化场景")[0]
                        if (!beanTask.viewed) {
                            await receiveTask()
                            await $.wait(3000)
                        }

                        let tasks = data.data.floorList.filter(vo => vo.floorName === "赚京豆")[0]['stageList']
                        for (let i = 0; i < tasks.length; ++i) {
                            const vo = tasks[i]
                            if (vo.viewed) continue
                            await receiveTask(vo.stageId, `4_${vo.stageId}`)
                            await $.wait(3000)
                        }
                        await award()
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve();
            }
        })
    })
}

function receiveTask(itemId = "zddd", type = "3") {
    return new Promise(resolve => {
        const body = { "awardFlag": false, "itemId": itemId, "source": "home", "type": type };
        $.post(taskUrl('beanHomeTask', body), (err, resp, data) => {
            try {
                if (err) {
                    that.log(`${JSON.stringify(err)}`)
                    that.log(`${$.name} API请求失败，请检查网路重试`)
                } else {
                    if (safeGet(data)) {
                        data = JSON.parse(data);
                        if (data.data) {
                            that.log(`完成任务成功，进度${data.data.taskProgress}/${data.data.taskThreshold}`)
                        } else {
                            that.log(`完成任务失败，${data.errorMessage}`)
                        }
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve();
            }
        })
    })
}


function award(source = "home") {
    return new Promise(resolve => {
        const body = { "awardFlag": true, "source": source };
        $.post(taskUrl('beanHomeTask', body), (err, resp, data) => {
            try {
                if (err) {
                    that.log(`${JSON.stringify(err)}`)
                    that.log(`${$.name} API请求失败，请检查网路重试`)
                } else {
                    if (safeGet(data)) {
                        data = JSON.parse(data);
                        if (data.data) {
                            that.log(`领奖成功，获得 ${data.data.beanNum} 个京豆`)
                            message += "<font color=\'#FFA500\'>" + `领奖成功，获得 ${data.data.beanNum} 个京豆\n` + "</font> \n\n"

                        } else {
                            that.log(`领奖失败，${data.errorMessage}`)
                            // message += `领奖失败，${data.errorMessage}\n`
                        }
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve();
            }
        })
    })
}
function receiveJd2() {
    var headers = {
        'Host': 'api.m.jd.com',
        'content-type': 'application/x-www-form-urlencoded',
        'accept': '*/*',
        'user-agent': 'JD4iPhone/167515 (iPhone; iOS 14.2; Scale/3.00)',
        'accept-language': 'zh-Hans-JP;q=1, en-JP;q=0.9, zh-Hant-TW;q=0.8, ja-JP;q=0.7, en-US;q=0.6',
        'Cookie': cookie
    };
    var dataString = 'body=%7B%7D&build=167576&client=apple&clientVersion=9.4.3&openudid=53f4d9c70c1c81f1c8769d2fe2fef0190a3f60d2&osVersion=14.2&partner=TF&rfs=0000&scope=10&screen=1242%2A2208&sign=19c33b5b9ad4f02c53b6040fc8527119&st=1614701322170&sv=122'
    var options = {
        url: 'https://api.m.jd.com/client.action?functionId=sceneInitialize',
        headers: headers,
        body: dataString
    };
    return new Promise(resolve => {
        $.post(options, (err, resp, data) => {
            try {
                if (err) {
                    that.log(`${JSON.stringify(err)}`)
                    that.log(`${$.name} API请求失败，请检查网路重试`)
                } else {
                    if (safeGet(data)) {
                        data = JSON.parse(data);
                        if (data['code'] === '0' && data['data']) {
                            that.log(`强制开启新版领京豆成功,获得${data['data']['sceneLevelConfig']['beanNum']}京豆\n`);
                            $.msg($.name, '', `强制开启新版领京豆成功\n获得${data['data']['sceneLevelConfig']['beanNum']}京豆`);
                        } else {
                            that.log(`强制开启新版领京豆结果:${JSON.stringify(data)}\n`)
                        }
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve();
            }
        })
    })
}
function taskGetUrl(function_id, body) {
    return {
        url: `${JD_API_HOST}client.action?functionId=${function_id}&body=${escape(JSON.stringify(body))}&appid=ld&clientVersion=9.2.0`,
        headers: {
            'Cookie': cookie,
            'Host': 'api.m.jd.com',
            'Accept': '*/*',
            'Connection': 'keep-alive',
            'User-Agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1"),
            'Accept-Language': 'zh-Hans-CN;q=1,en-CN;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Content-Type': "application/x-www-form-urlencoded"
        }
    }
}


function taskUrl(function_id, body) {
    body["version"] = "9.0.0.1";
    body["monitor_source"] = "plant_app_plant_index";
    body["monitor_refer"] = "";
    return {
        url: JD_API_HOST,
        body: `functionId=${function_id}&body=${escape(JSON.stringify(body))}&appid=ld&client=apple&area=5_274_49707_49973&build=167283&clientVersion=9.1.0`,
        headers: {
            'Cookie': cookie,
            'Host': 'api.m.jd.com',
            'Accept': '*/*',
            'Connection': 'keep-alive',
            'User-Agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1"),
            'Accept-Language': 'zh-Hans-CN;q=1,en-CN;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Content-Type': "application/x-www-form-urlencoded"
        }
    }
}

function TotalBean() {
    return new Promise(async resolve => {
        const options = {
            "url": `https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2`,
            "headers": {
                "Accept": "application/json,text/plain, */*",
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept-Encoding": "gzip, deflate, br",
                "Accept-Language": "zh-cn",
                "Connection": "keep-alive",
                "Cookie": cookie,
                "Referer": "https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2",
                "User-Agent": $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1")
            }
        }
        $.post(options, (err, resp, data) => {
            try {
                if (err) {
                    that.log(`${JSON.stringify(err)}`)
                    that.log(`${$.name} API请求失败，请检查网路重试`)
                } else {
                    if (data) {
                        data = JSON.parse(data);
                        if (data['retcode'] === 13) {
                            $.isLogin = false; //cookie过期
                            return
                        }
                        if (data['retcode'] === 0) {
                            $.nickName = (data['base'] && data['base'].nickname) || $.UserName;
                        } else {
                            $.nickName = $.UserName
                        }
                    } else {
                        that.log(`京东服务器返回空数据`)
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve();
            }
        })
    })
}

function safeGet(data) {
    try {
        if (typeof JSON.parse(data) == "object") {
            return true;
        }
    } catch (e) {
        that.log(e);
        that.log(`京东服务器访问数据为空，请检查自身设备网络情况`);
        return false;
    }
}
function jsonParse(str) {
    if (typeof str == "string") {
        try {
            return JSON.parse(str);
        } catch (e) {
            that.log(e);
            $.msg($.name, '', '请勿随意在BoxJs输入框修改内容\n建议通过脚本去获取cookie')
            return [];
        }
    }
}



//我加的函数
function postToDingTalk(messgae) {
    const message1 = "" + messgae
    // that.log(messgae)

    const body = {
        "msgtype": "markdown",
        "markdown": {
            "title": "签到领现金",
            "text": message1
        },
        "at": {
            "atMobiles": [],
            "isAtAll": false
        }
    }


    $.post(toDingtalk(dingtalk, JSON.stringify(body)), (data, status, xhr) => {
        try {
            that.log(resp)
            that.log(data)
            if (err) {
                that.log(JSON.stringify(err));
                $.logErr(err);
            } else {
                if (safeGet(data)) {
                    $.duckRes = JSON.parse(data);
                }
            }
        } catch (e) {
            $.logErr(e, resp)
        } finally {
            resolve();
        }
    }, "json")
}


function toDingtalk(urlmain, bodyMain) {
    return {
        url: urlmain,
        body: bodyMain,
        headers: { 'Content-Type': 'application/json;charset=utf-8' },
        timeout: 10000,
    }
}