/*
 * ********************************************************************************************************************
 *
 *               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.DialogInterface
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.app.AlertDialog
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.hutool.core.collection.CollectionUtil
import cn.sagacloud.android.cadengine.FloorScene
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.model.db.entity.dict.MajorEntity
import com.framework.mvvm.model.db.entity.task.InfosforEq
import com.framework.mvvm.model.db.entity.task.ObjectEntity
import com.framework.mvvm.mv.AdmViewModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
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.adapter.PictureAdapter
import com.sybotan.android.demo.adapter.PipeAdapter
import com.sybotan.android.demo.bean.ReLoactionEventBus
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.view.SelectListSinglePopupWindow
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.yuyh.library.imgsel.utils.LogUtils
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
import kotlin.collections.HashMap


@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 equipClassList = ArrayList<String>()

    //选择图片
    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
    private var major: String = ""

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

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

    /** 缩放后的同比例距离 */
    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
    lateinit var spaceEqList: ArrayList<SpaceEqModel>

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

    } // test()

    private lateinit var graphyView: SGraphyView
    private lateinit var quesDetail: RelativeLayout
    private lateinit var spaceName2: TextView
    private lateinit var equipLl: LinearLayout
    private lateinit var drawLl: LinearLayout
    private lateinit var equipLocation: TextView
    private lateinit var sceneCheckBox: CheckBox
    private lateinit var sceneSubmit: TextView
    private lateinit var pipeCancel: TextView
    private lateinit var pipeLl: LinearLayout
    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 equipCancel: TextView
    private lateinit var equipNext: TextView
    private lateinit var equipEdit: EditText
    private lateinit var equipRg: RadioGroup
    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 webview: WebView
    private lateinit var quesIma: ImageView
    private lateinit var equipDetail: TextView
    private lateinit var equipContainer: TextView
    private lateinit var equipDelete: TextView
    private lateinit var sift: TextView
    private lateinit var copyDetail: TextView
    private lateinit var checkAll: CheckBox
    private lateinit var onlySpace: CheckBox
    private lateinit var root: LinearLayout

    /**
     * 创建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)
        spaceName2 = findViewById(R.id.spaceName2)
        equipLl = findViewById(R.id.equipLl)
        drawLl = findViewById(R.id.drawLl)
        equipLocation = findViewById(R.id.equipLocation)
        sceneCheckBox = findViewById(R.id.sceneCheckBox)
        sceneSubmit = findViewById(R.id.sceneSubmit)
        pipeCancel = findViewById(R.id.pipeCancel)
        pipeLl = findViewById(R.id.pipeLl)
        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)
        equipCancel = findViewById(R.id.equipCancel)
        equipNext = findViewById(R.id.equipNext)
        equipEdit = findViewById(R.id.equipEdit)
        equipRg = findViewById(R.id.equipRg)
        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)
        webview = findViewById(R.id.webview)
        quesIma = findViewById(R.id.quesIma)
        equipDetail = findViewById(R.id.equipDetail)
        equipContainer = findViewById(R.id.equipContainer)
        equipDelete = findViewById(R.id.equipDelete)
        checkAll = findViewById(R.id.checkAll)
        onlySpace = findViewById(R.id.onlySpace)
        sift = findViewById(R.id.sift)
        root = findViewById(R.id.root)
        copyDetail = findViewById(R.id.copyDetail)

    }

    /**
     * 初始化数据
     */
    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("图片上传失败")
                    pictureAdapter.notifyDataSetChanged()
                }
                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)) {
                    realDistance = distance * scene.defaultPointScale / graphyView.scale
                    var hasChoose = false
                    for (point in scene.pointItemList) {
                        if (!CommonUtils.IsNull(point.data.points.size) && point.data.points.size > 1) {
                            var dist = 500.00
                            for (index in 0..point.data.points.size - 2) {
                                val point1 = point.data.points.get(index)
                                var point2 = point.data.points.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
                                        }
                                    }
                                    hasChoose = true
                                    for (p in point.data.points) {
                                        var pipe = PipeLine()
                                        var pointf = PointF()
                                        pointf.x = p.x
                                        pointf.y = p.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)

                                    }
                                    showDotDetail(point)
                                    break

                                }

                            }
                        } else {
                            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) {
                    } else {
                        return
                    }
                    var hasChooseEquip = false
                    var equipList = ArrayList<EquipItem>()
                    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) {
                            equipList.add(point)
                            hasChooseEquip = true
                        }
                        point.data.equipState = point.data.equipType
                    }
                    if (!CommonUtils.IsNull(equipList)) {
                        if (equipList.size == 1) {
                            val point = equipList[0]
                            initEquipDetail(point)
                        } else {
                            val pop = SelectListSinglePopupWindow(this@GraphyActivity)
                            pop.setGenList(equipList, Constant.TYPE4)
                            pop.setBtn(false, "")
                            pop.showAtLocation(root, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
                            pop.setOnItemClickListener { initEquipDetail(equipList[it]) }
                        }
                    }
                    if (!hasChooseEquip) {
                        copyDetail.alpha = 0.5f
                        equipDetail.alpha = 0.5f
                        equipContainer.alpha = 0.5f
                        equipDelete.alpha = 0.5f
                        copyDetail.isEnabled = false
                        equipDetail.isEnabled = false
                        equipContainer.isEnabled = false
                        equipDelete.isEnabled = false
                    } else {
                        return
                    }
                }

                //如果只是查看模式，可以选中空间，进行空间内业务操作
                if ("normal".equals(scene.type)) {
                    var hasChose = false
                    for (space in scene.tunableSpaceList) {
                        val polygonContainsPoint = Lasso.isPolygonContainsPoint(
                            space.data.outLine,
                            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
                    }
                } 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 ("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 (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")) {
                    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()
                }
            }
        })
    }

    private fun initEquipDetail(point: EquipItem) {
        copyDetail.alpha = 1f
        equipDetail.alpha = 1f
        equipDelete.alpha = 1f
        copyDetail.isEnabled = true
        equipDetail.isEnabled = true
        equipDelete.isEnabled = true
        graphyVM.getContainer(point.data.deviceId!!)
        point.data.equipState = 4
        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
            for (space in scene.tunableSpaceList) {
                val isContain = Lasso.isPolygonContainsPoint(space.data.outLine, android.graphics.Point(positon.x.toFloat().toInt(), -positon.y.toFloat().toInt()))
                if (isContain) {
                    bundle.putString("spaceId", space.data.id)
                    break
                }
            }
            bundle.putSerializable("position", positon)
            bundle.putString("buildingId", buildingId)
            bundle.putString("floorId", floorId)
            bundle.putString("deviceId", point.data.deviceId)
            bundle.putString("projectId", projectId)
            bundle.putString("floorMap", floorMap)
            bundle.putFloat("scale", scene.view!!.scale)
            bundle.putParcelable(
                "centerPoint",
                graphyView.mapToScene(
                    PointF(
                        graphyView.width / 2f,
                        graphyView.height / 2f
                    )
                )
            )
            intent.putExtra("equip", bundle)
            startActivityForResult(intent, REQUEST_CODE_EQUIP)
        }
        equipContainer.setOnClickListener {
            val intent =
                Intent(this@GraphyActivity, EquipContainerActivity::class.java)
            val bundle = Bundle()
            bundle.putString("buildingId", buildingId)
            bundle.putString("floorId", floorId)
            bundle.putString("projectId", projectId)
            bundle.putString("deviceId", point.data.deviceId)
            bundle.putString("floorMap", floorMap)
            bundle.putFloat("scale", scene.view!!.scale)
            bundle.putParcelable(
                "centerPoint",
                graphyView.mapToScene(
                    PointF(
                        graphyView.width / 2f,
                        graphyView.height / 2f
                    )
                )
            )
            val position =
                gson.fromJson(point.data.position, Position::class.java)
            bundle.putSerializable("position", position)
            bundle.putString("spaceId", scene.choseSpace!!.data.id)
            intent.putExtra("params", bundle)
            startActivity(intent)
        }
        equipDelete.setOnClickListener {
            val builder: AlertDialog.Builder =
                AlertDialog.Builder(this@GraphyActivity)
                    .setTitle("确认标记/删除设备吗")
                    .setPositiveButton(
                        "确定"
                    ) { _, _ ->
                        graphyVM.insProblemEquip(
                            scene.choseSpace!!,
                            point.data.deviceId!!
                        )
                    }.setNegativeButton(
                        "取消"
                    ) { dialogInterface, _ ->
                        dialogInterface.dismiss()
                    }
            builder.create().show()


        }
        copyDetail.setOnClickListener {
            graphyVM.copyDetail(point.data.deviceId)
        }
    }

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

        /** 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")
        }

        /** 取消绘制管道 */
        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()
        }

        /** 添加管线下一步 */
        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
            equipEdit.setText("")
            equipRg.clearCheck()
            equipNext.setText("下一步")
            /** 取消添加设备 */
            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 (floor.isChecked) {
                    equipEdit.setText("0")
                }
                if (!air.isChecked && !roof.isChecked && !floor.isChecked && !wall.isChecked) {
                    ToastUtils.showMyToast("请选择设备位置")
                    return@setOnClickListener
                }
                if ((air.isChecked || wall.isChecked) && 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()
                if (roof.isChecked) {
                    z.offset = "0"
                }
                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
                for (space in scene.tunableSpaceList) {
                    val isContain = Lasso.isPolygonContainsPoint(space.data.outLine, android.graphics.Point(positon.x.toFloat().toInt(), -positon.y.toFloat().toInt()))
                    if (isContain) {
                        bundle.putString("spaceId", space.data.id)
                        break
                    }
                }
                bundle.putSerializable("position", positon)
                bundle.putString("buildingId", buildingId)
                bundle.putString("floorId", floorId)
                bundle.putString("projectId", projectId)
                bundle.putString("floorMap", floorMap)
                bundle.putFloat("scale", scene.view!!.scale)
                bundle.putParcelable(
                    "centerPoint",
                    graphyView.mapToScene(
                        PointF(
                            graphyView.width / 2f,
                            graphyView.height / 2f
                        )
                    )
                )
                intent.putExtra("equip", bundle)
                startActivityForResult(intent, REQUEST_CODE_EQUIP)
            }

        }

        /** 添加管线 */
        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()
        }
        roof.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                equipEdit.setText("")
                equipEdit.isEnabled = false
                equipEdit.alpha = 0.5f
            }
        }
        wall.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                equipEdit.setText("")
                equipEdit.isEnabled = true
                equipEdit.alpha = 1f
            }
        }
        air.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                equipEdit.setText("")
                equipEdit.isEnabled = true
                equipEdit.alpha = 1f
            }
        }
        floor.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                equipEdit.setText("0")
                equipEdit.isEnabled = true
                equipEdit.alpha = 1f
            }
        }
    }

    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
    }


    /**
     * 初始化viewModel
     */
    private fun initViewModel() {
        graphyVM = GraphyVM(this.application, BaseViewModelInterface { name, params ->
            when (name) {
                GraphyVM.MAP_LOAD -> {
                    val floorOfflineData = gson.fromJson(params.toString(), FloorData::class.java)
                    scene.loadData(floorOfflineData)
                    /** 适应屏幕大小 */
                    graphyView.fitSceneToView()
                    /** 限定移动范围不超出屏幕 */
//                    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[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
                                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)
                        }
                    }
                    graphyVM.floorPipe()
                }

                /** 设置空间的任务状态(新建和修改) */
                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 -> {
                    spaceEqList = params as ArrayList<SpaceEqModel>
                    for (item in scene.equipList) {
                        scene.removeItem(item)
                    }
                    scene.equipList.clear()
                    initEquipChoose(spaceEqList)
                    refreshEquip(spaceEqList)
                    checkAll.setOnCheckedChangeListener { buttonView, isChecked ->
                        if (isChecked) {
                            for (model in spaceEqList) {
                                model.isCheck = false
                                equipClassList.add(model.type!!)
                            }
                        } else {
                            equipClassList.clear()
                            for (model in spaceEqList) {
                                model.isCheck = true
                            }
                        }
                        initEquipChoose(spaceEqList)
                        refreshEquip(spaceEqList)
                    }
                    onlySpace.setOnCheckedChangeListener { buttonView, isChecked ->
                        if (isChecked) {
                            initEquipChoose(spaceEqList)
                            refreshEquip(spaceEqList)
                        } else {
                            graphyVM.getSpaceEq(scene.choseSpace)
                        }
                    }
                    sift.setOnClickListener {
                        graphyVM.getMajor()
                    }
                }

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

                /** 专业列表 */
                GraphyVM.MAJORS_LIST -> {
                    val majors = params as ArrayList<MajorEntity>
                    val popupWindow = SelectListSinglePopupWindow(this)
                    popupWindow.setGenList(majors, Constant.TYPE3)
                    popupWindow.setBtn(true, "全部")
                    popupWindow.showAtLocation(root, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
                    popupWindow.setOnItemClickListener {
                        if (it == -1) {
                            this.major = ""
                            sift.setText("专业：全部")
                        } else {
                            this.major = majors.get(it).code
                            sift.setText("专业：${majors.get(it).label}")
                        }
                        initEquipChoose(spaceEqList)
                        refreshEquip(spaceEqList)
                    }
                }

                /** 添加管线 */
                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)
                }
                /** 添加设备成功 */
                GraphyVM.UPDATE_LOCATION -> {
                    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()
                }

                GraphyVM.CONTAINER_EQUIP -> {
                    val hashMap = params as HashMap<String, Any>
                    val objs = hashMap.get("objs") as ArrayList<ObjectEntity>
                    val configs = hashMap.get("configs") as ArrayList<ObjectEntity>
                    if (!CommonUtils.IsNull(configs)) {
                        equipContainer.setText("无模型设备（${objs.size})")
                        equipContainer.isEnabled = true
                        equipContainer.alpha = 1f
                    } else {
                        equipContainer.setText("无模型设备")
                        equipContainer.isEnabled = false
                        equipContainer.alpha = 0.5f
                    }
                }
            }
        }, this, buildingId, floorId, projectId)
        graphyVM.getMap()
        graphyVM.getSpaceJob(from, scene.spaceList)
    }

    private fun initEquipChoose(list: ArrayList<SpaceEqModel>) {
        //流式布局
        equipWwv.removeAllViews()
        var equipList = ArrayList<SpaceEqModel>()
        CollectionUtil.addAll(equipList as Collection<Any>?, MutableList(list.size) {})
        Collections.copy(equipList, list)
//        equipList = deepClone(list) as ArrayList<SpaceEqModel>
        if (onlySpace.isChecked) {
            val iterator = equipList.iterator()
            while (iterator.hasNext()) {
                val item = iterator.next()
                val childIterator = item.children.iterator()
                while (childIterator.hasNext()) {
                    val child = childIterator.next()
                    if (child.position != null) {
                        var position = gson.fromJson(child.position, Position::class.java)
                        val isContain = Lasso.isPolygonContainsPoint(scene.choseSpace!!.data.outLine, android.graphics.Point(position.x.toFloat().toInt(), position.y.toFloat().toInt()))
                        if (!isContain) {
                            childIterator.remove()
                        }
                    }
                }
                if (CommonUtils.IsNull(item.children)) {
                    iterator.remove()
                }
            }
        }
        if (!TextUtils.isEmpty(major)) {
            val iterator = equipList.iterator()
            while (iterator.hasNext()) {
                val item = iterator.next()
                if (!item.type!!.startsWith(major)) {
                    iterator.remove()
                }
            }
        }
        equipList.sortBy { it.type }
        for (model in equipList) {
            val textview = TextView(this)
            textview.apply {
                setText(model.typeName + "-" + model.type + "(${model.children.size})")
                setSingleLine()
                gravity = Gravity.CENTER
                textSize = 12f
                height = DensityUtils.dp2px(this@GraphyActivity, 30f)
                if (equipClassList.contains(model.type)) {
                    model.isCheck = false
                }
                if (!model.isCheck || checkAll.isChecked) {
                    background = resources.getDrawable(R.drawable.shape_filter_selected)
                    textColor = resources.getColor(R.color.white)
                } else {
                    background = resources.getDrawable(R.drawable.shape_filter_normal)
                    textColor = resources.getColor(R.color.grey_900)
                }
                setOnClickListener {
                    model.isCheck = !model.isCheck
                    if (!model.isCheck || checkAll.isChecked) {
                        equipClassList.add(model.type!!)
                        textview.background =
                            resources.getDrawable(R.drawable.shape_filter_selected)
                        textview.textColor = resources.getColor(R.color.white)
                    } else {
                        equipClassList.remove(model.type!!)
                        textview.background =
                            resources.getDrawable(R.drawable.shape_filter_normal)
                        textview.textColor = resources.getColor(R.color.grey_900)
                    }
                    refreshEquip(equipList)
                }
                equipWwv.addView(this)
            }

        }
    }

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


                }
            }
        }
    }

    /**
     * 刷新地图上设备
     */
    private fun refreshEquip(list: List<SpaceEqModel>) {
        graphyHelper.removeAllEquip()
        for (model in list) {
            if (!model.children.isEmpty() && (!model.isCheck || checkAll.isChecked)) {
                for (child in model.children) {
                    if (child.position != null) {
                        val position = gson.fromJson(child.position, Position::class.java)
                        val point = Point()
                        point.mX = position.x.toFloat()
                        point.mY = -position.y.toFloat()
                        val isContains = Lasso.isPolygonContainsPoint(scene.choseSpace!!.data.outLine, android.graphics.Point(point.mX.toInt(), -point.mY.toInt()))
                        point.remark = child.remark
                        point.type = model.type
                        point.equipState = child.type
                        point.name = child.name
                        point.equipType = child.type
                        point.position = child.position
                        point.deviceId = child.deviceId
                        point.digitalDeliveryID = child.digitalDeliveryID
                        if (((onlySpace.isChecked && isContains) || !onlySpace.isChecked) && (TextUtils.isEmpty(major) || point.type!!.startsWith(major))) {
                            graphyHelper.addEquip(point)
                        }
                    }
                }
            }
        }
    }

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

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

        graphyHelper.removeAllQrcode()
        graphyHelper.removeAllEquip()


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

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

    /**
     * 显示点位信息框
     */
    private fun showDotDetail(point: PointItem?) {
//        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()
//        }

//        if (point != null) {
//            problemDesc.setText(point.data.content)
//        } else {
//            problemDesc.setText("")
//        }
//        initProblemPicture(point)
    }

    /**
     * 扫码返回uuid
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            /** 添加设备成功 */
            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)
        EventBus.getDefault().unregister(this)
    }

    @Subscribe
    fun onEvent(bus: ReLoactionEventBus) {
        for (eq in scene.equipList) {
            if (eq.data.deviceId!!.equals(bus.equip.id)) {
                scene.removeItem(eq)
                break
            }
        }
        val info = gson.fromJson(bus.equip.infos, InfosforEq::class.java)
        scene.type = "equip"
        equipLocation.setText("(${info.location!!.x()},${-info.location.y()})")
        drawLl.visibility = View.GONE
        equipLl.visibility = View.VISIBLE
        equipRg.clearCheck()
        if (info.zRegion == "roof") {
            roof.isChecked = true
        } else if (info.zRegion == "floor") {
            floor.isChecked = true
        } else if (info.zRegion == "wall") {
            wall.isChecked = true
        } else if (info.zRegion == "air") {
            air.isChecked = true
        }
        equipEdit.setText(info.location.z().toString())

        scene.point.mX = info.location.x()
        scene.point.mY = -info.location.y()
        scene.point.equipState = 4
        scene.eqItem = EquipItem(this@GraphyActivity, scene.point)
        scene.eqItem!!.isVisible = true
        scene.eqItem!!.zOrder = 10000012f
        scene.addItem(scene.eqItem!!)
        equipNext.setText("保存确定")
        /** 添加设备下一步 */
        equipNext.setOnClickListener {
            if (TextUtils.isEmpty(equipLocation.text.toString())) {
                ToastUtils.showMyToast("请扎点")
                return@setOnClickListener
            }
            if (floor.isChecked) {
                equipEdit.setText("0")
            }
            if (!air.isChecked && !roof.isChecked && !floor.isChecked && !wall.isChecked) {
                ToastUtils.showMyToast("请选择设备位置")
                return@setOnClickListener
            }
            if ((air.isChecked || wall.isChecked) && TextUtils.isEmpty(equipEdit.text.toString())) {
                ToastUtils.showMyToast("请输入高度")
                return@setOnClickListener
            }
            val position = Position()
            position.x = scene.point.mX.toString()
            position.y = scene.point.mY.toString()
            val z = Z()
            z.offset = equipEdit.text.toString()
            if (roof.isChecked) {
                z.offset = "0"
            }
            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"
                }
            }
            position.z = z
            copyDetail.alpha = 0.5f
            equipDetail.alpha = 0.5f
            equipContainer.alpha = 0.5f
            equipDelete.alpha = 0.5f
            copyDetail.isEnabled = false
            equipDetail.isEnabled = false
            equipContainer.isEnabled = false
            equipDelete.isEnabled = false
            graphyVM.insEquip(bus.equip, position)
        }
        /** 取消添加设备 */
        equipCancel.setOnClickListener {
            drawLl.visibility = View.VISIBLE
            equipLl.visibility = View.GONE
            scene.eqItem?.let { it1 -> scene.removeItem(it1) }
            scene.type = "normal"
            copyDetail.alpha = 0.5f
            equipDetail.alpha = 0.5f
            equipContainer.alpha = 0.5f
            equipDelete.alpha = 0.5f
            copyDetail.isEnabled = false
            equipDetail.isEnabled = false
            equipContainer.isEnabled = false
            equipDelete.isEnabled = false
            graphyVM.getSpaceEq(scene.choseSpace)
        }

    }


} // Class GraphyActivity
