package com.sybotan.android.demo.activities

import android.os.Bundle
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import cn.sagacloud.android.cadengine.types.FloorData
import com.framework.mvvm.model.db.entity.task.InfosforFloor
import com.framework.mvvm.model.db.entity.task.ObjectEntity
import com.google.gson.Gson
import com.sybotan.android.demo.R
import com.sybotan.android.demo.bean.SpaceInfo
import com.sybotan.android.demo.bean.model3d.FunctionEndBlockModel
import com.sybotan.android.demo.bean.model3d.SetFloorPathModel
import com.sybotan.android.demo.bean.model3d.SpaceData3D
import com.sybotan.android.demo.data.PageParam
import com.sybotan.android.demo.tools.ToastUtils
import com.sybotan.android.demo.viewmodel.Space3DVM
import com.sybotan.base.utils.SJsonUtil
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.android.closestDI
import java.io.File

class Space3DActivity : BaseActivity(), DIAware {

    override val di: DI by closestDI()
    var isLastSpace = false
    private lateinit var buildingId: String
    private lateinit var floorId: String
    private lateinit var projectId: String
    private lateinit var floorEntity: ObjectEntity

    companion object {
        private lateinit var webview: WebView
        lateinit var viewModel: Space3DVM
        val gson = Gson()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_space3_dactivity)
        val floor = intent.getBundleExtra("floor")!!
        buildingId = floor.getString("buildingId", "")
        floorId = floor.getString("floorId", "")
        projectId = floor.getString("projectId", "")
        webview = findViewById(R.id.webview)
        webview.clearCache(true)
        val settings: WebSettings = webview.settings
        settings.javaScriptEnabled = true
        settings.defaultTextEncodingName = "utf-8"
        settings.builtInZoomControls = true
        settings.loadsImagesAutomatically = true
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        // 是否启动概述模式浏览界面，当页面宽度超过WebView显示宽度时，缩小页面适应WebView。默认false
        settings.loadWithOverviewMode = true
        settings.domStorageEnabled = true
        settings.databaseEnabled = true
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        WebView.setWebContentsDebuggingEnabled(true)
        webview.addJavascriptInterface(this, "android")
        webview.webViewClient = MyWebViewClient()
        webview.loadUrl("http://60.205.177.43:8000/APP/")
//        webview.loadUrl("file:///android_asset/dist/index.html")


        viewModel = Space3DVM(this.application, { name, param ->
            when (name) {
                Space3DVM.FLOOR_SPACE -> {
                    val spaces = param as ArrayList<ObjectEntity>
                    val spaceDataList = ArrayList<SpaceData3D>()
                    val space3D = SpaceData3D()
                    for (space in spaces) {
                        val id = SpaceData3D.ID()
                        id.ID = space.id
                        val info = gson.fromJson(space.infos, SpaceInfo::class.java)
                        val outLineString = gson.toJson(info.outline)
                        id.OutLine = outLineString.replace("\"", "\\\"")
                        val floorInfo = gson.fromJson(floorEntity.infos, InfosforFloor::class.java)
                        id.FloorElevation = floorInfo.floorElevation
                        space3D.ID.add(id)
                        if (space3D.ID.size >= 5 || space == spaces[spaces.size - 1]) {
                            if (space === spaces[spaces.size - 1]) {
                                Thread.sleep(300)
                                isLastSpace = true
                            }
                            spaceDataList.add(space3D)
                            val sss = gson.toJson(spaceDataList)
                            webview.loadUrl("javascript:SetSpaceData('${sss}')")
                            space3D.ID.clear()
                            spaceDataList.clear()
                        }
                    }


                }
                Space3DVM.FLOOR_OBJECT -> {
                    floorEntity = param as ObjectEntity
                }
            }
        }, this, projectId, buildingId, floorId)
    }


    @JavascriptInterface
    fun MeshClick(meshObject: String) {
        runOnUiThread {
            ToastUtils.showMyToast("选中了ID:${meshObject}")
        }
    }

    @JavascriptInterface
    fun FunctionEndBlock(name: String) {
        val nameObject = gson.fromJson(name, FunctionEndBlockModel::class.java)
        when (nameObject.Name) {
            "OpenPage" -> {
//                runOnUiThread { webview.loadUrl("javascript:OpenTestData()") }
                runOnUiThread { viewModel.getFloorSpace() }
            }
            "SetSpaceData" -> {
                if (isLastSpace) {
                    runOnUiThread {
                        val model = SetFloorPathModel()
                        webview.loadUrl("javascript:SetFloorPath('${gson.toJson(model)}')")
                    }
                }
            }
            "SetFloorPath" -> {
                runOnUiThread {
                    webview.loadUrl("javascript:LoadAllModelWithFloor()")
                }
            }
            "OpenTestData" -> {
                runOnUiThread { webview.loadUrl("javascript:LoadAllModelWithFloor()") }
            }
        }
    }

    class MyWebViewClient : WebViewClient() {
        //兼容低版本
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            if (view.progress == 100) {
//            viewModel.getFloorSpace()
                val pageParam = PageParam()
                val param = PageParam.Param()
                param.PageType = "1"
                pageParam.Param = param
                webview.loadUrl("javascript:OpenPage('${gson.toJson(pageParam)}')")
            }
        }
    }
}