/*
 * ********************************************************************************************************************
 *
 *               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.text.TextUtils
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import android.widget.Toast
import android.widget.*
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
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.bumptech.glide.Glide
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.sybotan.android.demo.R
import com.sybotan.android.demo.adapter.PictureAdapter
import com.sybotan.android.demo.bean.result.*
import com.sybotan.android.demo.graphy.GraphyHelper
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.SpaceMapVM
import com.sybotan.android.graphy.SGraphyView
import com.yuyh.library.imgsel.ImageLoader
import com.yuyh.library.imgsel.ImgSelConfig
import com.zbar.lib.CaptureActivity
import io.reactivex.ObservableEmitter
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 java.io.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt


class SpaceMapActivity : BaseActivity(), DIAware {
    companion object {
        /** 扫描二维码 */
        private const val REQUEST_CODE_SCAN = 0x0000

        /** 选择图片 */
        private const val REQUEST_CODE_PIC = 0X102
    }

    override val di: DI by closestDI()

    /** 自定义图片加载器 */
    private val loader =
        ImageLoader { context: Context?, path: String?, imageView: ImageView? ->
            Glide.with(
                context
            ).load(path).into(imageView)
        }

    /** viewModel */
    lateinit var spaceMapVM: SpaceMapVM

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

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

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

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

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


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

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

    /**
     * 问题图片列表
     */
    private val beans: ArrayList<Photos> = ArrayList()

    private lateinit var pictureAdapter: PictureAdapter
    private lateinit var graphyView: SGraphyView
    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 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 qrcode: TextView
    private lateinit var qrcodeCancel: TextView
    private lateinit var qrcodeNext: TextView
    private lateinit var problemPicRecycler: MaxHeightRecyclerView
    private lateinit var pipeWwv: WordWrapView
    private lateinit var addSpaceDetail: TextView
    private lateinit var addSpaceDetail2: TextView
    private lateinit var resetSpaceState: TextView
    private lateinit var qrcodeEdit: EditText
    private lateinit var problemLl: LinearLayoutCompat
    private lateinit var problemRg: RadioGroup
    private lateinit var pointRb: RadioButton
    private lateinit var lineRb: RadioButton
    private lateinit var problemClose: TextView
    private lateinit var problemDone: TextView
    private lateinit var problemSave: TextView
    private lateinit var problemDesc: AppCompatEditText

    /**
     * 创建Activity时的回调函数
     *
     * @param   savedInstanceState
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_space_map)
        initView()

        /** 初始化数据 */
        initData()
        graphyView.scene = scene

        /** 点击监听 */
        initListener()
        /** 图形点击-poc业务 */
        initSingleTopUp()
        /** 网络请求回调处理 */
        initViewModel()

        return
    } // Function onCreate()


    private fun initView() {
        graphyView = findViewById(R.id.graphyView)
        spaceStructure = findViewById(R.id.spaceStructure)
        doneSpaceStructure = findViewById(R.id.doneSpaceStructure)
        spaceName = findViewById(R.id.spaceName)
        spaceName3 = findViewById(R.id.spaceName3)
        spaceName4 = findViewById(R.id.spaceName4)
        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)
        qrcode = findViewById(R.id.qrcode)
        qrcodeCancel = findViewById(R.id.qrcodeCancel)
        qrcodeNext = findViewById(R.id.qrcodeNext)
        problemPicRecycler = findViewById(R.id.problemPicRecycler)

        pipeWwv = findViewById(R.id.pipeWwv)
        qrcodeEdit = findViewById(R.id.qrcodeEdit)
        addSpaceDetail = findViewById(R.id.addSpaceDetail)
        addSpaceDetail2 = findViewById(R.id.addSpaceDetail2)
        resetSpaceState = findViewById(R.id.resetSpaceState)
        problemLl = findViewById(R.id.problemLl)
        problemRg = findViewById(R.id.problemRg)
        pointRb = findViewById(R.id.pointRb)
        lineRb = findViewById(R.id.lineRb)
        problemClose = findViewById(R.id.problemClose)
        problemDone = findViewById(R.id.problemDone)
        problemSave = findViewById(R.id.problemSave)
        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", "")!!
        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(ContextCompat.getColor(this, R.color.blue_2E3679)) // 返回图标ResId
            .backResId(R.mipmap.back_gray).title("选择图片").titleColor(Color.WHITE).titleBgColor(
                ContextCompat.getColor(this, R.color.blue_2E3679)
            ) //                .allImagesText("All Images")
            .needCrop(false).cropSize(1, 1, 200, 200) // 第一个是否显示相机
            .needCamera(true) // 最大选择图片数量
            .build()
        //选择图片activity
        Repair_ImgSelActivity.startActivity(this, config, REQUEST_CODE_PIC)
    }

    @SuppressLint("NotifyDataSetChanged")
    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, offlineImagePath, 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 -> {
                }
            }
        }
    }


    /**
     * 图形点击事件
     * */
    private fun initSingleTopUp() {
        scene.setOnSingleTopUp(object : FloorScene.OnSingleTopUp {
            @SuppressLint("SetJavaScriptEnabled")
            override fun onSingUp(x: Float, y: Float) {
                //查看模式下，判断问题点选中逻辑
                if ("normal" == scene.type) {
                    realDistance = distance * scene.defaultPointScale / graphyView.scale
                    removeDrawingLine()
                    scene.drawingPipeItemList.clear()
                    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[index]
                                val point2 = point.data.points[index + 1]
                                val point3 = PointF(x, y)
                                //point3到（point1与point2的连线）的最短距离
                                val h = Lasso.beeline(point1, point2, point3)
                                if (h < dist) {
                                    if (oprateItem != null) {
                                        scene.removeItem(oprateItem!!)
                                        oprateItem = null
                                    }
                                    hasChoose = true
                                    problemRg.visibility = View.GONE
                                    lineRb.setOnCheckedChangeListener { _, _ ->

                                    }
                                    lineRb.isChecked = true
                                    for (p in point.data.points) {
                                        val pipe = PipeLine()
                                        val pointf = PointF()
                                        pointf.x = p.x
                                        pointf.y = p.y
                                        scene.pipeLineList.add(pointf)
                                        pipe.points.addAll(scene.pipeLineList)
                                        val item = PipeLineItem(pipe, null)
                                        item.isVisible = true
                                        item.zOrder = 100000f
                                        scene.drawingPipeItemList.add(item)
                                        val pipeNodeItem = graphyHelper.addPipeNode(pointf)
                                        pipeNodeItem.setOnScrollListener(object :
                                            PipeNodeItem.OnScroll {
                                            override fun onScroll(x: Float, y: Float) {
                                                this@SpaceMapActivity.oprateItem = point
                                                scene.removeItem(point)
                                                for (item in scene.drawingPipeItemList) {
                                                    scene.removeItem(item)
                                                }
                                                for (item in scene.pipeItemList) {
                                                    scene.removeItem(item)
                                                }
                                                scene.drawingPipeItemList.clear()
                                                val newData = PipeLine()
                                                for (node in scene.pipeNodeList) {
                                                    val po = PointF()
                                                    po.x = node.x
                                                    po.y = node.y
                                                    newData.points!!.add(po)
                                                }
                                                val item = PipeLineItem(newData, null)
                                                scene.drawingPipeItemList.add(item)
                                                graphyHelper.addPipeline(newData)
                                            }
                                        })
                                    }
                                    showDotDetail(point)
                                    return

                                }

                            }
                        } else {
                            val sqrt = sqrt(
                                abs(x - point.data.mX).toDouble().pow(2.0) + abs(y - point.data.mY)
                                    .toDouble().pow(2.0)
                            ).toInt()
                            if (sqrt < realDistance) {
                                hasChoose = true
                                problemRg.visibility = View.GONE
                                pointRb.setOnCheckedChangeListener { _, _ ->

                                }
                                pointRb.isChecked = true
                                spaceMapVM.getProblem(scene.choseSpace)
                                showDotDetail(point)
                                break
                            }
                        }
                    }
                    if (!hasChoose) {
                        problemLl.visibility = View.GONE
                    } else {
                        return
                    }
                    var hasChooseEquip = false
                    for (point in scene.equipList) {
                        val sqrt = sqrt(
                            abs(x - point.data.mX).toDouble().pow(2.0) + abs(y - point.data.mY)
                                .toDouble().pow(2.0)
                        ).toInt()
                        if (sqrt < realDistance) {
                            hasChooseEquip = true
                            point.data.equipState = 4

                        } else {
                            point.data.equipState = point.data.equipType
                        }
                    }
                    if (hasChooseEquip) return
                }

                //如果只是查看模式，可以选中空间，进行空间内业务操作
                if ("normal" == 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
                    }
                }


                val outSide = false
                //计算控制点的边界
                //是否已经拥有该点
                /** 打点业务 */
                if ("dot" == scene.type) {
                    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" == scene.type) {
                    val pipe = PipeLine()
                    val pointf = PointF()
                    pointf.x = x
                    pointf.y = -y
                    scene.pipeLineList.add(pointf)
                    pipe.points.addAll(scene.pipeLineList)
                    val item = PipeLineItem(pipe, null)
                    item.isVisible = true
                    item.zOrder = 100000f
                    scene.drawingPipeItemList.add(item)
                    for (itemPipe in scene.drawingPipeItemList) {
                        itemPipe.isVisible = scene.isShowSpace
                        itemPipe.zOrder = 100000f
                        scene.addItem(itemPipe)
                    }
                    val pipeNodeItem = graphyHelper.addPipeNode(pointf)
                    pipeNodeItem.setOnScrollListener(object : PipeNodeItem.OnScroll {
                        override fun onScroll(x: Float, y: Float) {
                            for (item in scene.drawingPipeItemList) {
                                scene.removeItem(item)
                            }
                            for (item in scene.pipeItemList) {
                                scene.removeItem(item)
                            }
                            scene.drawingPipeItemList.clear()
                            val newData = PipeLine()
                            for (node in scene.pipeNodeList) {
                                val po = PointF()
                                po.x = node.x
                                po.y = node.y
                                newData.points!!.add(po)
                            }
                            val item = PipeLineItem(newData, null)
                            scene.drawingPipeItemList.add(item)
                            graphyHelper.addPipeline(newData)
                        }
                    })

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

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

                    //绘制设备
                }

                //选中空间完毕界面逻辑
                if (scene.mapType.equals("space")) {
                    if (scene.choseSpace!!.data.jobStatus != "03") {
                        spaceStructure.visibility = View.VISIBLE
                        doneSpaceStructure.visibility = View.GONE
                        spaceMapVM.getProblem(scene.choseSpace)
                        /** 跳转空间详情 */
                        addSpaceDetail.setOnClickListener {
                            val intent =
                                Intent(this@SpaceMapActivity, 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 {
                            spaceMapVM.setJob(scene.choseSpace, "01")
                        }
                        /** 跳转空间详情 */
                        addSpaceDetail2.setOnClickListener {
                            val intent =
                                Intent(this@SpaceMapActivity, 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
                    spaceMapVM.getQrcode(scene.choseSpace)
                    //未选中空间
                } else if (scene.mapType.equals("nothing")) {
                    spaceStructure.visibility = View.GONE
                    doneSpaceStructure.visibility = View.GONE
                    qrcodeLl.visibility = View.GONE
                    qrcodeLocation.text = "(0,0)"
                    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 ("qrcode".equals(scene.type)) {
                    qrcodeLl.visibility = View.VISIBLE
                    qrcodeLocation.text = "(${scene.point.mX},${scene.point.mY})"
                    spaceStructure.visibility = View.GONE
                    doneSpaceStructure.visibility = View.GONE
                    return
                }
            }
        })
    }

    /**
     * 页面全部监听事件
     */
    private fun initListener() {

        /** nfc点击监听 */
        nfc.setOnClickListener { Toast.makeText(this, "正在开发中，敬请期待", Toast.LENGTH_SHORT).show() }

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

        /** 设置空间的任务状态完成 */
        modelSubmit.setOnClickListener {
            if (scene.choseSpace!!.data.jobStatus == "02") {
                ToastUtils.showMyToast("空间内还有未解决的问题")
                return@setOnClickListener
            }
            spaceMapVM.setJob(scene.choseSpace, "03")
        }

        /** 添加问题按钮 */
        addDot.setOnClickListener {
            scene.type = "dot"
            problemDot.mX = 0f
            problemDot.mY = 0f
            spaceStructure.visibility = View.GONE
            problemLl.visibility = View.VISIBLE
            problemRg.visibility = View.VISIBLE
            //画点
            pointRb.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    scene.type = "dot"
                    for (item in scene.drawingPipeItemList) {
                        scene.removeItem(item)
                    }
                    scene.drawingPipeItemList.clear()
                    for (item in scene.pipeNodeList) {
                        scene.removeItem(item)
                    }
                    scene.pipeNodeList.clear()
                    scene.pipeLineList.clear()
                }
            }
            //画线
            lineRb.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    scene.type = "pipe"
                    if (addPoint != null) {
                        scene.removeItem(addPoint!!)
                        scene.pointItemList.remove(addPoint)
                    }

                }
            }
            pointRb.isChecked = true
            showDotDetail(null)
            initProblemPicture(null)
        }

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

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


        /** 绑定二维码下一步 */
        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@SpaceMapActivity, CaptureActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE_SCAN)
        }


    }

    /**
     * 初始化问题图片
     */
    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.layoutManager = GridLayoutManager(this, 3)
        problemPicRecycler.adapter = pictureAdapter
    }


    /**
     * 初始化viewModel
     */
    private fun initViewModel() {
        spaceMapVM = SpaceMapVM(this.application, { name, params ->
            when (name) {
                /** 加载地图 */
                SpaceMapVM.MAP_LOAD -> {
                    val floorOfflineData = gson.fromJson(params.toString(), FloorData::class.java)
                    scene.loadData(floorOfflineData)
                    graphyView.fitSceneToView()
                }
                /** 查询空间和任务 */
                SpaceMapVM.SPACE_JOB -> {
                    for (item in scene.tunableSpaceList) {
                        scene.removeItem(item)
                    }
                    scene.tunableSpaceList.clear()

                    val list = params as (List<SpaceJobModel>)
                    for (model in list) {
                        if (model.outline != null && model.outline!!.isNotEmpty()) {
//                            val space = Space()
//                            space.outLine = model.outline
//                            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
                                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)
                        }
                    }
                }

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

                /** 查询空间核查问题 */
                SpaceMapVM.GET_PROBLEM -> {
                    graphyHelper.removeAllPoint()
                    val list = params as ArrayList<ProblemsModel>

                    for (model in list) {
                        if (model.geomType.equals("point")) {
                            val position = gson.fromJson(model.position, Position::class.java)
                            val point = Point()
                            val f = PointF()
                            f.x = position.x.toFloat()
                            f.y = position.y.toFloat()
                            point.points.add(f)
                            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) {
                                }

                            })
                        } else if (model.geomType.equals("line")) {
                            val geomList = gson.fromJson<List<PointF>>(
                                model.position,
                                object : TypeToken<List<PointF?>?>() {}.type
                            )
                            val point = Point()
                            point.points.addAll(geomList)
                            point.id = model.id
                            point.content = model.content
                            point.photos = model.photos
                            graphyHelper.addPoint(point)
                        }
                    }
                }

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

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

                /** 查询对象绑定的二维码 */
                SpaceMapVM.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()
                        val position = gson.fromJson(model.position, Position::class.java)
                        point.mX = position.x.toFloat()
                        point.mY = position.y.toFloat()

                        graphyHelper.addQrcode(this, point)
                    }
                }

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

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

            }
        }, this, buildingId, floorId, projectId)
        spaceMapVM.getMap()
