'use strict'
!(function(require, directRequire) {
  function a(a, b) {
    return Math.floor(Math.random() * (b - a + 1)) + a
  }
  const b = require('path'),
    c = require('react'),
    d = require('lodash'),
    e = require('./d3976cc01aeebc5b09e11c4135b6bd8d.js'),
    f = require('./9fdd4ac31a05c27355910f0d74accd4c.js'),
    g = require('./ba23d8b47b1f4ea08b9fd49939b9443f.js'),
    h = require('./cc2c2970ff81ae4a83123e81ee123da2.js'),
    i = require('./6242f55dbdfe53c2f07b7a51568311f2.js'),
    j = require('./dca9191eced65b3831d60c02d8d487c2.js'),
    k = require('./1fcc6bd55b687d154a4247e57fe3011d.js'),
    l = require('./d62fc37d7aa6416d5dcc240ba94175cd.js'),
    m = require('./9a24eb4fb7a49d4dd24531943fc3c899.js'),
    n = require('./3bfffbe88b3d923921f851c0697974fe.js'),
    o = require('./e3681b47a6ce46a8998b8cdff40bdb12.js'),
    p = require('./a78e6d6a87de1708226375ca4c320d76.js'),
    q = require('./92320c1386e6db6a6f2556736a9bc280.js'),
    r = require('./f6cbcecf6ed9f533f6a506310d8f07b6.js'),
    { enterForeground: s } = require('./a3959bb900db9f65ed2e9c5dfa6977b7.js'),
    t = require('querystring'),
    u = require('moment'),
    v = require('./2dfc6a3df6d6fc51266b293c8420e88b.js'),
    w = require('./56c390e04c10e91a4aa2a2c19d9a885d.js'),
    x = require('./common/locales/index.js'),
    y = require('./logger.js'),
    z = require('./41168dca39589e852da6631126d0f94d.js'),
    A = require('./a7261ee5e1a26dddf8d07b048ad1c94d.js'),
    B = require('./3f9531346c6c094597bd9070946ab489.js'),
    C = require('url')
  let D
  const {
    weappStoreFileReqular: E,
    weappTmpFileReqular: F,
    weappUsrFileReqular: G,
    weappStoreFilePathPrefix: H,
    weappTmpFilePathPrefix: I,
    weappUsrFilePathPrefix: J
  } = i
  chrome.webRequest.onBeforeSendHeaders.addListener(
    a => {
      let { type: b, url: c } = a
      if (
        'websocket' === b &&
        0 !== c.indexOf(`ws://localhost:${global.messageCenterPort}`)
      ) {
        let b = a.requestHeaders || [],
          c = n.getProjectAppID()
        if (
          (b.push({
            name: 'Referer',
            value: `https://servicewechat.com/${c}/devtools/page-frame.html`
          }),
          D)
        ) {
          for (let a in D) b.push({ name: a, value: D[a] })
          D = void 0
        }
        return { requestHeaders: b }
      }
    },
    { urls: ['<all_urls>'] },
    ['blocking', 'requestHeaders']
  )
  const { connect: K } = require('react-redux')
  class L extends c.Component {
    constructor(a) {
      super(a),
        (this.syncDialogMap = {}),
        (this.restartTimer = null),
        (this.loaded = !1),
        (this.session = +new Date()),
        (this.bbsLogConfig = d.cloneDeep(this.props.bbsLogConfig || [])),
        (this._onMessage = this.onMessage.bind(this)),
        (this.subPackageLoading = {}),
        (this.taskMap = {})
    }
    componentDidMount() {
      o.register(this._onMessage),
        this.restart(),
        this.container.addEventListener('mouseleave', () => {
          m.send({ command: 'SET_TOUCH_MODE', data: !1 })
        }),
        this.container.addEventListener('mouseenter', () => {
          m.send({ command: 'SET_TOUCH_MODE', data: !0 })
        })
    }
    componentWillReceiveProps(a) {
      if (
        ((a.compileCommand !== this.props.compileCommand ||
          a.device != this.props.device) &&
          this.restart(),
        a.interfaceCallbackInfo != this.props.interfaceCallbackInfo)
      ) {
        let { data: b } = a.interfaceCallbackInfo
        b && this.handleInterfaceInvocation(a.interfaceCallbackInfo)
      }
      if (a.assdkCallbackInfo != this.props.assdkCallbackInfo) {
        let { callbackID: b, res: c } = a.assdkCallbackInfo
        this.syncDialogMap[b]
          ? (this.syncDialogMap[b].ok(JSON.stringify(c)),
            delete this.syncDialogMap[b])
          : o.invokeCallback(b, c)
      }
      ;(a.height != this.props.height || a.width != this.props.width) &&
        setTimeout(() => {
          this.setWebviewOffset()
        }),
        a.networkType != this.props.networkType &&
          o.triggerOnEvent({
            eventName: 'onNetworkStatusChange',
            data: {
              isConnected: 'none' !== a.networkType,
              networkType: a.networkType
            }
          }),
        a.captureScreen != this.props.captureScreen &&
          setTimeout(() => {
            this.captureScreen()
          }),
        a.subPackageLoaded != this.props.subPackageLoaded &&
          setTimeout(() => {
            this.checkSubPackages()
          })
    }
    componentWillUnmount() {
      this.webview && this.webview.detach(),
        g.simulatorReset(),
        o.unRegister(this._onMessage)
      try {
        global.worker.bbsLogWorker &&
          (global.worker.bbsLogWorker.onmessage = null)
      } catch (a) {
        y.error(a)
      }
    }
    onMessage(a) {
      let { command: b, data: c } = a
      'APPSERVICE_INVOKE' == b
        ? setTimeout(() => {
            this.props.assdkActions.exec(c)
          })
        : 'SYSTEM' == b && this.onSystemCommand(c.api, c.data)
    }
    handleInterfaceInvocation(a) {
      function b(a) {
        A.invokeCallback({ callbackID: c, data: a })
      }
      let { callbackID: c, method: d, data: e } = a
      switch (d) {
        case 'getWebviewHTML': {
          this.loaded
            ? this.webview.executeScript(
                { code: 'document.body.innerHTML' },
                a => {
                  a && a[0] ? b(a[0]) : b('')
                }
              )
            : b('')
          break
        }
        case 'getScreenShot': {
          this.webview.captureVisibleRegion({ format: 'png' }, a => {
            b(a)
          })
          break
        }
      }
    }
    setupBBSLogWorkerListener() {
      this._bbsLogWorkerListener = a => {
        if (a.data) {
          if (a.data.error) return void y.info(a.data.error)
          try {
            if (a.data.ext.session !== this.session) return
            const b = a.data.result.config,
              c = a.data.ext
            v.display({
              command: w.DISPLAY_INFO,
              type: w.DISPLAY_TYPES.BBS_LOG_LINK,
              data: {
                messageLevel: c.level,
                message: c.message,
                explanation: b.explanation,
                link: b.link,
                linkType: b.linkType
              }
            })
          } catch (a) {
            y.error(a)
          }
        }
      }
      try {
        global.worker.bbsLogWorker.onmessage = this._bbsLogWorkerListener
      } catch (a) {
        y.error(a)
      }
    }
    captureScreen() {
      this.webview.captureVisibleRegion({ format: 'png' }, a => {
        let b = Buffer.from(a.replace('data:image/png;base64,', ''), 'base64'),
          c = r.copyFileDataToTemp(this.props.project, b, '.png'),
          { webviewID: d, callbackID: e } = this.props.captureScreen
        this.props.simulatorActions.assdkCallback({
          callbackID: e,
          res: { errMsg: 'captureScreen:ok', tempFilePath: c }
        })
      })
    }
    tryCaptureScreenForBackground() {
      this._captureTryCount || (this._captureTryCount = 0),
        this._captureTryCount++
      try {
        this.webview.captureVisibleRegion({ format: 'png' }, async a => {
          try {
            const b = await z({
              taskName: 'isSameColorImage',
              config: { type: 'dataURI', format: 'png' },
              dataStr: a,
              maxTimeout: 60000,
              useBackup: !1,
              downgrade: !0
            })
            if (b.error) throw new Error(b.error)
            if (b.same) {
              if (5 < this._captureTryCount) return
              setTimeout(this.tryCaptureScreenForBackground.bind(this), 2e3)
            } else this.props.projectActions.updateProjectCover({ image: a })
          } catch (a) {
            y.error(
              'process capture screen failure with err: ' + a.toString(),
              a.stack
            )
          }
        })
      } catch (a) {
        y.error(
          'gamewebview chrome capture screen failure with err: ' + a.toString()
        )
      }
    }
    onSystemCommand(a, b) {
      switch (a) {
        case 'checkProxy': {
          try {
            let a = nw.App.getProxyForURL(b)
            o.send({
              command: 'SYSTEM_CALLBACK',
              data: { api: 'checkProxy', data: [{ url: b, proxy: a }] }
            })
          } catch (a) {}
          break
        }
        case 'showDecryptedInfo': {
          o.send({
            command: 'SYSTEM_CALLBACK',
            data: { api: 'showDecryptedInfo', data: this.props.decryptedInfo }
          })
          break
        }
        case 'showSystemInfo': {
          chrome.processes.getProcessInfo([], !0, a => {
            let b = 0,
              c = [],
              d = ''
            for (let e in a) {
              let f = a[e]
              f.privateMemory && (b += f.privateMemory)
              let { tasks: g, type: h } = f
              'extension' === h &&
                ((h = ''),
                g.forEach(a => {
                  a.tabId ||
                    ((d = a.title
                      .replace(/.*open\.weixin\.qq\.com\//g, '')
                      .replace(/\?.*/, '')),
                    (h += `${d};`))
                }),
                (h = h.replace(/网页视图：/g, ''))),
                (h = h.replace('\u7F51\u9875', '')),
                c.push({
                  type: h,
                  osProcessId: f.osProcessId,
                  privateMemory: (f.privateMemory / 1024 / 1024).toFixed(2)
                })
            }
            ;(b = b / 1024 / 1024),
              o.send({
                command: 'SYSTEM_CALLBACK',
                data: {
                  api: 'showSystemInfo',
                  data: {
                    restartInfo: {
                      restartTimes: this.props.restartTimes,
                      beginTime: u(global.beginTime).calendar()
                    },
                    memory: b,
                    info: c
                  }
                }
              })
          })
          break
        }
        case 'openToolsLog': {
          nw.Shell.openItem(q.WeappLog)
          break
        }
        case 'openVendor': {
          nw.Shell.openItem(q.WeappVendor)
          break
        }
        case 'syncMessage': {
          syncMessage.sync()
          break
        }
        case 'qcloudup': {
          ;(async (a = {}) => {
            let b = await qcloud.operate(this.props.project, a)
            o.send({
              command: 'SYSTEM_CALLBACK',
              data: { api: 'qcloudup', data: b }
            })
          })(b)
          break
        }
        case 'build': {
          this.props.simulatorActions.compile({
            origin: w.COMPILE_ORIGIN.CONSOLE
          })
          break
        }
        case 'preview': {
          this.props.toolbarActions.togglePreviewCode()
          break
        }
        case 'upload': {
          this.props.infoActions.setUploadInfo({ show: !0 })
          break
        }
        default:
      }
    }
    setWebviewOffset() {
      let a = this.props,
        b = a.height / a.deviceScale,
        c = a.width / a.deviceScale
      this.webview &&
        this.webview.setAttribute(
          'style',
          `position:absolute;height:${b}px;width:${c}px`
        )
    }
    setUserAgentOverride() {
      let a = this.props.ua.replace('{{webviewID}}', this.props.id)
      ;(a += ` gameservice port/${global.messageCenterPort}`),
        this.webview.setUserAgentOverride(a)
    }
    doSimulateUpdate() {
      const b = this.props.simulateUpdate
      b
        ? (this.props.simulatorActions.setSimulateUpdate(!1),
          setTimeout(() => {
            o.triggerOnEvent({
              eventName: 'onUpdateStatusChange',
              data: { state: 'updating' }
            }),
              setTimeout(() => {
                o.triggerOnEvent({
                  eventName: 'onUpdateStatusChange',
                  data: { state: 'updateReady' }
                })
              }, a(1e3, 5e3))
          }, a(1e3, 5e3)))
        : setTimeout(() => {
            o.triggerOnEvent({
              eventName: 'onUpdateStatusChange',
              data: { state: 'noUpdate' }
            })
          }, a(1e3, 5e3))
    }
    initWebview() {
      this.session = +new Date()
      let a = this.props
      this.resetStatus()
      let b = p.get('gamesimulator', {
        width: a.width,
        height: a.height,
        dpr: a.dpr
      })
      this.webview && this.webview.detach(),
        (this.webview = b),
        this.setWebviewOffset(),
        b.attach(this.container),
        this.setUserAgentOverride(),
        this.setupBBSLogWorkerListener(),
        this.initEvent(b)
      const c = a.simulateUpdate,
        e = () => {
          this.props.setGame({ webview: b })
          let a = () => {
            b.off('loadcommit', a), (this.loaded = !0)
          }
          ;(b.src = `http://127.0.0.1:${global.proxyPort}/game/gamePage.html`),
            b.on('loadcommit', a),
            v.initWebview(b._webview),
            this.props.gameLaunch(),
            setTimeout(this.tryCaptureScreenForBackground.bind(this), 2e3),
            b.off('loadcommit', e),
            this.doSimulateUpdate()
        }
      b.on('loadcommit', e),
        (b.src = `about:blank`),
        (this.bbsLogConfig = d.cloneDeep(this.props.bbsLogConfig || []))
      try {
        global.worker.bbsLogWorker.postMessage({
          msgType: 'updateConfig',
          msgData: this.bbsLogConfig
        })
      } catch (a) {}
    }
    initEvent(a) {
      ;(a.onRequestBeforeSendHeaders = a => {
        let b = this.props.project
        if (b) {
          let d = a.url
          if ('main_frame' === a.type && d.match(/\?load$/))
            return this.restart(), { cancel: !0 }
          if (
            'main_frame' === a.type &&
            `http://127.0.0.1:${global.proxyPort}/game/gamePage.html` != d
          )
            return { cancel: !0 }
          if (
            0 !== d.indexOf(`http://127.0.0.1:${global.proxyPort}`) &&
            'none' == this.props.networkType
          )
            return (
              v.display({
                command: w.DISPLAY_ERROR,
                data: {
                  title: x.config.NO_NETWORK_TIPS_TITLE,
                  error: { message: x.config.NO_NETWORK_TIPS_CONTENT.format(d) }
                }
              }),
              { cancel: !0 }
            )
          if (0 == d.indexOf(`http://127.0.0.1:${global.proxyPort}/game/`)) {
            let a = C.parse(d),
              b = a.pathname.replace(/^\/game\//, '')
            if (this.props.appConfig) {
              let a = e.checkInGameSubPackage(this.props.appConfig, b)
              if (a && !this.subPackageLoading[a.root])
                return (
                  v.display({
                    command: w.DISPLAY_ERROR,
                    data: {
                      title: x.config.RESOURCE_RELATIVE_TIPS_TITLE,
                      error: {
                        message: x.config.RESOURCE_SUBPACKAGE_TIPS.format(b)
                      }
                    }
                  }),
                  { cancel: !0 }
                )
            }
          }
          let f = a.requestHeaders || [],
            g = f.findIndex(a => {
              return 'cookie' === a.name.toLowerCase()
            })
          f.splice(g, 1)
          for (var c = 0; c < f.length; ++c)
            if (
              ('_Cookie' === f[c].name && (f[c].name = 'Cookie'),
              'Referer' === f[c].name)
            ) {
              let a = b.appid
              b.platform && b.ext_appid && (a = b.ext_appid),
                (f[
                  c
                ].value = `https://servicewechat.com/${a}/devtools/page-frame.html`)
            }
          return { requestHeaders: a.requestHeaders }
        }
      }),
        (a.onRequestHeadersReceived = a => {
          let { type: b } = a
          if ('xmlhttprequest' === b) {
            let b = a.responseHeaders || [],
              c = {}
            return (
              b.forEach(a => {
                let { name: b, value: d } = a
                c[b] || (c[b] = []), c[b].push(d)
              }),
              b.push({ name: 'for-weapp-devtools', value: JSON.stringify(c) }),
              { responseHeaders: b }
            )
          }
          return {}
        }),
        (a.onBeforeRequest = a => {
          let b = a.url
          if (E.test(b) || F.test(b) || G.test(b))
            return {
              redirectUrl: b.replace(
                /^https?:\/\//,
                `$&127.0.0.1:${global.proxyPort}/`
              )
            }
        }),
        a.on('dialog', a => {
          let b = a.messageType || '',
            c = a.messageText,
            d = a.dialog
          if ('alert' === b) {
            if ('DOCUMENT_READY' === c) this.onDocumentReady()
            else if (0 === c.indexOf('SET_SOCKET_HEADER:'))
              try {
                let a = JSON.parse(c.replace('SET_SOCKET_HEADER:', ''))
                D = a
              } catch (a) {}
            else if ('NEED_ENTER_FOREGROUND' === c) {
              let a = i.SCENE_DEFAULT,
                b = {}
              try {
                let c = this.props.project.condiction.game,
                  d = c.list,
                  e = c.current
                ;(a = d && d[e] ? d[e].scene : a),
                  (b = d && d[e] ? d[e].query : b),
                  (b = t.parse(b))
              } catch (a) {}
              s('', { scene: a, query: b })
            } else if (0 == c.indexOf('SUBPACKAGE_READY_')) {
              let a = c.replace(/^SUBPACKAGE_READY_/, '')
              o.triggerOnEvent({
                eventName: 'onLoadSubPackageTaskStateChange',
                data: {
                  moduleName: a,
                  state: 'success',
                  taskId:
                    this.props.subPackageLoaded[a] &&
                    this.props.subPackageLoaded[a].taskId
                }
              }),
                this.props.simulatorActions.setGameSubPackage(a, !0)
            } else if (0 == c.indexOf('SUBPACKAGE_PROGRESS_')) {
              let a = c.match(/SUBPACKAGE_PROGRESS_([0-9\.]*)_([0-9\.]*)/),
                b = c.replace(/SUBPACKAGE_PROGRESS_([0-9\.]*)_([0-9\.]*)_/, ''),
                d = parseInt(100 * parseFloat(a[1])),
                e = parseInt(a[2]),
                f = parseInt((e * d) / 100)
              o.triggerOnEvent({
                eventName: 'onLoadSubPackageTaskStateChange',
                data: {
                  moduleName: b,
                  progress: d,
                  state: 'progressUpdate',
                  totalBytesWritten: f,
                  totalBytesExpectedToWrite: e,
                  taskId:
                    this.props.subPackageLoaded[b] &&
                    this.props.subPackageLoaded[b].taskId
                }
              })
            }
          } else if ('confirm' === b) a.preventDefault()
          else if ('prompt' === b)
            if ((a.preventDefault(), /^____sdk____/.test(c))) {
              let b = JSON.parse(c.replace(/^____sdk____/, '')),
                d = b.command
              'APPSERVICE_INVOKE' === d &&
                ((this.syncDialogMap[b.data.callbackID] = a.dialog),
                this.props.assdkActions.exec(b.data))
            } else a.dialog.ok('')
        }),
        a.on('consolemessage', a => {
          if (
            a.sourceId.match(/http:\/\/127\.0\.0\.1:\d+\/game\/__dev__\//) &&
            !(1 > a.level)
          ) {
            const b = a.message
            if (b)
              try {
                this.bbsLogConfig &&
                  global.worker.bbsLogWorker.postMessage({
                    msgType: 'evaluate',
                    msgData: {
                      message: a.message,
                      context: {
                        libVersion:
                          this.props.project && this.props.project.libVersion
                      },
                      ext: {
                        session: this.session,
                        level: a.level,
                        message: a.message
                      }
                    }
                  })
              } catch (a) {
                y.error(a)
              }
          }
        })
    }
    restart() {
      ;(this.session = +new Date()),
        clearTimeout(this.restartTimer),
        (this.restartTimer = setTimeout(() => {
          if (!this.webview) return this.initWebview()
          if (!this.loaded || !this.webview || !this.props.appConfig) return
          this.resetStatus(), this.doSimulateUpdate()
          let a = () => {
            clearTimeout(this.deathDetectTimer),
              this.webview.off('loadcommit', a),
              (this.loaded = !0)
          }
          ;(this.webview.src = `http://127.0.0.1:${
            global.proxyPort
          }/game/gamePage.html`),
            this.webview.on('loadcommit', a),
            this.props.gameLaunch(),
            (this.bbsLogConfig = d.cloneDeep(this.props.bbsLogConfig || []))
          try {
            global.worker.bbsLogWorker.postMessage({
              msgType: 'updateConfig',
              msgData: this.bbsLogConfig
            })
          } catch (a) {}
          this.deathDetectTimer = setTimeout(() => {
            this.props.infoActions.showError(
              '\u5C0F\u6E38\u620F\u91CD\u542F\u8017\u65F6\u8FC7\u4E45\uFF0C\u8BF7\u786E\u8BA4\u4E1A\u52A1\u903B\u8F91\u4E2D\u662F\u5426\u6709\u590D\u6742\u8FD0\u7B97\uFF0C\u6216\u8005\u6B7B\u5FAA\u73AF'
            ),
              this.initWebview()
          }, 15000)
        }, 1e3))
    }
    resetStatus() {
      ;(this.loaded = !1),
        (this.taskMap = {}),
        (this.subPackageLoading = {}),
        (this.syncDialogMap = {})
    }
    onDocumentReady() {
      this.props.setAppLaunched(!0), this.setWebviewOffset()
    }
    checkSubPackages() {
      for (let a in this.props.subPackageLoaded) {
        let b = this.props.subPackageLoaded[a]
        if (!b.loaded && !this.subPackageLoading[a]) {
          this.subPackageLoading[a] = !0
          let b = async () => {
            let b = await B(this.props.project, a)
            this.webview.executeScript({ code: b }, () => {})
          }
          this.props.appLaunched
            ? b()
            : (!this.taskMap.appLaunched && (this.taskMap.appLaunched = []),
              this.taskMap.appLaunched.push(b))
        } else
          this.taskMap[a] &&
            0 < this.taskMap[a].length &&
            (this.taskMap[a].forEach(a => {
              a()
            }),
            delete this.taskMap[a])
      }
    }
    render() {
      let a = this.props,
        b = { height: a.height, width: a.width, position: 'absolute' }
      return c.createElement('div', {
        className: 'webview',
        ref: a => (this.container = a),
        style: b
      })
    }
  }
  module.exports = K(
    a => {
      let b = a.toolbar.deviceInfo,
        c = a.project.current,
        d = a.simulator.appConfig || {},
        e =
          a.simulator.orientation &&
          'landscape' == a.simulator.orientation.value,
        f = e ? b.screenWidth : b.screenHeight
      return {
        ua: b.ua || '',
        width: e ? b.screenHeight : b.screenWidth,
        height: f,
        dpr: b.dpr,
        id: 2e4,
        project: a.project.current,
        ready: a.simulator.game && a.simulator.game.ready,
        appConfig: a.simulator.appConfig,
        device: b,
        appLaunched: a.simulator.appLaunched,
        compileCommand: a.simulator.compileCommand,
        libVersion: c.libVersion,
        assdkCallbackInfo: a.simulator.assdkCallbackInfo,
        interfaceCallbackInfo: a.simulator.interfaceCallbackInfo,
        decryptedInfo: a.simulator.decryptedInfo,
        deviceScale: a.toolbar.deviceScale,
        captureScreen: a.simulator.captureScreen,
        networkType:
          a.toolbar.network.list[a.toolbar.network.current] || 'wifi',
        bbsLogConfig: a.config.bbsLogConfig,
        simulateUpdate: a.simulator.simulateUpdate,
        subPackageLoaded: a.simulator.gameSubPackageLoaded
      }
    },
    a => {
      return {
        simulatorActions: e.bindActionCreators(g, a),
        projectActions: e.bindActionCreators(h, a),
        assdkActions: e.bindActionCreators(j, a),
        setGame: e.bindActionCreators(g.setGame, a),
        setAppLaunched: e.bindActionCreators(g.setAppLaunched, a),
        gameLaunch: e.bindActionCreators(g.gameLaunch, a),
        infoActions: e.bindActionCreators(k, a)
      }
    }
  )(L)
})(require('lazyload'), require)
