/*
 * ********************************************************************************************************************
 *
 *               iFHS7.
 *              ;BBMBMBMc                  rZMBMBR              BMB
 *              MBEr:;PBM,               7MBMMEOBB:             BBB                       RBW
 *     XK:      BO     SB.     :SZ       MBM.       c;;     ir  BBM :FFr       :SSF:    ;xBMB:r   iuGXv.    i:. iF2;
 *     DBBM0r.  :D     S7   ;XMBMB       GMBMu.     MBM:   BMB  MBMBBBMBMS   WMBMBMBBK  MBMBMBM  BMBRBMBW  .MBMBMBMBB
 *      :JMRMMD  ..    ,  1MMRM1;         ;MBMBBR:   MBM  ;MB:  BMB:   MBM. RMBr   sBMH   BM0         UMB,  BMB.  KMBv
 *     ;.   XOW  B1; :uM: 1RE,   i           .2BMBs  rMB. MBO   MBO    JMB; MBB     MBM   BBS    7MBMBOBM:  MBW   :BMc
 *     OBRJ.SEE  MRDOWOR, 3DE:7OBM       .     ;BMB   RMR7BM    BMB    MBB. BMB    ,BMR  .BBZ   MMB   rMB,  BMM   rMB7
 *     :FBRO0D0  RKXSXPR. JOKOOMPi       BMBSSWBMB;    BMBB:    MBMB0ZMBMS  .BMBOXRBMB    MBMDE RBM2;SMBM;  MBB   xBM2
 *         iZGE  O0SHSPO. uGZ7.          sBMBMBDL      :BMO     OZu:BMBK,     rRBMB0;     ,EBMB  xBMBr:ER.  RDU   :OO;
 *     ,BZ, 1D0  RPSFHXR. xWZ .SMr                  . .BBB
 *      :0BMRDG  RESSSKR. 2WOMBW;                   BMBMR
 *         i0BM: SWKHKGO  MBDv
 *           .UB  OOGDM. MK,                                          Copyright (c) 2015-2019.  斯伯坦机器人
 *              ,  XMW  ..
 *                  r                                                                     All rights reserved.
 *
 * ********************************************************************************************************************
 */

package com.sybotan.android.demo.activities

import android.content.Intent
import android.graphics.Color
import android.graphics.PointF
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.TextView
import android.widget.Toast
import cn.sagacloud.android.cadengine.FloorScene
import cn.sagacloud.android.cadengine.Opt
import cn.sagacloud.android.cadengine.items.*
import cn.sagacloud.android.cadengine.types.PipeLine
import cn.sagacloud.android.cadengine.types.Point
import cn.sagacloud.android.cadengine.types.Space
import cn.sagacloud.android.cadengine.types.TunableSpace
import cn.sagacloud.cadengine.HttpDownloadMap
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.sybotan.android.demo.R
import com.sybotan.android.demo.activities.poc.DeviceActivity
import com.sybotan.android.demo.activities.poc.RelationActivity
import com.sybotan.android.demo.adapter.PipeAdapter
import com.sybotan.android.demo.bean.result.*
import com.sybotan.android.demo.retrofit.BaseViewModelInterface
import com.sybotan.android.demo.tools.DensityUtils
import com.sybotan.android.demo.viewmodel.GraphyVM
import com.sybotan.android.graphy.events.SGraphyViewMoveEvent
import com.zbar.lib.CaptureActivity
import kotlinx.android.synthetic.main.activity_graphy.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.textColor
import org.jetbrains.anko.uiThread


class GraphyActivity : BaseActivity() {
    companion object {
        private val TAG = GraphyActivity::class.java.name

        /** 扫描二维码 */
        private val REQUEST_CODE_SCAN = 0x0000

        /** 添加设备成功 */
        private val REQUEST_CODE_EQUIP = 0x0001
    }

    /** viewModel */
    lateinit var graphyVM: GraphyVM

    /** 建筑Id */
    lateinit var buildingId: String

    /** 楼层Id */
    lateinit var floorId: String

