/*
 * ********************************************************************************************************************
 *
 *               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.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.PointF
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
import android.widget.Toast
import android.widget.*
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.sagacloud.android.cadengine.FloorScene
import cn.sagacloud.android.cadengine.Lasso
import cn.sagacloud.android.cadengine.Opt
import cn.sagacloud.android.cadengine.items.*
import cn.sagacloud.android.cadengine.types.*
import cn.sagacloud.android.cadengine.types.Space
import com.afollestad.materialdialogs.MaterialDialog
import com.arashivision.sdkcamera.camera.InstaCameraManager
import com.arashivision.sdkcamera.camera.callback.ICameraChangedCallback
import com.arashivision.sdkcamera.camera.callback.ICaptureStatusListener
import com.bumptech.glide.Glide
import com.framework.mvvm.mv.AdmViewModel
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.model.Response
import com.sybotan.android.demo.R
import com.sybotan.android.demo.activities.poc.RelationActivity
import com.sybotan.android.demo.adapter.PictureAdapter
import com.sybotan.android.demo.adapter.PipeAdapter
import com.sybotan.android.demo.bean.result.*
import com.sybotan.android.demo.graphy.GraphyHelper
import com.sybotan.android.demo.retrofit.BaseViewModelInterface
import com.sybotan.android.demo.retrofit.Constant
import com.sybotan.android.demo.tools.*
import com.sybotan.android.demo.view.MaxHeightRecyclerView
import com.sybotan.android.demo.viewmodel.GraphyVM
import com.sybotan.android.graphy.SGraphyView
import com.sybotan.android.graphy.events.SGraphyViewMoveEvent
import com.yuyh.library.imgsel.ImageLoader
import com.yuyh.library.imgsel.ImgSelConfig
import com.zbar.lib.CaptureActivity
import io.reactivex.ObservableEmitter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.jetbrains.anko.textColor
import org.json.JSONException
import org.json.JSONObject
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.android.closestDI
import org.kodein.di.android.x.viewmodel.viewModel
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import kotlin.collections.ArrayList


@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class GraphyActivity : BaseActivity(), ICaptureStatusListener, ICameraChangedCallback, DIAware {
    companion object {
        private val TAG = GraphyActivity::class.java.name

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

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

        /** 上次点击图形时间 */
        private var lastClickTime: Long = 0

        /** 是否显示了底图item */
        var isAddBaseMap: Boolean = false
    }

    override val di: DI by closestDI()

    private val mVm: AdmViewModel by viewModel()

    //选择图片
    private val REQUEST_CODE_PIC = 0X102

    // 自定义图片加载器
    private val loader =
        ImageLoader { context: Context?, path: String?, imageView: ImageView? ->
            Glide.with(
                context
            ).load(path).into(imageView)
        }
    private lateinit var spacePipeModel: java.util.ArrayList<SpacePipeModel>

    /** viewModel */
    lateinit var graphyVM: GraphyVM

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

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

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

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

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

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

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

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

    /** 底图item */
    lateinit var mapItem: BaseMapItem

    /**
     * 问题点坐标
     */
    val ProblemDot = Point()
    var addPoint: PointItem? = null

    /**
     * 问题图片列表
     */
    val beans: ArrayList<Photos> = ArrayList()
    lateinit var pictureAdapter: PictureAdapter

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

    } // test()

    private lateinit var graphyView: SGraphyView
    private lateinit var quesDetail: RelativeLayout
    private lateinit var spaceStructure: LinearLayout
    private lateinit var doneSpaceStructure: LinearLayout
    private lateinit var spaceName: TextView
    private lateinit var spaceName3: TextView
    private lateinit var spaceName4: TextView
    private lateinit var spaceName2: TextView
    private lateinit var equipLl: LinearLayout
    private lateinit var drawLl: LinearLayout
    private lateinit var equipLocation: TextView
    private lateinit var qrcodeLl: LinearLayout
    private lateinit var addDot: TextView
    private lateinit var nfc: TextView
    private lateinit var qrcodeLocation: TextView
    private lateinit var modelCheckBox: CheckBox
    private lateinit var modelSubmit: TextView
    private lateinit var sceneCheckBox: CheckBox
    private lateinit var sceneSubmit: TextView
    private lateinit var qrcode: TextView
    private lateinit var qrcodeCancel: TextView
    private lateinit var pipeCancel: TextView
    private lateinit var pipeLl: LinearLayout
    private lateinit var qrcodeNext: TextView
    private lateinit var pipeNext: TextView
    private lateinit var pipeEdit: EditText
    private lateinit var drawEquip: TextView
    private lateinit var drawPipe: TextView
    private lateinit var piprRv: RecyclerView
    private lateinit var problemPicRecycler: MaxHeightRecyclerView
    private lateinit var equipCancel: TextView
    private lateinit var equipNext: TextView
    private lateinit var equipEdit: EditText
    private lateinit var equipRg: RadioGroup
    private lateinit var eqSpServe: TextView
    private lateinit var eqEqCtrl: TextView
    private lateinit var eqEqSs: TextView
    private lateinit var eqEqPower: TextView
    private lateinit var eqEqVv: TextView
    private lateinit var eqPipeCnct: TextView
    private lateinit var equipWwv: WordWrapView
    private lateinit var pipeWwv: WordWrapView
    private lateinit var roof: RadioButton
    private lateinit var floor: RadioButton
    private lateinit var wall: RadioButton
    private lateinit var air: RadioButton
    private lateinit var quesTv: TextView
    private lateinit var quesSubmit: TextView
    private lateinit var addSpaceDetail: TextView
    private lateinit var addSpaceDetail2: TextView
    private lateinit var resetSpaceState: TextView
    private lateinit var qrcodeEdit: EditText
    private lateinit var webview: WebView
    private lateinit var quesIma: ImageView
    private lateinit var problemLl: LinearLayoutCompat
    private lateinit var problemClose: TextView
    private lateinit var problemDone: TextView
    private lateinit var problemSave: TextView
    private lateinit var equipDetail: TextView
    private lateinit var equipDelete: TextView
    private lateinit var problemDesc: AppCompatEditText

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

        /** 初始化数据 */
        initData()
        InstaCameraManager.getInstance().registerCameraChangedCallback(this)
        graphyView.scene = scene

        /** 开启异步 */
