let _global_duration = 1000;

let global = {
    setDuration: function (duration) {
        _global_duration = duration
    },
}

let store = storages.create("_##_@_DY_Proxy");

const project = "autojs"

let pwdFile = function (path) {
    let pwd = engines.myEngine().cwd()

    if (!path) {
        return pwd
    }

    if (path) {
        path = path.replace(/^\//, "")
    }

    return `${pwd}/${project}/${path}`.replace(/\/\//g, "/").replace(/\/$/, "")
}

let pageUser = {
    activity: "com.ss.android.ugc.aweme.profile.ui.UserProfileActivity",
    wait: function () {
        waitForActivity(this.activity)
    },
    open: function () {
        let activity = "snssdk1128://user/profile"
        app.startActivity({
            packageName: "com.ss.android.ugc.aweme",
            action: "android.intent.action.VIEW",
            data: activity,
        });
        let appId = id("com.miui.securitycore:id/app1").findOne(1000)
        if (appId) {
            appId.click()
        }

        waitForActivity("com.ss.android.ugc.aweme.main.MainActivity")

        let pt = className("android.widget.TextView").find().findOne(text("我")).bounds()
        click(pt.centerX(), pt.centerY())
    },
    openUser: function (uid) {
        let activity = "snssdk1128://user/profile/{uid}".replace("{uid}", uid)
        app.startActivity({
            packageName: "com.ss.android.ugc.aweme",
            action: "android.intent.action.VIEW",
            data: activity,
        });
        let appId = id("com.miui.securitycore:id/app1").findOne(1000)
        if (appId) {
            appId.click()
        }
        waitForActivity("com.ss.android.ugc.aweme.profile.ui.UserProfileActivity")
    },
    hasPublishItems: function () {
        let txt = "还没有作品"
        let id = "com.ss.android.ugc.aweme:id/title"

        let elem = text(txt).findOne(2 * 1000)
        if (!elem) {
            return true
        }

        return !(elem.id() == id)
    },

    getBtnGuanZhu: function () {
        let txt = "关注"
        let _id = "r2s"

        let elems = text(txt).find()
        if (elems.empty()) {
            log("找不到关注按钮")
            return false
        }

        let elem = elems.findOne(id(_id))
        if (!elem) {
            log("找不到关注按钮 id")
            return false
        }

        return elem
    },

    getBtnSiXin: function () {
        let txt = "私信"
        let desc = "私信"

        let elem = text(txt).findOne(2 * this.duration)
        if (!elem) {
            log("找不到私信按钮")
            return false
        }

        if (elem.desc() != desc) {
            log("私信按钮 desc 不匹配")
            return false
        }
        return elem
    },

    getIPLocation: function () {
        let txt = "IP："
        let _pid = "com.ss.android.ugc.aweme:id/tpw"

        let elems = textStartsWith(txt).find()
        if (elems.empty()) {
            log("找不到 IP 标签")
            return false
        }
        let elem = null
        elems.forEach(function (e) {
            if (elem) return
            if (e.parent().id() == _pid) {
                elem = e
            }
        })
        if (!elem) {
            log("找不到 IP 标签 id")
            return false
        }

        return elem.text().replace(txt, "").trim()
    },

    clickBtnSiXin: function () {
        let elem = this.getBtnSiXin()
        if (!elem) {
            return false
        }

        elem.click()
        sleep(2 * this.duration)
        return true
    },

    clickBtnGuanZhu: function () {
        let elem = this.getBtnGuanZhu()
        if (!elem) {
            return false
        }

        elem.click()
        sleep(2 * this.duration)
        return true
    },
}

let pageChat = {
    getBtnVoice: function () {
        let _desc = "语音"
        let _class = "android.widget.Button"

        let elem = className(_class).find().findOne(desc(_desc))
        if (!elem) {
            log("找不到 语音 按钮")
            return false
        }
        return elem
    },
    getBtnMyLoveSend: function () {
        let _txt = "发送"
        let _id = "com.ss.android.ugc.aweme:id/send"

        let elem = id(_id).findOne(2 * _global_duration)
        if (!elem) {
            log("找不到发送按钮")
            return false
        }

        return elem
    },
    getMyLoveFirstProduct: function () {
        let _class = "com.bytedance.ies.dmt.ui.widget.DmtTextView";
        let loves = className(_class).find()
        if (loves.empty()) {
            log("找不到我的喜欢")
            return false
        }

        return loves.shift()
    },
    getMyLoveButton: function () {
        let _txt = "我的喜欢"
        let _class = "android.widget.TextView"

        let _pclass = "android.view.ViewGroup"

        let elem = className(_pclass).find().findOne(text(_txt)).parent()
        if (!elem) {
            log("找不到 我的喜欢 按钮")
            return false
        }

        return elem
    },
    getPanelMore: function () {
        let _class = "androidx.viewpager.widget.ViewPager"

        let elem = className(_class).findOne(2 * _global_duration)
        if (!elem) {
            log("找不到 更多面板")
            return false
        }

        return elem
    },
    getBtnCloseMore: function () {
        let _desc = "关闭面板"
        let _class = "android.widget.Button"

        let elem = className(_class).find().findOne(desc(_desc))
        if (!elem) {
            log("找不到关闭面板按钮")
            return false
        }

        return elem
    },
    getBtnMore: function () {
        let _desc = "更多面板"
        let _class = "android.widget.Button"

        let elem = className(_class).find().findOne(desc(_desc))
        if (!elem) {
            log("找不到更多面板按钮")
            return false
        }
        log(elem.id())

        return elem
    },
    clickBtnCloseMore: function () {
        let elem = this.getBtnCloseMore()
        if (!elem) {
            return false
        }

        elem.click()
        sleep(_global_duration)
        return true
    },
    clickBtnMore: function () {
        let elem = this.getBtnMore()
        if (!elem) {
            return false
        }

        elem.click()
        sleep(_global_duration)
        return true
    },
    swipeMorePanelRight: function () {
        let elem = this.getPanelMore()
        if (!elem) {
            return false
        }

        // elem.scrollLeft()
        let x = elem.bounds().centerX() + elem.bounds().width() / 4
        let y = elem.bounds().centerY()
        let x1 = elem.bounds().left
        let y1 = elem.bounds().centerY()
        log(x, y, x1, y1)
        swipe(x, y, x1, y1, 200)
        sleep(_global_duration)
        return true
    },
    swipeMorePanelLeft: function () {
        let elem = this.getPanelMore()
        if (!elem) {
            return false
        }

        let x = elem.bounds().centerX() - elem.bounds().width() / 4
        let y = elem.bounds().centerY()
        let x1 = elem.bounds().right
        let y1 = elem.bounds().centerY()
        log(x, y, x1, y1)
        swipe(x, y, x1, y1, 200)
        sleep(_global_duration)
        return true
    },

    clickBtnMyLove: function () {
        let elem = this.getMyLoveButton()
        if (!elem) {
            return false
        }

        elem.click()
        // click(elem.bounds().centerX(), elem.bounds().centerY())
        sleep(_global_duration)
        return true
    },
    clickBtnMyLoveFirstProduct: function () {
        let elem = this.getMyLoveFirstProduct()
        if (!elem) {
            return false
        }

        log(elem.className())
        click(elem.bounds().centerX(), elem.bounds().centerY())
        sleep(_global_duration)
        return true
    },
    clickBtnMyLoveSend: function () {
        let elem = this.getBtnMyLoveSend()
        if (!elem) {
            return false
        }

        elem.click()
        sleep(_global_duration)
        return true
    },
    pressBtnVoice: function (duration) {
        let elem = this.getBtnVoice()
        if (!elem) {
            return false
        }

        press(elem.bounds().centerX(), elem.bounds().centerY(), duration)
        sleep(_global_duration)
        return true
    },
    sendAudioVoice: function (voice) {
        let elem = this.getBtnVoice()
        if (!elem) {
            log("找不到 语音 按钮")
            return false
        }

        var musicDuration = threads.disposable();
        threads.start(function () {
            sleep(500)
            //播放音乐
            media.playMusic(pwdFile(`audio/${voice}.m4a`));
            media.pauseMusic()

            //让音乐播放完
            let duration = media.getMusicDuration()
            musicDuration.setAndNotify(duration)
            sleep(500)
            media.resumeMusic()

            sleep(duration);
        });

        let duration = musicDuration.blockedGet()

        press(elem.bounds().centerX(), elem.bounds().centerY(), 1000 + duration)
        sleep(_global_duration)
        return true

    },
    isSendVoiceMode: function () {
        let _txt = "按住 说话"
        return text(_txt).findOne(2 * _global_duration)
    },
    getBtnVoiceToTxt: function () {
        return desc("文本").findOne(2 * _global_duration)
    },
    getInputSendTxt: function () {
        return text("发送消息").findOne(2 * _global_duration)
    },
    getBtnSendTxt: function () {
        return desc('发送').findOne(2 * _global_duration)
    },
    sendTxt: function (txt) {
        if (this.isSendVoiceMode()) {
            let elem = this.getBtnVoiceToTxt()
            if (!elem) {
                return false
            }
            elem.click()
            sleep(_global_duration)
        }

        elem = this.getInputSendTxt()
        if (!elem) {
            log("找不到发送消息输入框")
            return false
        }

        elem.setText(txt)
        sleep(2 * _global_duration)

        if (!this.getBtnSendTxt().click()) {
            log("找不到发送按钮")
            return false
        }
        return true
    }
}

let pageFriend = {
    activity: "com.ss.android.ugc.aweme.following.ui.FollowRelationTabActivity",
    wait: function () {
        lib.waitForActivity(_activity)
    },
    open: function () {
        // app.startActivity(this.activity)
    },
    listFriends: function () {
        let _id = "com.ss.android.ugc.aweme:id/content"
        let elems = id(_id).find()
        if (elems.empty()) {
            log("找不到 好友列表")
            return []
        }

        let friends = [];
        elems.forEach((elem, i) => {
            let [name, online] = elem.desc().split(",")

            let btn = elem.findOne(text("发私信"))
            log(name, online, btn)
            friends.push({
                name: name,
                online: online,
                btn: btn,
            })
        })

        return friends
    },
}

let messages = [
    [
        "你好，是要男性健康方面的问题吗",
        "{voice}",
        "十我详谈吧，这里敏感词太多",
        "这里敏感词多",
        "这里有时候不常在，消息回复不及时",
    ],
    [
        "{wechat}"
    ],
    [
        "↑微訫号",
        "微訫号",
        "↑微訫号",
        "↑徽沁",
        "↑微沁",
    ],
    [
        "十了说一下给你通过",
        "加上一对一给你解答",
        "",
        "加上详谈",
        "加上详细沟通一下你的情况",
    ]
];

let st = {
    times: function () {
        return store.get('__times', 0)
    },
    addTimes: function () {
        return store.put('__times', this.times() + 1)
    },
    host: function () {
        let host = store.get("__host", "")
        log("HOST=", host)
        if (host.length == 0) {
            host = "http://10.1.1.108:8080"
            store.put("__host", host)
        }
        return host
    },
    lastID: function (id) {
        if (id) {
            return store.put('__lastID', id)
        }
        return store.get('__lastID', 0)
    }
}
let fetch = function () {
    //指定确定按钮点击时要执行的动作
    const deviceID = device.getAndroidId()

    let lastID = st.lastID()
    let path = "{host}/api/devices/{deviceID}/follower"
    let url = path.replace("{host}", st.host()).replace("{deviceID}", deviceID)
    if (lastID != 0) {
        url = url + "?lastID=" + lastID
    }
    // log("url =", url)

    let resp = http.get(url)
    let body = resp.body.json()
    if (body == null) {
        toastLog("没有新的数据")
        return
    }

    st.lastID(body.ID)
    // log("body =", body)

    return body.UID
}

module.exports = {
    duration: 1000,
    global: global,
    page: {
        user: pageUser,
        chat: pageChat,
        friend: pageFriend,
    },
    messages: messages,
    fetch: fetch,
    store: st,
    kill: function () {
        let name = "com.ss.android.ugc.aweme"
        app.openAppSetting(name);//通过包名打开应用的详情页(设置页)
        text(app.getAppName(name)).waitFor();//通过包名获取已安装的应用名称，判断是否已经跳转至该app的应用设置界面
        sleep(500);//稍微休息一下，不然看不到运行过程，自己用时可以删除这行
        let is_sure = textMatches(/(.*强.*|.*停.*|.*结.*)/).findOne();//在app的应用设置界面找寻包含“强”，“停”，“结”，“行”的控件
        //特别注意，应用设置界面可能存在并非关闭该app的控件，但是包含上述字样的控件，如果某个控件包含名称“行”字
        //textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/)改为textMatches(/(.*强.*|.*停.*|.*结.*)/)
        //或者结束应用的控件名为“结束运行”直接将textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/)改为text("结束运行")

        if (is_sure.enabled()) {//判断控件是否已启用（想要关闭的app是否运行）
            is_sure.parent().click();//结束应用的控件如果无法点击，需要在布局中找寻它的父控件，如果还无法点击，再上一级控件，本案例就是控件无法点击
            textMatches(/(.*确.*|.*定.*)/).findOne().click();//需找包含“确”，“定”的控件
            log(app.getAppName(name) + "应用已被关闭");
            sleep(1000);
            back();
        } else {
            log(app.getAppName(name) + "应用不能被正常关闭或不在后台运行");
            back();
        }
    },
}