"ui";

ui.layout(
    <vertical padding="16" id="parent">
     <webview id="web" h="*" w="*"  />

</vertical>
);
let SCRIPT_CONF = require('./common/ScriptConf.js')
let floatyObj = require('./demo.js');

console.log(floatyObj)

initUi('http://192.168.2.24:8080')

ui.emitter.on("back_pressed", (e) => {
    e.consumed = true;
    activity.moveTaskToBack(true);
  });

var storage = storages.create("dtok");
function initUi(htmlPath) {
    webViewExpand_init(ui.web)

    if (htmlPath.indexOf('http') === 0) {
        ui.web.loadUrl(htmlPath)
    } else {
        let path = 'file:' + files.path(htmlPath)
        ui.web.loadUrl(path)
    }
}

let conf = {
    baseUrl: "https://ruanjian168.cc/"
}
ui.web.jsBridge.registerHandler("doLogin", (data, callBack) => {
    let loginUrl = conf.baseUrl + 'login'
    if (data == null) {
        toastLog("请填写用户名密码")
        return;
    }
    let loginObj = JSON.parse(data)

    if (!loginObj.hasOwnProperty('username')) {
        toastLog("请填写用户名")
        return;
    }
    if (!loginObj.hasOwnProperty('password')) {
        toastLog("请填写密码")
        return;
    }
    threads.start(function () {
        let res = http.post(loginUrl, {
            "name": loginObj.username,
            "passwd": loginObj.password
        })
        var loginRespObj = res.body.json();
        if (loginRespObj.code !== 200) {
            toastLog(loginRespObj.msg)
        } else {
            storage.put("token", loginRespObj.data.token)
            storage.put("userInfo", JSON.stringify(loginRespObj.data))
            callBack(loginRespObj.data.token)
        }
    });


})

ui.web.jsBridge.registerHandler("startScript", (data, callBack) => {
    let scriptUrl = "https://cybersicko.net/niuke/get_script"
    let token = storage.get("token")
    console.log("登录token" ,token)
    let dataObj = JSON.parse(data)

    threads.start(function () {
        let res = http.post(scriptUrl, {
            "module":dataObj.module
        },{
            headers: {"Authorization": token},
        });

        let scriptObj = res.body.json()
        console.log("getScript",scriptObj.msg)
        if (scriptObj.code == 401) {
            toastLog("请登录")
            callBack(scriptObj.code.toString())
            return
        }
        SCRIPT_CONF.script = scriptObj.data.script
        SCRIPT_CONF.conf = dataObj.conf
        SCRIPT_CONF.module = dataObj.module
        var packageName = "com.ss.android.ugc.aweme"; // 视频App的包名

        // 打开视频App
        launch(packageName);
        floatyObj.show()

    });
})

ui.web.jsBridge.registerHandler("getToken", (data, callBack) => {
    let token = storage.get("token")
    console.log("获取TOKEN", token)
    callBack(token)
})

ui.web.jsBridge.registerHandler("getUserInfo", (data, callBack) => {
    let userInfo = storage.get("userInfo")
    console.log("获取用户信息", userInfo)
    callBack(userInfo)
})
ui.web.jsBridge.registerHandler("reload", (data, callBack) => {
    console.log("刷新...")
    ui.web.reload()
})

ui.web.jsBridge.registerHandler("logout", (data, callBack) => {
    storage.remove("token")
    callBack(200)
})
ui.web.jsBridge.registerHandler("showToast", (data, callBack) => {
    console.log(data)
    toastLog(data)
})
// setTimeout(() => {
//     ui.web.jsBridge.callHandler('jsTest', '数据', (data) => {})
// }, 1000)



function webViewExpand_init(webview) {
    webview.setOnKeyListener(
        new android.view.View.OnKeyListener({
          onKey: function (v, keyCode, event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
              if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
                //表示按返回键
                log("返回键");
                ui.web.goBack(); //后退
                //webview.goForward();//前进
                return true; //已处理
              }
            }
            return false;
          },
        })
      );

    webview.webViewClient = new JavaAdapter(android.webkit.WebViewClient, {
        /** 页面开始加载, 此时还没有加载 index.html 中的代码 */
        onPageStarted: (webView, url, favicon) => {},
        /** 页面加载完成, 在 window.onload 之后触发 */
        onPageFinished: (webView, curUrl) => {
            webview.injectionJsBridge()
        },
        onReceivedError: (webView, webResourceRequest, webResourceError) => {
            let url = webResourceRequest.getUrl()
            let errorCode = webResourceError.getErrorCode()
            let description = webResourceError.getDescription()
            console.trace(errorCode + ' ' + description + ' ' + url)
        },
    })



    webview.webChromeClient = new JavaAdapter(android.webkit.WebChromeClient, {
        /** 拦截 web console 消息 */
        onConsoleMessage: (consoleMessage) => {
            /** @type {string} */
            let msg = consoleMessage.message()
            let sourceId = consoleMessage.sourceId().split('/')
            let sourceIdStr = sourceId[sourceId.length - 1]
            let lineNumber = consoleMessage.lineNumber()
            let msgLevel = consoleMessage.messageLevel()
        },
    })
}