"ui";

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

</vertical>
  `
);
let SCRIPT_CONF = require('./common/ScriptConf.js')
let floatyObj = require('./floatywindow.js');
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)
    var settings = ui.web.getSettings();
    settings.setSupportZoom(false); // 是否支持页面缩放
    settings.setBuiltInZoomControls(false); // 是否出现缩放工具
    settings.setDisplayZoomControls(false);
    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/"
    baseUrl: "http://192.168.2.24:9090/",
    apiUrl: "http://192.168.2.24:9090/api/",
    deviceType: 'DEVICE',
    androidId:device.getAndroidId(),
    deviceName:device.device,
    deviceBrand:device.brand,
    deviceVersion:device.release
}


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

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


})

ui.web.jsBridge.registerHandler("doCheckAccountStatus", (data,callBack) => {
    let checkLoginUrl = conf.apiUrl + 'checkLogin'
    let token = storage.get("token")
    console.log(token)
    threads.start(function () {
        let res = http.get(checkLoginUrl, {
            headers: {
                "satoken": token
            }
        })
        let respObj = res.body.json()
        if (respObj.code > 200){
            console.log("未登录，清除")
            toastLog("请先登录")
            storage.remove("token")
            storage.remove("userInfo")
        }

        callBack(JSON.stringify(respObj).toString())
    })
})


ui.web.jsBridge.registerHandler("checkRegister", (data,callBack) => {
    let token = storage.get("token")
    let checkRegisterUrl = conf.apiUrl + `checkRegister/${token}/${conf.androidId}` 
    console.log(token)
    threads.start(function () {
        let res = http.get(checkRegisterUrl, {
            headers: {
                "satoken": token
            }
        })
        let respObj = res.body.json()
        callBack(JSON.stringify(respObj).toString())
    })
})

ui.web.jsBridge.registerHandler("logout", (data,callBack) => {
    storage.remove("token")
    storage.remove("userInfo")
    callBack('1')
})

ui.web.jsBridge.registerHandler("registerDevice", (data,callBack) => {
    let token = storage.get("token")
    let registerUrl = conf.baseUrl + `device/registerDevice/${token}` 
    console.log(registerUrl)
    threads.start(function () {
        console.log(conf)
        let res = http.post(registerUrl,{
            "deviceName": conf.deviceName,
            "deviceVersion":conf.deviceVersion,
            "deviceBrand":conf.deviceBrand,
            "androidId":conf.androidId
        }, {
            headers: {
                "satoken": token
            },
        })
        let respObj = res.body.json()
        callBack(JSON.stringify(respObj).toString())
    })
})

ui.web.jsBridge.registerHandler("unBundleDevice", (data,callBack) => {
    console.log('解绑',data)
    let token = storage.get("token")
    let unRegisterUrl = conf.baseUrl + `device/unBundleDevice/` + data 
    console.log(unRegisterUrl)
    threads.start(function () {
        console.log(conf)
        let res = http.get(unRegisterUrl, {
            headers: {
                "satoken": token
            },
        })
        let respObj = res.body.json()
        callBack(JSON.stringify(respObj).toString())
    })
})

ui.web.jsBridge.registerHandler("getCommonItem", (data,callBack) => {
    let token = storage.get("token")
    let commonItemUrl = conf.apiUrl + "getCommonItem" 
    threads.start(function () {
        let res = http.get(commonItemUrl, {
            headers: {
                "satoken": token
            },
        })
        let respObj = res.body.json()
        callBack(JSON.stringify(respObj).toString())
    })
})

ui.web.jsBridge.registerHandler("reload", (data, callBack) => {
    console.log("刷新...")
    ui.web.reload()
})

ui.web.jsBridge.registerHandler("startScript", (data, callBack) => {
    let dataObj = JSON.parse(data)
    let scriptUrl = conf.apiUrl + 'getExecScript/' + dataObj.uuid
    let token = storage.get("token")
    console.log("URL", scriptUrl)

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

        let scriptObj = res.body.json()
        if (scriptObj.code !== 200) {
            toastLog(scriptObj.message)
            callBack(JSON.stringify(scriptObj).toString())
            return
        }
        SCRIPT_CONF.script = scriptObj.data.scriptContent
        SCRIPT_CONF.conf = dataObj.conf
        SCRIPT_CONF.module = dataObj.module
        var packageName = scriptObj.data.app; // 视频App的包名

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

    });
})

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("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()
            console.log(msg)
        },
    })
}