    /** 楼层地图 */
    lateinit var floorMap: String

    /**
     * space 结构核查
     * survey 空间勘测
     */
    lateinit var from: String

    /** 实际距离 */
    val distance = 2500f

    /** 缩放后的同比例距离 */
    var realDistance = 0f

    /** 管道类型数据 */
    lateinit var pipeTypeList: ArrayList<PipeListModel>

    val scene = FloorScene()
    val gson = Gson()

    @Subscribe
    fun test(msg: SGraphyViewMoveEvent) {
        Log.d(TAG, "msg=$msg")

    } // test()

    /**
     * 创建Activity时的回调函数
     *
     * @param   savedInstanceState
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_graphy)
        // 注册eventbus
        EventBus.getDefault().register(this)
        /** 初始化数据 */
        initData()

        graphyView.scene = scene

        /** 开启异步 */
        doAsync {
            val downloadGZIPMap = HttpDownloadMap.downloadGZIPMap(floorMap)
            if (downloadGZIPMap != null) {
                scene.loadData(downloadGZIPMap!!)
            }
            /** 主线程处理ui */
            uiThread {
                /** 适应屏幕大小 */
                graphyView.fitSceneToView()
//                graphyView.defaultScale = graphyView.scale
                /** 限定移动范围不超出屏幕 */
//                graphyView.moveRange()
                graphyView.post {
                    Log.e("viewW", graphyView.width.toString())
                }

                Log.e("viewH", graphyView.measuredHeight.toString())
            }
        }
        /** 点击监听 */
        initListener()
        /** 图形点击-poc业务 */
        initSingleTopUp()
        /** 网络请求回调处理 */
        initViewModel()


