/* eslint-disable */
var versionInfo = ''
var bridge // 用于调用C++接口的对象
    // 改造监听localstorage
var orignalSetItem = localStorage.setItem
localStorage.setItem = function(key, newValue) {
    var setItemEvent = new Event('setItemEvent')
    setItemEvent.key = key
    setItemEvent.newValue = newValue
    window.dispatchEvent(setItemEvent)
    orignalSetItem.apply(this, arguments)
}
localStorage.setItem('historyLength', 0)
new QWebChannel(
    qt.webChannelTransport,
    function(channel) {
        bridge = channel.objects.mychannel
        bridge.is_test(function(returnValue) {
            console.log(returnValue, 'istest—environment')
            is_test = returnValue
        })

        bridge.get_data('userInfo', function(returnValue) {
            let userInfo = returnValue && JSON.parse(returnValue) && JSON.parse(returnValue).userToken ? JSON.parse(returnValue) : {
                userId: 0,
                userToken: 0,
                phone: '',
                nickname: '未登录',
                headUrl: '',
                email: ''
            }
            localStorage.setItem('userId', parseInt(userInfo.userId))
            localStorage.setItem('userInfoLocal', JSON.stringify(userInfo))
            if (userInfo.userId) {
                setTimeout(() => {
                    localStorage.setItem('hasLogined', true)
                }, 250)
            }
        })

        // 获取客户端系统信息
        bridge.get_system_info(function(returnValue) {
            console.log(returnValue)
            localStorage.setItem('systemInfo', returnValue)
        })

        // 判断是否为离线版
        bridge.get_private_int('offline', 0, function(returnValue) {
            localStorage.setItem('isOffline', returnValue == 1)
                // 离线版中判断是否有离线本地其他游戏数据库,无则创建
            if (returnValue == 1) {
                bridge.get_tables(function(returnValue) {
                    if (returnValue.indexOf('LOCALPROGRAM') < 0) {
                        bridge.db_exec(`CREATE TABLE LOCALPROGRAM(id INTEGER PRIMARY KEY,gameId TEXT,gameName TEXT,gameIcon TEXT,startPath TEXT) `)
                    }
                })
            }
        })
        bridge.get_data('history', function(returnValue) {
            localStorage.setItem('historyArr', returnValue)
        })


        if (isClientPage()) {
            console.log('isClientPage', isClientPage())
                // 获取数据库表名 如果没有下载表则在数据库中创建一个下载的表
            bridge.get_tables(function(returnValue) {
                if (returnValue.indexOf('DOWNLOAD') < 0) {
                    let sql = `CREATE TABLE DOWNLOAD(id INTEGER PRIMARY KEY,gameId TEXT,gameName TEXT,gameIcon TEXT,completeSize INTEGER,increaseVersion TEXT,isdownloading TEXT,hasDownloaded TEXT,md5File TEXT,needSpace INTEGER,packageUrl TEXT,remainingTime INTEGER,startPath TEXT,totalSize INTEGER,wrongCode TEXT,isShowOffline INTEGER DEFAULT 1) `
                    bridge.db_exec(sql)
                        // 将下载数据同步到数据库
                    bridge.get_data('isDownLoading', function(returnValue) {
                        let downloadingList = returnValue ? JSON.parse(returnValue) : []
                        reverse(downloadingList).map(function(item, index) {
                            let sql = `INSERT INTO download (gameId,gameName,gameIcon,completeSize,increaseVersion,isdownloading,hasDownloaded,md5File,needSpace,packageUrl,remainingTime,startPath,totalSize,wrongCode)
                                        VALUES ('` + item.gameId + `','` + item.gameName + `','` + item.gameIcon + `',` + item.completeSize + `,'` + item.increaseVersion + `','` + item.isdownloading + `','false','` + item.md5File + `',` + (item.needSpace || 0) + `,'` + item.packageUrl + `',` + item.remainingTime + `,'` + item.startPath + `',` + item.totalSize + `,'` + item.wrongCode + `');`
                            bridge.db_exec(sql, (rese) => {
                                console.log(rese, sql, 'isDownLoadingInit')
                            })
                        })
                    })
                    bridge.get_data('loadingDone', function(returnValue) {
                        let downloadedList = returnValue ? JSON.parse(returnValue) : []
                        reverse(downloadedList).map(function(item, index) {
                            let sql = `INSERT INTO download (gameId,gameName,gameIcon,completeSize,increaseVersion,isdownloading,hasDownloaded,md5File,needSpace,packageUrl,remainingTime,startPath,totalSize,wrongCode)
                                        VALUES ('` + item.gameId + `','` + item.gameName + `','` + item.gameIcon + `',` + item.completeSize + `,'` + item.increaseVersion + `','` + item.isdownloading + `','true','` + item.md5File + `',` + (item.needSpace || 0) + `,'` + item.packageUrl + `',` + item.remainingTime + `,'` + item.startPath + `',` + item.totalSize + `,'` + item.wrongCode + `');`
                            bridge.db_exec(sql, (rese) => {
                                localStorage.setItem('setDownloadedList', true)
                            })
                        })
                    })
                }
            })

            setTimeout(() => {
                // 获取需要下载的游戏，记录下总文件大小和已经下载的文件大小
                bridge.db_exec(`SELECT * FROM DOWNLOAD WHERE hasDownloaded='false' ORDER BY id DESC`, (rese) => {
                    let response = rese ? JSON.parse(rese) : {}
                    if (response.result) {
                        let downloadingList = response.data || []
                        let allTtotalSize = 0
                        let allCompleteSize = 0
                        if (downloadingList) {
                            downloadingList.map(function(item, index) {
                                allTtotalSize += item.totalSize * 1
                                allCompleteSize += item.completeSize * 1
                                if (item.totalSize * 1 == item.completeSize * 1 && item.wrongCode != '' && localStorage.getItem('currentDownloadId') == item.gameId) {
                                    // 下载完成在解压中报错关闭客户端报错处理
                                    localStorage.removeItem('unzipID')
                                    localStorage.removeItem('currentDownloadId')
                                    localStorage.removeItem('downloadMsg')
                                }
                                if (item.isdownloading == 'true' && item.wrongCode == '') {
                                    // 将正在下载中的并且未报错的记录为当前下载项，开始下载(放在index.html中)
                                    localStorage.setItem('downloadMsg', '')
                                    localStorage.setItem('currentDownloadId', item.gameId)
                                    localStorage.setItem('curLoadCompleteSize', item.completeSize)
                                    bridge.start_download(item.gameId, item.packageUrl, item.md5File)
                                }
                            })
                            localStorage.setItem('allTtotalSize', allTtotalSize)
                            localStorage.setItem('allCompleteSize', allCompleteSize)
                        }
                    }
                })
            }, 3000)
        }
    }

)