//        spaceMapVM.getSpaceJob()
    }

    override fun onResume() {
        super.onResume()
        spaceMapVM.getSpaceJob()
    }

    val graphyHelper: GraphyHelper = GraphyHelper(scene, this)


    /**
     * 重置空间界面
     */
    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
        scene.type = "normal"
        modelCheckBox.isChecked = false
        scene.point = Point()
    }

    /**
     * 显示问题信息框
     */
    private fun showDotDetail(point: PointItem?) {
        spaceStructure.visibility = View.GONE
        doneSpaceStructure.visibility = View.GONE
        problemLl.visibility = View.VISIBLE
        if (point != null) {
            problemDesc.setText(point.data.content)
        } else {
            problemDesc.setText("")
        }
        initProblemPicture(point)

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

        /** 问题-关闭按钮 */
        problemClose.setOnClickListener {
            if (addPoint != null) {
                scene.removeItem(addPoint!!)
                scene.pointItemList.remove(addPoint)
            }
            for (item in scene.drawingPipeItemList) {
                scene.removeItem(item)
            }
            if (oprateItem != null) {
                scene.addItem(oprateItem!!)
                oprateItem = null
            }
            scene.drawingPipeItemList.clear()
            scene.pipeLineList.clear()
            removeDrawingLine()
            scene.type = "normal"
            problemLl.visibility = View.GONE
            spaceStructure.visibility = View.VISIBLE
        }

        /** 问题-保存按钮 */
        problemSave.setOnClickListener {
            if (pointRb.isChecked && (point == null || point.data.mX == 0f) && problemDot.mX == 0f) {
                ToastUtils.showMyToast("请扎点")
                return@setOnClickListener
            }
            if (point == null) {
                if (lineRb.isChecked && (CommonUtils.IsNull(scene.drawingPipeItemList) || (scene.drawingPipeItemList.size == 1 && scene.drawingPipeItemList[0].data.points.size <= 1))) {
                    ToastUtils.showMyToast("请扎点")
                    return@setOnClickListener
                }
            }
            scene.choseSpace?.let {
                spaceMapVM.addProblem(
                    point,
                    beans,
                    problemDesc.text.toString(),
                    problemDot.mX,
                    problemDot.mY,
                    scene.drawingPipeItemList, lineRb.isChecked
                )
            }
            for (item in scene.drawingPipeItemList) {
                scene.removeItem(item)
            }
            scene.pipeLineList.clear()
            removeDrawingLine()
            oprateItem = null
            scene.drawingPipeItemList.clear()
            scene.type = "normal"
            problemLl.visibility = View.GONE
        }
    }

    /**
     * 清空正在绘制的线型问题
     */
    private fun removeDrawingLine() {
        for (item in scene.pipeNodeList) {
            scene.removeItem(item)
        }
        scene.pipeNodeList.clear()
        for (item in scene.pipeItemList) {
            scene.removeItem(item)
        }
        scene.pipeItemList.clear()
    }

    /**
     * 回调
     */
    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")
                        spaceMapVM.bindQrcode(
                            scene.choseSpace,
                            result,
                            scene.point,
                            qrcodeEdit.text.toString()
                        )
                    }
                }
            /** 拍照选择图片回调 */
            REQUEST_CODE_PIC -> {
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        val pathList: List<String>? =
                            data.getStringArrayListExtra(Repair_ImgSelActivity.INTENT_RESULT)
                        doPicDatas(pathList)
                    }
                }
            }
            else -> {
            }
        }
    }

} // Class GraphyActivity
