"ui";

ui.layout(
    <webview id="web" h="*" w="*"  />
);

let floatyObj = require("../../common/flatwin.js");
console.log(floatyObj)

floatyObj.hide()

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

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 = conf.baseUrl + 'getScript'
    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()
        if (scriptObj.code == 401) {
            toastLog("请登录")
            callBack(scriptObj.code.toString())
            return
        }
        global.CONF.script = scriptObj.data.script
        global.CONF.conf = {"yxgs":1000,"czjg1":3,"czjg2":5,"gksj1":5,"gksj2":12,"dz":90,"gz":20,"pl":20,"plhs":["过来支持你啦，希望能获得你的回访","相遇是缘分，也看看我的作品吧","支持你的作品，互相帮助","诚信互助，一起进步","互帮互助，希望你也能看我主页","抖音那么大，也来我主页转转","默默关注，评论支持","互相帮忙，一起加油","来支持你啦，也来支持我一下吧","有缘看到你的作品，支持一下","看到就是一种缘分，评论支持你","给你点赞评论支持，希望也能回看一下我的","互相帮助，希望得到你的回应","关注你作品，向你学习","真诚互助，一起加油吧","双向奔赴的缘分来喽，支持你","互相帮忙，有赞回赞，有评回评","真诚交朋友，互相帮忙点赞评论"],"gjcs":["52042612234","42780888122","40605707934","34477336631","33119784740","42591640755","81239058442"],"pltp":false,"screenWidth":480,"screenHeight":801}
    });
})

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.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()
        },
    })
}