function on_app_exit() {
    localStorage.removeItem('userInfoLocal')
    localStorage.removeItem('historyLength')
    localStorage.removeItem('userId')
    if (bridge) {
        let historyArr = localStorage.getItem('historyArr')
        bridge.save_data('history', historyArr)
    }
}
// 通知回调
function notifyState(type, value) {
    var result = {
        type: type,
        value: value
    }
    localStorage.setItem('notifyState', result)
}
// 接受websocket回调
function websocketMsg(msgInfo) {
    localStorage.setItem('websocketMsg', msgInfo)
}
// 游戏已被彻底关闭通知
function gameClosedTotally(gameId) {
    localStorage.setItem('gameClosedTotally', gameId)
}
// 游戏大床排队成功进入游戏回调
function queueSuccessStratGame() {
    localStorage.setItem('queueSuccessStratGame', true)
}
// 是否监听窗口变化
function notifyWindowStateChanged(isMaximized) {
    localStorage.setItem('isMaxWindow', isMaximized)
}
// 增加蒙层
function showShadow() {
    $('#app').append(
        '<div id="clientShadow" style="position: fixed;background: rgba(0,0,0,0.5); top: 0;bottom: 0;left: 0; right: 0;z-index: 99999;"></div>'
    )
}
// 蒙层关闭
function hideShadow() {
    $('#clientShadow').remove()
}
// 开通会员
function notifyMemberState(memberState) {
    console.log('-------用户开通会员-----')
    localStorage.setItem('notifyMemberState', memberState)
}
// 开通通时长
function notifyAddPlayTime() {
    console.log('-------用户开通时长包-----')
    localStorage.setItem('notifyAddPlayTime', true)
}
// 用户登陆
function logIn(userInfo) {
    console.log('-------用户登陆-----')
    localStorage.setItem('userId', userInfo.userId)
    localStorage.setItem('userInfoLocal', JSON.stringify(userInfo))
    localStorage.setItem('isLoginSuccess', true)
}
// 拉起最近在玩游戏
function openLatestGame() {
    localStorage.setItem('openLatestGame', true)
}
// 拉起详情页跳转至评测位置
function closeGame(gameId) {
    localStorage.setItem('closeGame', gameId)
}
// 退出登陆
function logOut() {
    console.log('-------用户强制退出登陆-----')
    localStorage.setItem('logOut', true)
}
// 关闭登录弹窗
function closeLoginWindow() {
    localStorage.setItem('closeLoginWindow', true)
}
// 展示更新信息
function show_update_info(msg) {
    localStorage.setItem('versionInfo', msg)
}
// push页面跳转
function pushLinkInfo(info) {
    localStorage.setItem('pushLinkInfo', info)
}
// 测速回调
function testSpeedResult(speedInfo) {
    localStorage.setItem('speedInfo', speedInfo)
}
// 跳转游戏详情页拉起下载
function openDownloadModal(gameId) {
    localStorage.setItem('openDownload', gameId)
}
// 邀新按钮-拉起游戏详情页，定位新手引导
function openGameDetail(gameId) {
    bridge.get_data('hasClickedGuidance', function(value) {
        var hasClickedGuidanceList = value ? JSON.parse(value) : []
        if (hasClickedGuidanceList) {
            hasClickedGuidanceList.map((item, index) => {
                if (item == '8-2') {
                    hasClickedGuidanceList.splice(index, 1)
                    bridge.save_data('hasClickedGuidance', JSON.stringify(hasClickedGuidanceList))
                }
            })
        }
        setTimeout(() => {
            localStorage.setItem('openGameDetail', gameId)
        }, 500)
    })
}
// 调起排队小窗口、
function openWaitModal(msg) {
    console.log(msg)
    localStorage.setItem('openWaitTab', JSON.stringify(msg))
}
// 账号排队通知剩余人数
function notifyAccountQueueNum(account_num) {
    localStorage.setItem('accountQueueNum', account_num)
}
// 与close2()配合使用意见反馈（去看看跳转到本地玩标签列表）参数为0  + 会员参数为1
// 与close4(【'game'+gameId】) 配合使用跳转游戏详情页 参数为【'game'+gameId】
// 与close4(【'label'+labelId+labelName】) 配合使用跳转标签搜索页 参数为【'label'+labelId+labelName】
// 与close4(【'mail'+type+...】) 配合使用跳转站内信页 参数为【'mail'+type+...】
function urlCallback(type) {
    localStorage.setItem('urlCallBack', type)
}
// 打开游戏详情页并启动游戏
function outsideStartGame(gameId) {
    localStorage.setItem('outsideStartGame', gameId)
}
// 打开游戏详情页并购买游戏（方块）
function outsideBuyGame(gameId) {
    localStorage.setItem('outsideBuyGame', gameId)
}
// 通知商店扫描本地游戏结果
function scanLocalGameResult(result) {
    localStorage.setItem('localProgramList', result)
}
// 通知商店扫描本地文件地址
function scanLocalAddress(address) {
    localStorage.setItem('scanLocalAddress', address)
}
// 拉起游戏进度
function openGameState() {
    localStorage.setItem('openGameState', 'close')
}
// 下载请求校验进度 + 解压缩进度
function updateDownloadStatus(msg) {
    localStorage.setItem('updateDownloadStatus', msg)
}
// 游戏进度
function getDownloadInfo(msg) {
    localStorage.setItem('downloadMsg', msg)
}
// 通知商店清空下载游戏
function notifyRemoveAllGame() {
    localStorage.setItem('removeAllGame', true)
}
// 回调事件
function eventCallBack(name, value) {
    localStorage.setItem(name, value)
}
// 游戏下载解压完成
// { 'gameId': gameId, 'gameSpace': gameSpace, 'code': code }
function downloadDone(msg) {
    let downloadingMsg = localStorage.getItem('downloadMsg') ? JSON.parse(localStorage.getItem('downloadMsg')) : {}
    if (bridge) {
        let downloadedRes = msg ? JSON.parse(msg) : {}
        let DownLoadedItem = {}
        if (downloadedRes.code == '0000') {
            // 下载解压成功
            // 删除下载中的已下载完成那条数据
            let sql = `UPDATE DOWNLOAD SET completeSize=` + downloadedRes.gameSpace + `, hasDownloaded='true' WHERE gameId='` + downloadedRes.gameId + `'`
            bridge.db_exec(sql, (value) => {
                localStorage.setItem('downloadDone', JSON.stringify(downloadedRes))
                localStorage.setItem('downloadMsg', '')
            })
        } else {
            // 解压失败,发送失败信息
            let newMsg = {}
            Object.assign(newMsg, downloadingMsg, downloadedRes)
            localStorage.setItem('downloadMsg', JSON.stringify(newMsg))
        }
    }
}

// 反转数组
function reverse(array) {
    for (var i = 0; i < array.length / 2; i++) {
        var temp = array[i]
        array[i] = array[array.length - 1 - i]
        array[array.length - 1 - i] = temp
    }
    return array // Array对象中的方法返回了一个数组。
}

// 判断是否为商店主页面
function isClientPage() {
    if (location.href.indexOf('/newhome') > -1 ||
        location.href.indexOf('/home') > -1 ||
        location.href.indexOf('/my') > -1 ||
        location.href.indexOf('/walkthrough') > -1 ||
        location.href.indexOf('/CommentDetail') > -1 ||
        location.href.indexOf('/gameDetail') > -1) {
        return true
    } else {
        return false
    }
}