        return
    } // Function onCreate()

    /**
     * 初始化数据
     */
    private fun initData() {
        var floor = intent.getBundleExtra("floor")
        buildingId = floor.getString("buildingId")
        floorId = floor.getString("floorId")
        floorMap = floor.getString("floorMap")
        from = floor.getString("from")
//        from = "12345"
    }

    /**
     * 图形点击事件
     * */
    private fun initSingleTopUp() {
        scene.setOnSingleTopUp(object : FloorScene.OnSingleTopUp {
            override fun onSingUp(x: Float, y: Float) {
                if ("pipe".equals(scene.type)) {
                    return
                }
                //选中空间完毕界面逻辑
                if (scene.mapType.equals("space")) {
                    if ("space".equals(from)) {
                        quesDetail.visibility = View.GONE
                        if (!scene.choseSpace!!.data.jobStatus.equals("03")) {
                            spaceStructure.visibility = View.VISIBLE
                            spaceName.text = scene.choseSpace!!.data.localName
                            graphyVM.getProblem(scene.choseSpace)

                        }
                        graphyVM.getQrcode(scene.choseSpace)
                    } else {
                        if (equipLl.visibility == View.GONE) {
                            drawLl.visibility = View.VISIBLE
                            spaceName2.text = scene.choseSpace!!.data.localName
                            graphyVM.getSpaceEq(scene.choseSpace)
//                            graphyVM.spacePipe(scene.choseSpace)
                        }
                        equipLocation.setText("($x,$y)")

                    }
                    //未选中空间
                } else if (scene.mapType.equals("nothing")) {
                    spaceStructure.visibility = View.GONE
                    qrcodeLl.visibility = View.GONE
                    quesDetail.visibility = View.GONE
                    equipLl.visibility = View.GONE
                    drawLl.visibility = View.GONE
                    for (item in scene.pointItemList) {
                        scene.removeItem(item)
                    }
                    scene.pointItemList.clear()
                    for (item in scene.qrcodeItemList) {
                        scene.removeItem(item)
                    }
                    for (item in scene.equipList) {
                        scene.removeItem(item)
                    }
                    scene.equipList.clear()
                    scene.qrcodeItemList.clear()
                }

                //打点业务
                if ("dot".equals(scene.type)) {
                    scene.type = "normal"
                    addDot.alpha = 1f
                    scene.choseSpace?.let { graphyVM.addProblem(it, x, y) }
                    return
                }

                //查看模式下，判断问题点选中逻辑
                if ("normal".equals(scene.type)) {
                    realDistance = distance * scene.defaultPointScale / graphyView.scale
                    for (point in scene.pointItemList) {
                        val sqrt = Math.sqrt(
                                Math.pow(
                                        Math.abs(x - point.data.mX).toDouble(),
                                        2.0
                                ) + Math.pow(Math.abs(y - point.data.mY).toDouble(), 2.0)
                        ).toInt()
                        if (sqrt < realDistance) {
                            showDotDetail(point)
                            break
                        }
                    }

                    for (point in scene.equipList) {
                        val sqrt = Math.sqrt(
                                Math.pow(
                                        Math.abs(x - point.data.mX).toDouble(),
                                        2.0
                                ) + Math.pow(Math.abs(y - point.data.mY).toDouble(), 2.0)
                        ).toInt()
                        if (sqrt < realDistance) {
                            Toast.makeText(this@GraphyActivity, "${point.data.type}\n${point.data.remark}\n${point.data.position}", Toast.LENGTH_LONG).show()
                            break
                        }
                    }
                    return
                }

                //绑定二位码业务
                if ("qrcode".equals(scene.type)) {
                    qrcodeLl.visibility = View.VISIBLE
                    qrcodeLocation.setText("(${scene.point.mX},${scene.point.mY})")
                    spaceStructure.visibility = View.GONE
                    return
                }
            }
        })
    }

    /**
     * 页面全部监听事件
     */
    private fun initListener() {
        /** nfc点击监听 */
        nfc.setOnClickListener { Toast.makeText(this, "正在开发中，敬请期待", Toast.LENGTH_SHORT).show() }

        /** checkBox */
        modelCheckBox.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                modelSubmit.isEnabled = true
                modelSubmit.alpha = 1f
            } else {
                modelSubmit.isEnabled = false
                modelSubmit.alpha = 0.3f
            }
        }

        /** checkBox */
        sceneCheckBox.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                sceneSubmit.isEnabled = true
                sceneSubmit.alpha = 1f
            } else {
                sceneSubmit.isEnabled = false
                sceneSubmit.alpha = 0.3f
            }
        }

        /** 设置空间的任务状态完成 */
        sceneSubmit.setOnClickListener {
            graphyVM.setJob(scene.choseSpace, codeEdit.text.toString(), "05")
        }

        /** 设置空间的任务状态完成 */
        modelSubmit.setOnClickListener {
            graphyVM.setJob(scene.choseSpace, codeEdit.text.toString(), "03")
        }

        /** 打点按钮 */
        addDot.setOnClickListener {
            scene.type = "dot"
            addDot.alpha = 0.3f
        }

        /** 绑定二维码按钮 */
        qrcode.setOnClickListener {
            scene.type = "qrcode"
            qrcodeLl.visibility = View.VISIBLE
            spaceStructure.visibility = View.GONE
        }

        /** 取消绑定二维码 */
        qrcodeCancel.setOnClickListener {
            qrcodeLl.visibility = View.GONE
            spaceStructure.visibility = View.VISIBLE
            scene.type = "normal"
            scene.item?.let { it1 -> scene.removeItem(it1) }
        }

        /** 取消绘制管道 */
        pipeCancel.setOnClickListener {
            pipeLl.visibility = View.GONE
            drawLl.visibility = View.VISIBLE
            scene.type = "normal"
            for (item in scene.drawingPipeItemList) {
                scene.removeItem(item)
            }
            scene.pipeLineList.clear()
            scene.drawingPipeItemList.clear()
        }

        /** 绑定二维码下一步 */
        qrcodeNext.setOnClickListener {
            val intent = Intent(this@GraphyActivity, CaptureActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE_SCAN)
        }

        /** 添加管线下一步 */
        pipeNext.setOnClickListener {
            for (model in pipeTypeList) {
                if (model.isCheck) {
                    graphyVM.addPipe(model, scene.pipeLineList, pipeEdit.text.toString(), scene.choseSpace)
                    break
                }
            }
        }


        /** 添加设备 */
        drawEquip.setOnClickListener {
            scene.type = "equip"
            drawLl.visibility = View.GONE
            equipLl.visibility = View.VISIBLE

        }

        /** 添加管线 */
        drawPipe.setOnClickListener {
            scene.type = "pipe"
            drawLl.visibility = View.GONE
            pipeLl.visibility = View.VISIBLE
//            piprRv.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
            piprRv.layoutManager = GridLayoutManager(this, 3, LinearLayoutManager.HORIZONTAL, false)
            graphyVM.pipeList()
        }

        /** 取消添加设备 */
        equipCancel.setOnClickListener {
            drawLl.visibility = View.VISIBLE
            equipLl.visibility = View.GONE
            scene.eqItem?.let { it1 -> scene.removeItem(it1) }
            scene.type = "normal"
        }

        /** 添加设备下一步 */
        equipNext.setOnClickListener {
            val intent = Intent(this, DeviceActivity::class.java)
            val bundle = Bundle()
            val positon = Position()
            positon.x = scene.point.mX.toString()
            positon.y = scene.point.mY.toString()
            val z = Z()
            z.offset = equipEdit.text.toString()
            when (equipRg.checkedRadioButtonId) {
                R.id.roof -> {
                    z.region = "roof"
                }
                R.id.floor -> {
                    z.region = "floor"
                }
                R.id.wall -> {
                    z.region = "wall"
                }
                R.id.air -> {
                    z.region = "air"
                }
            }
            positon.z = z
            bundle.putString("spaceId", scene.choseSpace!!.data.id)
            bundle.putSerializable("position", positon)
            intent.putExtra("equip", bundle)
            startActivityForResult(intent, REQUEST_CODE_EQUIP)
        }

        /** 服务 */
        eqSpServe.setOnClickListener { skipRelationship("eq_sp_serve", "eq_sp") }
        /** 控制 */
        eqEqCtrl.setOnClickListener { skipRelationship("eq_eq_ctrl", "eq_eq") }
        /** 测量 */
        eqEqSs.setOnClickListener { skipRelationship("eq_eq_ss", "eq_eq") }
        /** 供电 */
        eqEqPower.setOnClickListener { skipRelationship("eq_eq_power", "eq_eq") }
        /** 阀门 */
        eqEqVv.setOnClickListener { skipRelationship("eq_eq_vv", "eq_eq") }
        /** 连接 */
        eqPipeCnct.setOnClickListener { skipRelationship("eq_pipe_cnct", "eq_pipe") }
    }

    private fun skipRelationship(code: String, type: String) {
        val intent = Intent(this, RelationActivity::class.java)
        val bundle = Bundle()
        bundle.putString("spaceId", scene.choseSpace!!.data.id)
        bundle.putString("code", code)
        bundle.putString("type", type)
        intent.putExtra("params", bundle)
        startActivity(intent)
    }

    /**
     * 初始化viewModel
     */
    private fun initViewModel() {
        graphyVM = GraphyVM(BaseViewModelInterface { name, params ->
            when (name) {
                /** 查询空间和任务 */
                GraphyVM.SPACE_JOB -> {
                    for (item in scene.tunableSpaceList) {
                        scene.removeItem(item)
                    }
                    scene.tunableSpaceList.clear()

                    val list = params as (List<SpaceJobModel>)
                    for (model in list) {
                        if (!model.outline.isEmpty()) {
                            val space = Space()
                            space.outLine = model.outline.get(0)
                            space.name = model.name
                            val nameItem = SpaceNameItem(space)
                            nameItem.zOrder = 99999f
                            nameItem.isVisible = scene.isShowSpace
                            scene.spaceNameList.add(nameItem)
                            scene.addItem(nameItem)

                            val tunableSpace = TunableSpace()
                            tunableSpace.outLine = model.outline.get(0)
                            tunableSpace.name = model.name
                            tunableSpace.jobStatus = model.job
                            tunableSpace.id = model.id
                            tunableSpace.localName = model.localName
                            val item = TunableSpaceItem(tunableSpace, null)
                            scene.choseSpace?.let {
                                if (tunableSpace.id.equals(scene.choseSpace!!.data.id)) {
                                    item.paint.color = Opt.spaceChoseColor
                                    item.outPaint.color = Color.rgb(0xbd, 0xe8, 0xfe)
                                }
                            }
                            item.isVisible = true
                            item.zOrder = 99996f
                            scene.tunableSpaceList.add(item)
                            scene.addItem(item)
                        }
                    }
                    if (from.equals("scene")) {
                        graphyVM.floorPipe()
                    }
                }

                /** 添加空间核查问题 */
                GraphyVM.ADD_PROBLEM -> {
                    Toast.makeText(this, "记录成功", Toast.LENGTH_SHORT).show()
                    graphyVM.getProblem(scene.choseSpace)
                    graphyVM.getSpaceJob(from)
                }

                /** 查询空间核查问题 */
                GraphyVM.GET_PROBLEM -> {
                    for (item in scene.pointItemList) {
                        scene.removeItem(item)
                    }
                    scene.pointItemList.clear()
                    var list = params as ArrayList<ProblemsModel>
                    for (model in list) {
                        val point = Point()
                        var position = gson.fromJson(model.position, Position::class.java)
                        point.mX = position.x.toFloat()
                        point.mY = position.y.toFloat()
                        point.id = model.id
                        var item = PointItem(point, null, scene.defaultPointScale)
                        item.isVisible = true
                        item.zOrder = 100000f
                        scene.pointItemList.add(item)
                        scene.addItem(item)
                    }
                }

                /** 关闭空间核查问题 */
                GraphyVM.CLOSE_PROBLEM -> {
                    graphyVM.getProblem(scene.choseSpace)
                }

                /** 绑定二维码 */
                GraphyVM.BIND_QECODE -> {
                    Toast.makeText(this, "绑定成功", Toast.LENGTH_SHORT).show()
                    scene.type = "normal"
                    qrcodeLl.visibility = View.GONE
                    spaceStructure.visibility = View.VISIBLE
                    scene.removeItem(scene.item!!)
                    scene.qrcodeItemList.clear()
                    graphyVM.getQrcode(scene.choseSpace)
                }

                /** 查询对象绑定的二维码 */
                GraphyVM.GET_QECODE -> {
                    for (item in scene.qrcodeItemList) {
                        scene.removeItem(item)
                    }
                    scene.qrcodeItemList.clear()
                    val models = params as ArrayList<QrcodeModel>
                    for (model in models) {
                        val point = Point()
                        var position = gson.fromJson(model.position, Position::class.java)
                        point.mX = position.x.toFloat()
                        point.mY = position.y.toFloat()

                        var item = QrcodeItem(point, null, scene.defaultPointScale)
                        item.isVisible = true
                        item.zOrder = 100000f
                        scene.qrcodeItemList.add(item)
                        scene.addItem(item)
                    }
                }

                /** 设置空间的任务状态(新建和修改) */
                GraphyVM.SET_JOB -> {
                    Toast.makeText(this, "核查成功", Toast.LENGTH_SHORT).show()
                    refreshAll()
                    graphyVM.getSpaceJob(from)
                }

                /** 设置空间核查问题的信息和状态 */
                GraphyVM.SET_PROBLEM -> {
                    graphyVM.getSpaceJob(from)
                }

                /** 查询空间下的设备(所在关系) */
                GraphyVM.SPACE_EQ -> {
                    val list = params as List<SpaceEqModel>
                    for (item in scene.equipList) {
                        scene.removeItem(item)
                    }
                    scene.equipList.clear()
                    //流式布局
                    equipWwv.removeAllViews()
                    for (model in list) {
                        val textview = TextView(this)
                        textview.setText(model.type + "(${model.children.size})")
                        textview.setSingleLine()
                        textview.gravity = Gravity.CENTER
                        textview.textSize = 12f
                        textview.height = DensityUtils.dp2px(this, 30f)
                        if (model.isCheck) {
                            textview.background = resources.getDrawable(R.drawable.shape_filter_normal)
                            textview.textColor = resources.getColor(R.color.grey_900)
                        } else {
                            textview.background = resources.getDrawable(R.drawable.shape_filter_selected)
                            textview.textColor = resources.getColor(R.color.white)
                        }
                        textview.setOnClickListener {
                            model.isCheck = !model.isCheck
                            if (model.isCheck) {
                                textview.background = resources.getDrawable(R.drawable.shape_filter_normal)
                                textview.textColor = resources.getColor(R.color.grey_900)
                            } else {
                                textview.background = resources.getDrawable(R.drawable.shape_filter_selected)
                                textview.textColor = resources.getColor(R.color.white)
                            }
                            refreshEquip(list)
                        }
                        equipWwv.addView(textview)

                    }
                    refreshEquip(list)
                }

                /** 查询管道类型树 */
                GraphyVM.PIPE_LIST -> {
                    pipeTypeList = params as ArrayList<PipeListModel>
                    val adapter = PipeAdapter(this, pipeTypeList)
                    piprRv.adapter = adapter
                }

                /** 添加管线 */
                GraphyVM.ADD_PIPE -> {
                    pipeLl.visibility = View.GONE
                    drawLl.visibility = View.VISIBLE
                    scene.type = "normal"
                    for (item in scene.pipeItemList) {
                        scene.removeItem(item)
                    }
                    for (item in scene.drawingPipeItemList) {
                        scene.removeItem(item)
                    }
                    scene.pipeLineList.clear()
                    scene.pipeItemList.clear()
                    scene.drawingPipeItemList.clear()

                    graphyVM.floorPipe()
                }

                /** 查询空间下的管道 */
                GraphyVM.SPACE_PIPE -> {
                    val spacePipeModel = params as ArrayList<SpacePipeModel>

                    //流式布局
                    pipeWwv.removeAllViews()
                    for (model in spacePipeModel) {
                        val textview = TextView(this)
                        textview.setText(model.typeName + "(${model.children.size})")
                        textview.setSingleLine()
                        textview.gravity = Gravity.CENTER
                        textview.textSize = 12f
                        textview.height = DensityUtils.dp2px(this, 30f)
                        if (model.isCheck) {
                            textview.background = resources.getDrawable(R.drawable.shape_filter_normal)
                            textview.textColor = resources.getColor(R.color.grey_900)
                        } else {
                            textview.background = resources.getDrawable(R.drawable.shape_filter_selected)
                            textview.textColor = resources.getColor(R.color.white)
                        }
                        textview.setOnClickListener {
                            model.isCheck = !model.isCheck
                            if (model.isCheck) {
                                textview.background = resources.getDrawable(R.drawable.shape_filter_normal)
                                textview.textColor = resources.getColor(R.color.grey_900)
                            } else {
                                textview.background = resources.getDrawable(R.drawable.shape_filter_selected)
                                textview.textColor = resources.getColor(R.color.white)
                            }
                            refreshPipe(spacePipeModel)
                        }
                        pipeWwv.addView(textview)

                    }
                    refreshPipe(spacePipeModel)
                }
            }
        }, this, buildingId, floorId)
        graphyVM.getSpaceJob(from)
    }

    /**
     * 刷新地图上管线
     */
    private fun refreshPipe(spacePipeModel: ArrayList<SpacePipeModel>) {
        for (item in scene.pipeItemList) {
            scene.removeItem(item)
        }
        scene.pipeItemList.clear()

        for (model in spacePipeModel) {
            if (!model.children.isEmpty() && !model.isCheck) {
                for (child in model.children) {
                    val pipe = PipeLine()
                    var points: ArrayList<ArrayList<PointF>> = ArrayList()
                    points.add(child.position)
                    pipe.points!!.addAll(points)
                    val pipeItem = PipeLineItem(pipe, null)
                    pipeItem.isVisible = true
                    pipeItem.zOrder = 100000f
                    scene.pipeItemList.add(pipeItem)
                    scene.addItem(pipeItem)

                }
            }
        }
    }

    /**
     * 刷新地图上设备
     */
    private fun refreshEquip(list: List<SpaceEqModel>) {
        for (item in scene.equipList) {
            scene.removeItem(item)
        }
        scene.equipList.clear()
        for (model in list) {
            if (!model.children.isEmpty() && !model.isCheck) {
                for (child in model.children) {
                    val point = Point()
                    var position = gson.fromJson(child.position, Position::class.java)
                    point.mX = position.x.toFloat()
                    point.mY = position.y.toFloat()
                    point.remark = child.remark
                    point.type = model.type
                    point.position = child.position

                    var item = EquipItem(point, null, scene.defaultPointScale)
                    item.isVisible = true
                    item.zOrder = 100000f
                    scene.equipList.add(item)
                    scene.addItem(item)
                }
            }
        }
    }

    /**
     * 重置空间界面
     */
    private fun refreshAll() {
        for (item in scene.pointItemList) {
            scene.removeItem(item)
        }
        scene.pointItemList.clear()

        for (item in scene.tunableSpaceList) {
            scene.removeItem(item)
        }
        scene.tunableSpaceList.clear()

        for (item in scene.qrcodeItemList) {
            scene.removeItem(item)
        }
        scene.qrcodeItemList.clear()

        for (item in scene.equipList) {
            scene.removeItem(item)
        }
        scene.equipList.clear()

        spaceStructure.visibility = View.GONE
        quesDetail.visibility = View.GONE
        drawLl.visibility = View.GONE
        equipLl.visibility = View.GONE

        scene.type = "normal"
        modelCheckBox.isChecked = false
        codeEdit.setText("")
        equipLocation.setText("")
        roof.isChecked = false
        floor.isChecked = false
        wall.isChecked = false
        air.isChecked = false
        scene.point = Point()
    }

    /**
     * 显示点位信息框
     */
    private fun showDotDetail(point: PointItem) {
        spaceStructure.visibility = View.GONE
        quesDetail.visibility = View.VISIBLE
        quesTv.setText(
                "这是描述问题的文本，左侧是拍照图片。" +
                        "\n问题编码:${point.data.id}" +
                        "\nx轴:${point.data.mX}" +
                        "\ny轴:${point.data.mY}" +
                        "\n点击下方“问题已解决”按钮后可关闭该问题点。"
        )

        /** 问题已解决按钮 */
        quesSubmit.setOnClickListener {
            graphyVM.closeProblem(point, scene.choseSpace)
            spaceStructure.visibility = View.VISIBLE
            quesDetail.visibility = View.GONE
            scene.pointItemList.remove(point)
            scene.removeItem(point)
            if (scene.pointItemList.isEmpty()) {
                for (item in scene.tunableSpaceList) {
                    scene.removeItem(item)
                }
            }
            graphyVM.getSpaceJob(from)
        }
    }

    /**
     * 扫码返回uuid
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            /** 扫描二维码回传 */
            REQUEST_CODE_SCAN ->
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        //获取扫描结果
                        val bundle = data.extras
                        val result = bundle.getString(CaptureActivity.EXTRA_STRING)
                        Log.e("tag", "扫描结果：$result")
                        graphyVM.bindQrcode(
                                scene.choseSpace,
                                result,
                                scene.point,
                                qrcodeEdit.text.toString()
                        )
                    }
                }

            /** 添加设备成功 */
            REQUEST_CODE_EQUIP -> {
                if (resultCode == RESULT_OK) {
                    equipLocation.setText("")
                    equipEdit.setText("")
                    scene.eqItem?.let { it1 -> scene.removeItem(it1) }
                    roof.isChecked = false
                    floor.isChecked = false
                    wall.isChecked = false
                    air.isChecked = false
                    scene.point = Point()
                    scene.type = "normal"
                    equipLl.visibility = View.GONE
                    drawLl.visibility = View.VISIBLE
                    graphyVM.getSpaceEq(scene.choseSpace)
                }
            }
            else -> {
            }
        }
    }


} // Class GraphyActivity
