package com.sybotan.android.demo.activities

import android.content.Intent
import android.graphics.PointF
import android.os.Bundle
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import android.widget.TextView
import com.framework.mvvm.model.db.entity.task.InfosforEq
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.bean.result.Position
import com.sybotan.android.demo.bean.result.Z
import com.sybotan.android.demo.data.PageParam
import com.sybotan.android.demo.tools.ObjectNameUtils
import com.sybotan.android.demo.viewmodel.Scene3DVM
import com.sybotan.android.demo.viewmodel.Space3DVM
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.android.closestDI

class Scene3DActivity : 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
        private lateinit var viewModel: Scene3DVM
        private val gson = Gson()
    }

    private lateinit var title: TextView
    private lateinit var equipDetail: TextView
    private lateinit var equipDelete: TextView
    private lateinit var bottomLl: LinearLayout
    private lateinit var equipObject: ObjectEntity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scene3_dactivity)
        val floor = intent.getBundleExtra("floor")!!
        buildingId = floor.getString("buildingId", "")
        floorId = floor.getString("floorId", "")
        projectId = floor.getString("projectId", "")
        webview = findViewById(R.id.webview)
        title = findViewById(R.id.title)
        equipDetail = findViewById(R.id.equipDetail)
        equipDelete = findViewById(R.id.equipDelete)
        bottomLl = findViewById(R.id.bottomLl)
        val settings: WebSettings = webview.getSettings()
        settings.javaScriptEnabled = true
        settings.defaultTextEncodingName = "utf-8"
        settings.builtInZoomControls = true
        settings.loadsImagesAutomatically = true
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webview.webViewClient = MyWebViewClient()
        settings.loadWithOverviewMode = true
        settings.domStorageEnabled = true
        settings.databaseEnabled = true
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        webview.addJavascriptInterface(this, "android")
        webview.loadUrl("http://60.205.177.43:8000/APP/#/?PageType=2")

        viewModel = Scene3DVM(this.application, { name, params ->
            when (name) {
                Scene3DVM.EQUIP_OBJECT -> {
                    if (params != null) {
                        equipObject = params as ObjectEntity
                        title.text = "本地名称：${equipObject.localName} , 本地编码：${equipObject.localId} , 数字化交付编码：${ObjectNameUtils.getEquipName(equipObject)}"
                    } else {
                        title.text = ""
                    }
                }
                Scene3DVM.FLOOR_SPACE -> {

                    val spaces = params as ArrayList<ObjectEntity>
                    val spaceDataList = ArrayList<SpaceData3D>()
                    val space3D = SpaceData3D()
                    for (space in spaces) {
                        val id = SpaceData3D.ID()
                        id.ID = space.id
                        id.IsShow = false
                        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()
                        }
                    }
                }
                Scene3DVM.FLOOR_OBJECT -> {
                    floorEntity = params as ObjectEntity
                }
            }
        }, this, projectId, buildingId, floorId)
        equipDetail.setOnClickListener {
            val intent = Intent(this@Scene3DActivity, EquipDetailActivity::class.java)
            val infosForEq = gson.fromJson(equipObject.infos, InfosforEq::class.java)
            val bundle = Bundle()
            val positon = Position()
            positon.x = infosForEq.location.x().toString()
            positon.y = infosForEq.location.y().toString()
            val z = Z()
            z.offset = infosForEq.location.z().toString()
            z.region = infosForEq.zRegion
            positon.z = z
//            for (space in scene.tunableSpaceList) {
//                val isContain = Lasso.isPolygonContainsPoint(space.mPoints, android.graphics.Point(positon.x.toFloat().toInt(), -positon.y.toFloat().toInt()))
//                if (isContain) {
//                    bundle.putString("spaceId", space.data.id)
//                    break
//                }
//            }
            bundle.putSerializable("position", positon)
            bundle.putString("buildingId", equipObject.buildingId)
            bundle.putString("floorId", equipObject.floorId)
            bundle.putString("deviceId", equipObject.id)
            bundle.putString("projectId", equipObject.projectId)
//            bundle.putString("floorMap", floorMap)
            bundle.putFloat("scale", 0f)
            bundle.putParcelable("centerPoint", PointF(0f, 0f))
            intent.putExtra("equip", bundle)
            startActivity(intent)
        }
    }

    @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()
                        val floorInfo = gson.fromJson(floorEntity.infos, InfosforFloor::class.java)
                        model.PorjectID = projectId
                        model.FloorID = floorInfo.bimIdPre
                        model.FloorElevation = floorInfo.floorElevation
                        webview.loadUrl("javascript:SetFloorPath('${gson.toJson(model)}')")
                    }
                }
            }
            "SetFloorPath" -> {
                runOnUiThread {
                    webview.loadUrl("javascript:LoadAllModelWithFloor()")
                }
            }
            "OpenTestData" -> {
                runOnUiThread { webview.loadUrl("javascript:LoadAllModelWithFloor()") }
            }
        }
    }

    @JavascriptInterface
    fun MeshClick(meshString: String) {
        runOnUiThread {
            viewModel.getObject(meshString)
            bottomLl.visibility = View.VISIBLE
        }
    }

    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 = "2"
                pageParam.Param = param
                webview.loadUrl("javascript:OpenPage('${gson.toJson(pageParam)}')")
            }
        }
    }
}