//        doAsync {
//            val downloadGZIPMap = HttpDownloadMap.downloadGZIPMap(floorMap)
//            downloadGZIPMap?.let {
//                scene.loadData(it)
//            }
//            /** 主线程处理ui */
//            uiThread {
//                /** 适应屏幕大小 */
//                graphyView.fitSceneToView()
////                graphyView.defaultScale = graphyView.scale
//                /** 限定移动范围不超出屏幕 */
////                graphyView.moveRange()
//                graphyView.post {
//                    Log.e("viewW", graphyView.width.toString())
////                    val mapItem = BaseMapItem(this@GraphyActivity, null)
////                    mapItem.zOrder = 1000000f
////                    mapItem.isVisible = true
////                    scene.addItem(mapItem)
//                    mapItem = BaseMapItem(this@GraphyActivity, null)
//                }
//
//                Log.e("viewH", graphyView.measuredHeight.toString())
//            }
//        }
        /** 点击监听 */
        initListener()
        /** 图形点击-poc业务 */
        initSingleTopUp()
        /** 网络请求回调处理 */
        initViewModel()

//        initGrid()
        return
    } // Function onCreate()

    /**
     * 模拟轴网
     */
    private fun initGrid() {
        val grid1 = Grid()
        val place1 = Place()
        place1.points = ArrayList<PointF>()
        val point1 = PointF()
        point1.x = 53587.82f
        point1.y = 28717.135f
        place1.points!!.add(point1)
        val point2 = PointF()
        point2.x = 53587.82f
        point2.y = -36885.92f
        place1.points!!.add(point2)
        grid1.location = place1
        grid1.name = "A"


        val grid3 = Grid()
        val place3 = Place()
        place3.points = ArrayList<PointF>()
        val point5 = PointF()
        point5.x = 44587.82f
        point5.y = 28717.135f
        place3.points!!.add(point5)
        val point6 = PointF()
        point6.x = 44587.82f
        point6.y = -36885.92f
        place3.points!!.add(point6)
        grid3.location = place3
        grid3.name = "B"

        val grid2 = Grid()
        val place2 = Place()
        place2.points = ArrayList<PointF>()
        val point3 = PointF()
        point3.x = -16887.006f
        point3.y = 7738.7656f
        place2.points!!.add(point3)
        val point4 = PointF()
        point4.x = 152855.56f
        point4.y = 9129.109f
        place2.points!!.add(point4)
        grid2.location = place2
        grid2.name = "X"

        val gridItem1 = GridItem(grid1, null, graphyView)
        gridItem1.zOrder = 1000009f
        val gridItem2 = GridItem(grid2, null, graphyView)
        gridItem2.zOrder = 1000009f
        val gridItem3 = GridItem(grid3, null, graphyView)
        gridItem3.zOrder = 1000009f

        scene.addItem(gridItem1)
        scene.addItem(gridItem2)
        scene.addItem(gridItem3)

    }


    private fun initView() {
        graphyView = findViewById(R.id.graphyView)
        quesDetail = findViewById(R.id.quesDetail)
        spaceStructure = findViewById(R.id.spaceStructure)
        doneSpaceStructure = findViewById(R.id.doneSpaceStructure)
        spaceName = findViewById(R.id.spaceName)
        spaceName2 = findViewById(R.id.spaceName2)
        spaceName3 = findViewById(R.id.spaceName3)
        spaceName4 = findViewById(R.id.spaceName4)
        equipLl = findViewById(R.id.equipLl)
        drawLl = findViewById(R.id.drawLl)
        equipLocation = findViewById(R.id.equipLocation)
        qrcodeLl = findViewById(R.id.qrcodeLl)
        addDot = findViewById(R.id.addDot)
        nfc = findViewById(R.id.nfc)
        qrcodeLocation = findViewById(R.id.qrcodeLocation)
        modelCheckBox = findViewById(R.id.modelCheckBox)
        modelSubmit = findViewById(R.id.modelSubmit)
        sceneCheckBox = findViewById(R.id.sceneCheckBox)
        sceneSubmit = findViewById(R.id.sceneSubmit)
        qrcode = findViewById(R.id.qrcode)
        qrcodeCancel = findViewById(R.id.qrcodeCancel)
        pipeCancel = findViewById(R.id.pipeCancel)
        pipeLl = findViewById(R.id.pipeLl)
        qrcodeNext = findViewById(R.id.qrcodeNext)
        pipeNext = findViewById(R.id.pipeNext)
        pipeEdit = findViewById(R.id.pipeEdit)
        drawEquip = findViewById(R.id.drawEquip)
        drawPipe = findViewById(R.id.drawPipe)
        piprRv = findViewById(R.id.piprRv)
        problemPicRecycler = findViewById(R.id.problemPicRecycler)
        equipCancel = findViewById(R.id.equipCancel)
        equipNext = findViewById(R.id.equipNext)
        equipEdit = findViewById(R.id.equipEdit)
        equipRg = findViewById(R.id.equipRg)
        eqSpServe = findViewById(R.id.eqSpServe)
        eqEqCtrl = findViewById(R.id.eqEqCtrl)
        eqEqSs = findViewById(R.id.eqEqSs)
        eqEqPower = findViewById(R.id.eqEqPower)
        eqEqVv = findViewById(R.id.eqEqVv)
        eqPipeCnct = findViewById(R.id.eqPipeCnct)
        equipWwv = findViewById(R.id.equipWwv)
        pipeWwv = findViewById(R.id.pipeWwv)
        roof = findViewById(R.id.roof)
        floor = findViewById(R.id.floor)
        wall = findViewById(R.id.wall)
        air = findViewById(R.id.air)
        quesTv = findViewById(R.id.quesTv)
        quesSubmit = findViewById(R.id.quesSubmit)
        qrcodeEdit = findViewById(R.id.qrcodeEdit)
        webview = findViewById(R.id.webview)
        quesIma = findViewById(R.id.quesIma)
        addSpaceDetail = findViewById(R.id.addSpaceDetail)
        addSpaceDetail2 = findViewById(R.id.addSpaceDetail2)
        resetSpaceState = findViewById(R.id.resetSpaceState)
        problemLl = findViewById(R.id.problemLl)
        problemClose = findViewById(R.id.problemClose)
        problemDone = findViewById(R.id.problemDone)
        problemSave = findViewById(R.id.problemSave)
        equipDetail = findViewById(R.id.equipDetail)
        equipDelete = findViewById(R.id.equipDelete)
        problemDesc = findViewById(R.id.problemDesc)

    }

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

    private fun addPic() {
        val config: ImgSelConfig = ImgSelConfig.Builder(this, loader) // 是否多选
            .multiSelect(true) // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
            .rememberSelected(false) // 确定按钮文字颜色
            .btnTextColor(Color.WHITE) // 使用沉浸式状态栏
            .statusBarColor(resources.getColor(R.color.blue_2E3679)) // 返回图标ResId
            .backResId(R.mipmap.back_gray).title("选择图片").titleColor(Color.WHITE).titleBgColor(
                resources.getColor(R.color.blue_2E3679)
            ) //                .allImagesText("All Images")
            .needCrop(false).cropSize(1, 1, 200, 200) // 第一个是否显示相机
            .needCamera(true) // 最大选择图片数量
            .build()
        //选择图片activity
        //选择图片activity
        Repair_ImgSelActivity.startActivity(this, config, REQUEST_CODE_PIC)
    }

    private fun doPicDatas(pathList: List<String>?) {
        LocalDataOperation.getInstance().dealLocalData<Photos>(this) { name, params ->
            when (name) {
                LocalDataOperation.SHOW_DIALOG_IN_MAIN -> ToastUtils.showMyToast("图片上传中")
                LocalDataOperation.DEAL_IO_DATA -> {
                    val emitter =
                        params as ObservableEmitter<String>
                    for (s in pathList!!) {
                        Log.e("已选择图片的路径为-----", s!!)
                        val path: String =
                            PictureUtils.compressImage(s, getOfflineImagePath(), 100)
                        val picFile = File(path)
                        if (picFile.exists()) {
                            val key = picFile.name
                            if (isHaveInternet()) {
                                val url: String = Constant.ServerImgIPUp + key
                                val str = UploadImage.uploadFiles(picFile, url)
                                if (!TextUtils.isEmpty(str)) {
                                    var resultString: String? = null
                                    try {
                                        val `object` = JSONObject(str)
                                        resultString = `object`.getString("Result")
                                    } catch (e: JSONException) {
                                        e.printStackTrace()
                                    }
                                    if ("success" == resultString) {
                                        val photos =
                                            Photos()
                                        photos.itemType = 0
                                        photos.path = path
                                        photos.key = key
                                        beans.add(photos)

                                    }
                                }
                            } else {
                                val photos =
                                    Photos()
                                photos.itemType = 0
                                photos.path = path
                                photos.key = key
                                beans.add(photos)
                            }
                        }
                    }
                    emitter.onNext("")
                }
                LocalDataOperation.DEAL_DATA_NEXT -> {
                    ToastUtils.showMyToast("图片上传完毕")
                    pictureAdapter.notifyDataSetChanged()
                }
                LocalDataOperation.DEAL_DATA_ERROR -> {
                    ToastUtils.showMyToast("图片上传失败")
                }
                else -> {
                }
            }
        }
    }


    /**
     * 防止用户连续点击
     *
     * @return true:连续点击 false：单次点击
     */
    fun isFastDoubleClick(): Boolean {
        val time = System.currentTimeMillis()
        val timeD = time - lastClickTime
        if (0 < timeD && timeD < 300) {
            return true
        }
        lastClickTime = time
        return false
    }

    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)
        }
    }

    /**
     * 图形点击事件
     * */
    private fun initSingleTopUp() {
        scene.setOnSingleTopUp(object : FloorScene.OnSingleTopUp {
            @SuppressLint("SetJavaScriptEnabled")
            override fun onSingUp(x: Float, y: Float) {
                //如果只是查看模式，可以选中空间，进行空间内业务操作
                if ("normal".equals(scene.type)) {
                    var hasChose = false
                    for (space in scene.tunableSpaceList) {
                        val polygonContainsPoint = Lasso.isPolygonContainsPoint(
                            space.mPoints,
                            android.graphics.Point(x.toInt(), -y.toInt())
                        )
                        if (polygonContainsPoint) {
                            if (hasChose) {
                                if (space.calculateArea() < scene.choseSpace!!.calculateArea()) {
                                    space.outPaint.color = Color.rgb(0xbd, 0xe8, 0xfe)
                                    space.outPaint.strokeWidth = 500f
                                    space.paint.color = Opt.spaceChoseColor
                                    scene.mapType = "space"
                                    scene.choseSpace = space
                                    hasChose = true

                                }
                            } else {
                                space.outPaint.color = Color.rgb(0xbd, 0xe8, 0xfe)
                                space.paint.color = Opt.spaceChoseColor
                                space.outPaint.strokeWidth = 500f
                                scene.mapType = "space"
                                scene.choseSpace = space
                                hasChose = true
                            }
                        } else {
                            space.paint.color = Opt.spaceColor
                            space.outPaint.strokeWidth = 50f
                            space.outPaint.color = Color.rgb(0xff, 0xff, 0xff)
                        }
                    }
                    if (!hasChose) {
                        scene.mapType = "nothing"
                        scene.choseSpace = null
                    }
                }


                var outSide = false
                //计算控制点的边界
                //是否已经拥有该点
                /** 打点业务 */
                if ("dot".equals(scene.type)) {
//                    for (space in scene.spaceList) {
//                        val polygonContainsPoint = Lasso.isPolygonContainsPoint(
//                            space.mPoints,
//                            android.graphics.Point(x.toInt(), -y.toInt())
//                        )
//                        outSide = true
//                        space.paint.color = Opt.spaceChoseColor
//                        space.outPaint.color = Color.rgb(0xbd, 0xe8, 0xfe)
//                    }
//                    val point = Point()
//                    point.mX = x
//                    point.mY = y
//                    var item = PointItem(point)
//                    item.isVisible = true
//                    item.zOrder = 100000f
//                    scene.pointItemList.add(item)

                    if (addPoint != null) {
                        scene.removeItem(addPoint!!)
                        scene.pointItemList.remove(addPoint)
                    }
                    ProblemDot.mX = x
                    ProblemDot.mY = y
                    addPoint = graphyHelper.addPoint(ProblemDot)

                    //添加问题点业务
                    for (item in scene.pointItemList) {
                        item.isVisible = scene.isShowSpace
                        item.zOrder = 100000f
                        scene.addItem(item)
                    }
                    if (!outSide) {
                        return
                    }
                }

                //打点业务
//                if ("dot".equals(scene.type)) {
//                    if (addPoint != null) {
//                        scene.removeItem(addPoint!!)
//                    }
//                    ProblemDot.mX = x
//                    ProblemDot.mY = y
//                    addPoint = graphyHelper.addPoint(ProblemDot)
//                    return
//                }

                //绘制管道业务
                else if ("pipe".equals(scene.type)) {
                    var pipe = PipeLine()
                    var pointf = PointF()
                    pointf.x = x
                    pointf.y = -y
                    scene.pipeLineList.add(pointf)
                    pipe.points!!.addAll(scene.pipeLineList)
                    var item = PipeLineItem(pipe, null)
                    item!!.isVisible = true
                    item!!.zOrder = 100000f
                    scene.drawingPipeItemList.add(item)
                    for (item in scene.drawingPipeItemList) {
                        item.isVisible = scene.isShowSpace
                        item.zOrder = 100000f
                        scene.addItem(item)
                    }

                    //绘制二维码
                } else if ("qrcode".equals(scene.type)) {
                    scene.point.mX = x
                    scene.point.mY = y

                    if (scene.item != null) {
                        scene.removeItem(scene.item!!)
                    }
                    scene.item =
                        QrcodeItem(this@GraphyActivity, scene.point, null, scene.defaultPointScale)
                    scene.item!!.isVisible = true
                    scene.item!!.zOrder = 100000f
                    scene.addItem(scene.item!!)

                    //绘制设备
                } else if ("equip".equals(scene.type)) {
                    scene.point.mX = x
                    scene.point.mY = y

                    if (scene.eqItem != null) {
                        scene.removeItem(scene.eqItem!!)
                    }

                    /* //吸附算法
                    var dist = 500.00
                    for (index in 0..scene.choseSpace!!.mPoints.size - 1) {


                        val point1 = scene.choseSpace!!.mPoints.get(index)
                        var point2 = PointF()
                        if (index == scene.choseSpace!!.mPoints.size - 1) {
                            point2 = scene.choseSpace!!.mPoints.get(0)
                        } else {
                            point2 = scene.choseSpace!!.mPoints.get(index + 1)
                        }


                        val l1 = Math.sqrt(Math.pow(Math.abs(point1.x - point2.x).toDouble(), 2.0) + Math.pow(Math.abs(point1.y - point2.y).toDouble(), 2.0)).toFloat()
                        val l2 = Math.sqrt(Math.pow(Math.abs(point1.x - x).toDouble(), 2.0) + Math.pow(Math.abs(point1.y + y).toDouble(), 2.0)).toFloat()
                        val l3 = Math.sqrt(Math.pow(Math.abs(point2.x - x).toDouble(), 2.0) + Math.pow(Math.abs(point2.y + y).toDouble(), 2.0)).toFloat()
                        val halfP = (l1 + l2 + l3) / 2
                        val s = Math.sqrt(halfP * (halfP - l1) * (halfP - l2) * (halfP - l3).toDouble())
                        val h = 2 * s / l1
                        if (h < dist) {
                            dist = h
                            var k1: Float
                            if (point1.x - point2.x == 0f) {
                                k1 = 0f
                            } else {
                                k1 = (point1.y - point2.y) / (point1.x - point2.x)
                            }

                            val b1 = point1.y - k1 * point1.x

                            var k2: Float
                            if (k1 == 0f) {
                                k2 = 0f
                            } else {
                                k2 = -1 / k1
                            }

                            val b2 = y - k2 * x

                            val x1 = (b2 - b1) / (k1 - k2)
                            val y1 = k2 * (x) + b2

                            if (point1.x - point2.x == 0f) {
                                scene.point.mX = point1.x
                                if (Math.abs(k1) == 0f) {
                                    scene.point.mY = y
                                } else {
                                    if (point1.y - point2.y == 0f) {
                                        scene.point.mY = -point1.y
                                    } else {
                                        scene.point.mY = y1
                                    }
                                }

                            } else {
                                if (Math.abs(k1) == 0f) {
                                    scene.point.mX = x
                                } else {
                                    scene.point.mX = x1
                                }
                                if (point1.y - point2.y == 0f) {
                                    scene.point.mY = -point1.y
                                } else {
                                    scene.point.mY = y1
                                }
                            }

                        }

                    }*/

                    scene.eqItem =
                        EquipItem(this@GraphyActivity, scene.point, null, scene.defaultPointScale)
                    scene.eqItem!!.isVisible = true
                    scene.eqItem!!.zOrder = 10000012f
                    scene.addItem(scene.eqItem!!)
                }


                //设置
//                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()
//                webview.loadUrl("http://60.205.177.43:8000/APP/#/")
//                if (isFastDoubleClick()) {
//                    if (isAddBaseMap) {
//                        scene.removeItem(mapItem)
//                        isAddBaseMap = false
//                        webview.visibility = View.GONE
//                    } else {
//                        mapItem.zOrder = 1000000f
//                        mapItem.isVisible = true
//                        scene.addItem(mapItem)
//                        isAddBaseMap = true
//                        webview.visibility = View.VISIBLE
//                    }
//                }
                if ("pipe".equals(scene.type)) {
                    return
                }
                //选中空间完毕界面逻辑
                if (scene.mapType.equals("space")) {
                    /** 4、平面图空间自动放缩定位并聚焦到某一具体空间 */
//                    val w = graphyView.width.toFloat()
//                    val h = graphyView.height.toFloat()
//                    val rect = scene.choseSpace!!.boundingRect()
//                    graphyView.setCenterPoint(PointF(rect.centerX(), rect.centerY()),
//                            min(w / rect.width(), h / rect.height()) * 0.8f)


                    if ("space".equals(from)) {
                        quesDetail.visibility = View.GONE
                        if (!scene.choseSpace!!.data.jobStatus.equals("03")) {
                            spaceStructure.visibility = View.VISIBLE
                            doneSpaceStructure.visibility = View.GONE
                            graphyVM.getProblem(scene.choseSpace)
                            /** 跳转空间详情 */
                            addSpaceDetail.setOnClickListener {
                                val intent =
                                    Intent(this@GraphyActivity, SpaceDetailActivity::class.java)
                                val bundle = Bundle()
                                bundle.putString("buildingId", buildingId)
                                bundle.putString("floorId", floorId)
                                bundle.putString("projectId", projectId)
                                bundle.putString("spaceId", scene.choseSpace!!.data.id)
                                bundle.putParcelable("space", scene.choseSpace!!.data)
                                intent.putExtra("floor", bundle)
                                startActivity(intent)
                            }
                        } else {
                            doneSpaceStructure.visibility = View.VISIBLE
                            spaceStructure.visibility = View.GONE
                            /** 重置空间状态 */
                            resetSpaceState.setOnClickListener {
                                if ("space".equals(from)) {
                                    graphyVM.setJob(scene.choseSpace, "01")
                                } else {
                                    graphyVM.setJob(scene.choseSpace, "04")
                                }
                            }
                            /** 跳转空间详情 */
                            addSpaceDetail2.setOnClickListener {
                                val intent =
                                    Intent(this@GraphyActivity, SpaceDetailActivity::class.java)
                                val bundle = Bundle()
                                bundle.putString("buildingId", buildingId)
                                bundle.putString("floorId", floorId)
                                bundle.putString("projectId", projectId)
                                bundle.putString("spaceId", scene.choseSpace!!.data.id)
                                bundle.putParcelable("space", scene.choseSpace!!.data)
                                intent.putExtra("floor", bundle)
                                startActivity(intent)
                            }
                        }
                        spaceName.text = scene.choseSpace!!.data.localName
                        spaceName3.text = scene.choseSpace!!.data.localName
                        spaceName4.text = scene.choseSpace!!.data.localName
                        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
                    doneSpaceStructure.visibility = View.GONE
                    qrcodeLl.visibility = View.GONE
                    qrcodeLocation.setText("(0,0)")
                    quesDetail.visibility = View.GONE
                    equipLl.visibility = View.GONE
                    drawLl.visibility = View.GONE
                    problemLl.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 ("normal".equals(scene.type)) {
                    realDistance = distance * scene.defaultPointScale / graphyView.scale
                    var hasChoose = false
                    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) {
                            hasChoose = true
                            showDotDetail(point)
                            break
                        }
                    }
                    if (!hasChoose) {
                        problemLl.visibility = View.GONE
                    }
                    var hasChooseEquip = false
                    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) {
                            hasChooseEquip = true
                            equipDetail.alpha = 1f
                            equipDelete.alpha = 1f
                            equipDetail.isEnabled = true
                            equipDelete.isEnabled = true
                            equipDetail.setOnClickListener {
                                val intent =
                                    Intent(this@GraphyActivity, EquipDetailActivity::class.java)
                                val bundle = Bundle()
                                val positon = Position()
                                positon.x = point.data.mX.toString()
                                positon.y = point.data.mY.toString()
                                val z = Z()
                                val position = gson.fromJson(point.data.position, Z::class.java)
                                z.offset = position.offset
                                z.region = position.region
                                positon.z = z
                                bundle.putString("spaceId", scene.choseSpace!!.data.id)
                                bundle.putSerializable("position", positon)
                                bundle.putString("buildingId", buildingId)
                                bundle.putString("floorId", floorId)
                                bundle.putString("deviceId", point.data.deviceId)
                                bundle.putString("projectId", projectId)
                                intent.putExtra("equip", bundle)
                                startActivityForResult(intent, REQUEST_CODE_EQUIP)
                            }
                            equipDelete.setOnClickListener {
                                graphyVM.insProblemEquip(scene.choseSpace!!, point.data.deviceId!!)
                            }
                            break
                        }
                    }
                    if (!hasChooseEquip) {
                        equipDetail.alpha = 0.5f
                        equipDelete.alpha = 0.5f
                        equipDetail.isEnabled = false
                        equipDelete.isEnabled = false
                    }
                    return
                }

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

    private fun checkSdCardEnabled(): Boolean {
        if (!InstaCameraManager.getInstance().isSdCardEnabled()) {
            Toast.makeText(this, "No SD card inserted or Not enough free space", Toast.LENGTH_SHORT)
                .show()
            return false
        }
        return true
    }


    /**
     * 页面全部监听事件
     */
    private fun initListener() {
        /** 普通拍照 */
        quesIma.setOnClickListener {
            InstaCameraManager.getInstance().openCamera(InstaCameraManager.CONNECT_TYPE_WIFI)
            if (checkSdCardEnabled()) {
                InstaCameraManager.getInstance().startNormalCapture(false)
            }
        }
        /** 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, "05")
        }

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

        /** 打点按钮 */
        addDot.setOnClickListener {
            scene.type = "dot"
            ProblemDot.mX = 0f
            ProblemDot.mY = 0f
            spaceStructure.visibility = View.GONE
            problemLl.visibility = View.VISIBLE
            showDotDetail(null)
            initProblemPicture(null)

        }

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

        /** 取消绑定二维码 */
        qrcodeCancel.setOnClickListener {
            qrcodeLl.visibility = View.GONE
            qrcodeLocation.setText("(0,0)")
            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 {
            if (qrcodeLocation.text.equals("(0,0)")) {
                ToastUtils.showMyToast("请扎点")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(qrcodeEdit.text.trim())) {
                ToastUtils.showMyToast("请输入高度")
                return@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"
            equipLocation.setText("")
            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 {
            if (TextUtils.isEmpty(equipLocation.text.toString())) {
                ToastUtils.showMyToast("请扎点")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(equipEdit.text.toString())) {
                ToastUtils.showMyToast("请输入高度")
                return@setOnClickListener
            }
            val intent = Intent(this, EquipDetailActivity::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)
            bundle.putString("buildingId", buildingId)
            bundle.putString("floorId", floorId)
            bundle.putString("projectId", projectId)
            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 initProblemPicture(point: PointItem?) {
        beans.clear()
        val photo = Photos()
        photo.itemType = 1
        beans.add(photo)
        if (point != null) {
            beans.addAll(point.data.photos)
        }
        pictureAdapter = PictureAdapter(this, beans, "", false, 0, 85)
        pictureAdapter.setOnPicAdd { addPic() }
        problemPicRecycler.setLayoutManager(GridLayoutManager(this, 3))
        problemPicRecycler.adapter = pictureAdapter
    }

    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(this.application, BaseViewModelInterface { name, params ->
            when (name) {
                GraphyVM.MAP_LOAD -> {
                    val floorDate = FloorData()
                    val floorOfflineData = gson.fromJson(params.toString(), FloorData::class.java)
                    floorDate.entityList.addAll(floorOfflineData.entityList)
                    scene.loadData(floorDate)
                    /** 适应屏幕大小 */
                    graphyView.fitSceneToView()
//                graphyView.defaultScale = graphyView.scale
                    /** 限定移动范围不超出屏幕 */
//                graphyView.moveRange()
                    graphyView.post {
                        Log.e("viewW", graphyView.width.toString())
//                    val mapItem = BaseMapItem(this@GraphyActivity, null)
//                    mapItem.zOrder = 1000000f
//                    mapItem.isVisible = true
//                    scene.addItem(mapItem)
                        mapItem = BaseMapItem(this@GraphyActivity, null)
                    }
                }
                /** 查询空间和任务 */
                GraphyVM.SPACE_JOB -> {
                    for (item in scene.tunableSpaceList) {
                        scene.removeItem(item)
                    }
                    scene.tunableSpaceList.clear()

//                    val list = params as (List<SpaceEntity>)
                    val list = params as (List<SpaceJobModel>)
                    for (model in list) {
                        if (model.outline != null && !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.apply {
                                outLine = model.outline.get(0)
                                objectEntity = gson.toJson(model.objectEntity)
                                this.name = model.name
//                                initSpaceState(tunableSpace, model.archState!!, model.equipState!!)
                                jobStatus = model.job
                                id = model.id
                                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 -> {
                    problemDesc.setText("")
                    Toast.makeText(this, "记录成功", Toast.LENGTH_SHORT).show()
                    graphyVM.getProblem(scene.choseSpace)
                    graphyVM.getSpaceJob(from, scene.spaceList)
                }

                /** 查询空间核查问题 */
                GraphyVM.GET_PROBLEM -> {
                    graphyHelper.removeAllPoint()
                    var list = params as ArrayList<ProblemsModel>
                    val mPoints = ArrayList<PointF>()
                    val point1 = PointF()
                    point1.set(scene.choseSpace!!.minX - 1000, scene.choseSpace!!.maxY + 1000)
                    val point2 = PointF()
                    point2.set(scene.choseSpace!!.maxX + 1000, scene.choseSpace!!.maxY + 1000)
                    val point3 = PointF()
                    point3.set(scene.choseSpace!!.minX - 1000, scene.choseSpace!!.minY - 1000)
                    val point4 = PointF()
                    point4.set(scene.choseSpace!!.maxX + 1000, scene.choseSpace!!.minY - 1000)
                    mPoints.add(point1)
                    mPoints.add(point2)
                    mPoints.add(point4)
                    mPoints.add(point3)

                    for (model in list) {
                        var position = gson.fromJson(model.position, Position::class.java)
                        val polygonContainsPoint = Lasso.isPolygonContainsPoint(
                            mPoints,
                            android.graphics.Point(
                                position.x.toFloat().toInt(),
                                position.y.toFloat().toInt()
                            )
                        )
                        if (polygonContainsPoint) {
                            val point = Point()
                            point.mX = position.x.toFloat()
                            point.mY = position.y.toFloat()
                            point.id = model.id
                            point.content = model.content
                            point.photos = model.photos
                            val addPoint = graphyHelper.addPoint(point)
                            addPoint.setOnActionMove(object : PointItem.ActionMove {
                                override fun onActionMove(event: MotionEvent) {
                                }

                            })
                        }
                    }
                }

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

                /** 绑定二维码 */
                GraphyVM.BIND_QECODE -> {
                    Toast.makeText(this, "绑定成功", Toast.LENGTH_SHORT).show()
                    scene.type = "normal"
                    qrcodeLl.visibility = View.GONE
                    qrcodeLocation.setText("(0,0)")
                    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()

                        graphyHelper.addQrcode(this, point)
                    }
                }

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

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

                /** 查询空间下的设备(所在关系) */
                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.apply {
                            setText(model.type + "(${model.children.size})")
                            setSingleLine()
                            gravity = Gravity.CENTER
                            textSize = 12f
                            height = DensityUtils.dp2px(this@GraphyActivity, 30f)
                            if (model.isCheck) {
                                background = resources.getDrawable(R.drawable.shape_filter_normal)
                                textColor = resources.getColor(R.color.grey_900)
                            } else {
                                background = resources.getDrawable(R.drawable.shape_filter_selected)
                                textColor = resources.getColor(R.color.white)
                            }
                            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(this)
                        }

                    }
                    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, projectId)
        graphyVM.getMap()
        graphyVM.getSpaceJob(from, scene.spaceList)
    }

    private fun initSpaceState(space: TunableSpace, archState: Int, equipState: Int) {
        //space 结构核查
        //survey 空间勘测
        if ("space".equals(from)) {
            if (archState == 1) {
                space.jobStatus = "01";
            } else if (archState == 2) {
                space.jobStatus = "03";
            }
        } else if ("survey".equals(from)) {
            if (archState == 1) {
                space.jobStatus = "01";
            } else if (archState == 2) {
                if (equipState == 1) {
                    space.jobStatus = "04"
                } else if (equipState == 2) {
                    space.jobStatus = "05"
                }
            }
        }

    }

    val graphyHelper: GraphyHelper = GraphyHelper(scene, this)

    /**
     * 刷新地图上管线
     */
    private fun refreshPipe(spacePipeModel: ArrayList<SpacePipeModel>) {
        graphyHelper.removeAllPipeline()
        this.spacePipeModel = spacePipeModel
        for (model in this.spacePipeModel) {
            if (!model.children.isEmpty() && !model.isCheck) {
                for (child in model.children) {
                    val pipe = PipeLine()

                    pipe.points!!.addAll(child.position)

                    graphyHelper.addPipeline(pipe)

                    for (point in child.position) {

                        val pipeNodeItem = graphyHelper.addPipeNode(point)
                        pipeNodeItem.setOnScrollListener(object : PipeNodeItem.OnScroll {
                            override fun onScroll(x: Float, y: Float) {
                                for (item in scene.pipeItemList) {
                                    scene.removeItem(item)
                                }

                                val newData = PipeLine()
                                for (node in scene.pipeNodeList) {
                                    val po = PointF()
                                    po.x = node.x
                                    po.y = node.y
                                    newData.points!!.add(po)
                                }
                                graphyHelper.addPipeline(newData)

//                                for (pointItem1 in scene.pipeItemList) {
//                                    for (pointList1 in pointItem1.data.points!!) {
//                                        for (point1 in pointList1) {
//                                            if (point1.x == pipeNodeItem.x && point1.y == pipeNodeItem.y) {
//                                                point1.x = x
//                                                point1.y = y
//                                                pipeNodeItem.x = x
//                                                pipeNodeItem.y = y

//                                                scene.removeItem(pointItem1)
//
//                                                val newData: PipeLine = deepClone(pointItem1.data) as PipeLine
//                                                for (pl in newData.points!!) {
//                                                    for (p in pl) {
//                                                        if (p.x == pipeNodeItem.x && p.y == pipeNodeItem.y) {
//                                                            p.x = x
//                                                            p.y = y
//                                                        }
//                                                    }
//                                                }
//                                                val pipeItem2 = PipeLineItem(newData, null)
//                                                pipeItem2.isVisible = true
//                                                pipeItem2.zOrder = 100000f
//                                                scene.pipeItemList.add(pipeItem2)
//                                                scene.addItem(pipeItem2)
//                                            }
//                                        }
//                                    }
//                                }
                            }
                        })
                    }


                }
            }
        }
    }

    @Throws(Exception::class)
    fun deepClone(data: PipeLine): Any? {
        // 序列化
        val bos = ByteArrayOutputStream()
        val oos = ObjectOutputStream(bos)
        oos.writeObject(data)
        // 反序列化
        val bis = ByteArrayInputStream(bos.toByteArray())
        val ois = ObjectInputStream(bis)
        return ois.readObject()
    }

    /**
     * 刷新地图上设备
     */
    private fun refreshEquip(list: List<SpaceEqModel>) {
        graphyHelper.removeAllEquip()
        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.equipState = child.type
                    point.position = child.position
                    point.deviceId = child.deviceId

                    graphyHelper.addEquip(point)
                }
            }
        }
    }

    /**
     * 重置空间界面
     */
    private fun refreshAll() {
        graphyHelper.removeAllPoint()

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

        graphyHelper.removeAllQrcode()
        graphyHelper.removeAllEquip()


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

        scene.type = "normal"
        modelCheckBox.isChecked = false
        equipLocation.setText("")
        scene.point = Point()
    }

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

        problemLl.visibility = View.VISIBLE
        if (point != null) {
            problemDesc.setText(point.data.content)
        }
        initProblemPicture(point)

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

        /** 问题-关闭 */
        problemClose.setOnClickListener {
            if (addPoint != null) {
                scene.removeItem(addPoint!!)
                scene.pointItemList.remove(addPoint)
            }
            scene.type = "normal"
            problemLl.visibility = View.GONE
            spaceStructure.visibility = View.VISIBLE
        }

        /** 问题-保存 */
        problemSave.setOnClickListener {
            if ((point == null || point.data.mX == 0f) && ProblemDot.mX == 0f) {
                ToastUtils.showMyToast("请扎点")
                return@setOnClickListener
            }
            scene.choseSpace?.let {
                graphyVM.addProblem(
                    point,
                    beans,
                    problemDesc.text.toString(),
                    it,
                    ProblemDot.mX,
                    ProblemDot.mY
                )
            }
            scene.type = "normal"
            problemLl.visibility = View.GONE
        }
    }

    /**
     * 扫码返回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)
                }
                graphyVM.floorPipe()
            }
            REQUEST_CODE_PIC -> {
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        val pathList: List<String>? =
                            data.getStringArrayListExtra(Repair_ImgSelActivity.INTENT_RESULT)
                        doPicDatas(pathList)
                    }
                }
            }
            else -> {
            }
        }
    }

    override fun onCaptureFinish(p0: Array<out String>?) {
        val time = SimpleDateFormat("HH:mm:ss").format(Date(System.currentTimeMillis()))
        quesTv.text = quesTv.text.toString() + "\n$time:拍照完成"
        downloadFilesAndPlay(p0)
    }

    override fun onCaptureStarting() {
        val time = SimpleDateFormat("HH:mm:ss").format(Date(System.currentTimeMillis()))
        quesTv.text = "$time:准备拍照"
    }

    override fun onCaptureWorking() {
        val time = SimpleDateFormat("HH:mm:ss").format(Date(System.currentTimeMillis()))
        quesTv.text = quesTv.text.toString() + "\n$time:拍照中"
    }

    override fun onCaptureStopping() {
        val time = SimpleDateFormat("HH:mm:ss").format(Date(System.currentTimeMillis()))
        quesTv.text = quesTv.text.toString() + "\n$time:拍照中断"
    }

    override fun onCameraConnectError() {
        super.onCameraConnectError()
        Toast.makeText(this, "相机连接失败", Toast.LENGTH_SHORT).show()
    }

    override fun onCameraSDCardStateChanged(enabled: Boolean) {
        super.onCameraSDCardStateChanged(enabled)
        if (enabled) {
            Toast.makeText(this, "SD卡可用", Toast.LENGTH_SHORT).show()
            // Capture Status Callback
            InstaCameraManager.getInstance().setCaptureStatusListener(this)
        } else {
            Toast.makeText(this, "SD卡异常", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCameraStatusChanged(enabled: Boolean) {
        super.onCameraStatusChanged(enabled)
        if (enabled) {
            Toast.makeText(this, "相机已连接", Toast.LENGTH_SHORT).show()
        } else {
            NetworkManager.getInstance().clearBindProcess()
            Toast.makeText(this, "相机连接断开", Toast.LENGTH_SHORT).show()
        }
    }

    private fun downloadFilesAndPlay(urls: Array<out String>?) {
        if (urls == null || urls.size == 0) {
            return
        }
        val localFolder =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                .toString() + "/SDK_DEMO_CAPTURE"
        val fileNames = arrayOfNulls<String>(urls.size)
        val localPaths = arrayOfNulls<String>(urls.size)
        var needDownload = false
        val dir = File(localFolder)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        for (i in localPaths.indices) {
            fileNames[i] = urls[i].substring(urls[i].lastIndexOf("/") + 1)
            localPaths[i] = localFolder + "/" + fileNames[i]
            if (!File(localPaths[i]).exists()) {
                needDownload = true
            }
        }
        if (!needDownload) {
            val time = SimpleDateFormat("HH:mm:ss").format(Date(System.currentTimeMillis()))
            quesTv.text = quesTv.text.toString() + "\n$time:文件已存在"
//            PlayAndExportActivity.launchActivity(this@CaptureActivity, localPaths)
            return
        }
        val dialog: MaterialDialog = MaterialDialog.Builder(this)
            .title(R.string.osc_dialog_title_downloading)
            .content(getString(R.string.osc_dialog_msg_downloading, urls.size, 0, 0))
            .cancelable(false)
            .canceledOnTouchOutside(false)
            .show()
        val successfulCount = AtomicInteger(0)
        val errorCount = AtomicInteger(0)
        for (i in localPaths.indices) {
            val url = urls[i]
            OkGo.get<File>(url).execute(object : FileCallback(localFolder, fileNames[i]) {
                override fun onError(response: Response<File?>?) {
                    super.onError(response)
                    errorCount.incrementAndGet()
                    checkDownloadCount()
                }

                override fun onSuccess(response: Response<File?>?) {
                    successfulCount.incrementAndGet()
                    checkDownloadCount()
                }

                private fun checkDownloadCount() {
                    dialog.setContent(
                        getString(
                            R.string.osc_dialog_msg_downloading,
                            urls.size,
                            successfulCount.toInt(),
                            errorCount.toInt()
                        )
                    )
                    if (successfulCount.toInt() + errorCount.toInt() >= urls.size) {
//                                PlayAndExportActivity.launchActivity(this@CaptureActivity, localPaths)
                        val time =
                            SimpleDateFormat("HH:mm:ss").format(Date(System.currentTimeMillis()))
                        quesTv.text = quesTv.text.toString() + "\n$time:下载完成"
                        dialog.dismiss()
                    }
                }
            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        InstaCameraManager.getInstance().unregisterCameraChangedCallback(this)
    }


} // Class GraphyActivity
