/*
 * ********************************************************************************************************************
 *
 *               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.DialogInterface
import android.graphics.Color
import android.graphics.PointF
import android.os.Bundle
import android.widget.CheckBox
import android.widget.RadioButton
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
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.google.gson.Gson
import com.sybotan.android.demo.R
import com.sybotan.android.demo.bean.result.*
import com.sybotan.android.demo.graphy.GraphyHelper
import com.sybotan.android.demo.tools.CommonUtils
import com.sybotan.android.demo.tools.Lasso
import com.sybotan.android.demo.tools.ToastUtils
import com.sybotan.android.demo.viewmodel.GraphyVM
import com.sybotan.android.demo.viewmodel.SpaceMapVM
import com.sybotan.android.graphy.SGraphyView
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.android.closestDI
import kotlin.collections.ArrayList

/**
 * 设备服务区域绘制
 * 2021-11-12功能废弃
 */
class ServeAreaActivity : BaseActivity(), DIAware {

    override val di: DI by closestDI()

    /** 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 deviceId: String
    private var scale: Float = 0f
    private lateinit var area: ServeAreaItem
    private lateinit var centerPoint: PointF
    private lateinit var position: Position
    var tunableSpaceList = ArrayList<TunableSpaceItem>()

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

    val scene = FloorScene()
    private val gson = Gson()
    private var hasMove = false
    private val points = ArrayList<PointF>()
    private val items = ArrayList<AreaNodeItem>()

    private lateinit var graphyView: SGraphyView
    private lateinit var close: TextView
    private lateinit var save: TextView
    private lateinit var delete: TextView
    private lateinit var rect: RadioButton
    private lateinit var space: RadioButton

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

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

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

        return
    } // Function onCreate()


    private fun initView() {
        graphyView = findViewById(R.id.graphyView)
        close = findViewById(R.id.close)
        save = findViewById(R.id.save)
        delete = findViewById(R.id.delete)
        rect = findViewById(R.id.rect)
        space = findViewById(R.id.space)
    }

    /**
     * 初始化数据
     */
    private fun initData() {
        val params = intent.getBundleExtra("params")!!
        buildingId = params.getString("buildingId", "")!!
        floorId = params.getString("floorId", "")!!
        floorMap = params.getString("floorMap", "")!!
        projectId = params.getString("projectId", "")!!
        deviceId = params.getString("deviceId", "")!!
        scale = params.getFloat("scale")!!
        centerPoint = params.getParcelable("centerPoint")!!
        position = (params.getSerializable("position") as Position?)!!
        val p = Point()
        p.mX = position.x.toFloat()
        p.mY = position.y.toFloat()
        val equipItem = EquipItem(this, p)
        equipItem.zOrder = 100000f
        scene.addItem(equipItem)
    }


    /**
     * 图形点击事件
     * */
    private fun initSingleTopUp() {
        scene.setOnSingleTopUp(object : FloorScene.OnSingleTopUp {
            @SuppressLint("SetJavaScriptEnabled")
            override fun onSingUp(x: Float, y: Float) {
                if (rect.isChecked) {
                    if (points.size < 2) {
                        val point = PointF(x, -y)
                        points.add(point)
                        val item = AreaNodeItem(point)
                        item.zOrder = 100000f
                        scene.addItem(item)
                        items.add(item)
                        item.setOnScrollListener(object : AreaNodeItem.OnScroll {
                            override fun onScroll(x: Float, y: Float) {
                                hasMove = true
                                scene.removeItem(area)
                                points.clear()
                                for (it in items) {
                                    points.add(PointF(it.x, it.y))
                                }
                                area = ServeAreaItem(points)
                                area.zOrder = 100000f
                                scene.addItem(area)
                            }
                        })
                    }
                    if (points.size == 2 && !hasMove) {
                        hasMove = true
                        area = ServeAreaItem(points)
                        area.zOrder = 100000f
                        scene.addItem(area)
                    }
                } else {
                    for (space in tunableSpaceList) {
                        val isContain = Lasso.isPolygonContainsPoint(space.mPoints, android.graphics.Point(x.toInt(), -y.toInt()))
                        if (isContain) {
                            scene.removeItem(space)
                            tunableSpaceList.remove(space)
                            return
                        }
                    }

                    for (space in scene.spaceList) {
                        val isContain = Lasso.isPolygonContainsPoint(space.mPoints, android.graphics.Point(x.toInt(), -y.toInt()))
                        if (isContain) {
                            val tunableSpace = TunableSpace()
                            tunableSpace.outLine!!.add(space.data.outLine!!)
                            val item = TunableSpaceItem(tunableSpace)
                            item.zOrder = 99996f
                            tunableSpaceList.add(item)
                            scene.addItem(item)
                        }
                    }
                }
            }
        })
    }

    /**
     * 页面全部监听事件
     */
    private fun initListener() {
        close.setOnClickListener { finish() }
        save.setOnClickListener {
            if (rect.isChecked) {
                if (points.size < 2) {
                    ToastUtils.showMyToast("请绘制服务区域")
                    return@setOnClickListener
                }
                spaceMapVM.insServeArea(deviceId, points)
            } else {
                if (CommonUtils.IsNull(tunableSpaceList)) {
                    ToastUtils.showMyToast("请绘制服务区域")
                    return@setOnClickListener
                }
                spaceMapVM.insServeAreas(deviceId, tunableSpaceList)
            }
        }
        delete.setOnClickListener {
            val builder: AlertDialog.Builder =
                AlertDialog.Builder(this@ServeAreaActivity)
                    .setTitle("确认删除服务区域吗")
                    .setPositiveButton("确定",
                        DialogInterface.OnClickListener { dialogInterface, i ->
                            spaceMapVM.deleteServeArea(deviceId)
                            if (rect.isChecked) {
                                scene.removeItem(area)
                                for (item in items) {
                                    scene.removeItem(item)
                                }
                                items.clear()
                                points.clear()
                                hasMove = false
                            } else {
                                for (space in tunableSpaceList) {
                                    scene.removeItem(space)
                                }
                                tunableSpaceList.clear()
                            }

                        }).setNegativeButton("取消",
                        DialogInterface.OnClickListener { dialogInterface, i ->
                            dialogInterface.dismiss()
                        })
            builder.create().show()
        }

        rect.setOnClickListener {
            if (!CommonUtils.IsNull(tunableSpaceList)) {
                ToastUtils.showMyToast("请先删除服务区域")
                space.isChecked = true
                return@setOnClickListener
            }
        }
        space.setOnClickListener {
            if (!CommonUtils.IsNull(points)) {
                ToastUtils.showMyToast("请先删除服务区域")
                rect.isChecked = true
                return@setOnClickListener
            }
        }
    }

    /**
     * 初始化viewModel
     */
    private fun initViewModel() {
        spaceMapVM = SpaceMapVM(this.application, { name, params ->
            when (name) {
                /** 加载地图 */
                SpaceMapVM.MAP_LOAD -> {
                    val floorOfflineData = gson.fromJson(params.toString(), FloorData::class.java)
                    doAsync {
                        scene.loadData(floorOfflineData)
                        uiThread {
                            graphyView.setCenterPoint(centerPoint, scale)
//                            graphyView.setCenterPoint(PointF(1f,1f), 0f)
                        }
                    }
//                    graphyView.fitSceneToView()
                }
                /** 查询空间和任务 */
                GraphyVM.SPACE_JOB -> {
                    for (item in scene.tunableSpaceList) {
                        scene.removeItem(item)
                    }
                    scene.tunableSpaceList.clear()
                    val list = params as (List<SpaceJobModel>)
                    for (model in list) {
                        if (model.outline != 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
                                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.SERVE_AREA -> {
                    rect.isChecked = true
                    val pa = params as ArrayList<PointF>
                    for (i in 0..pa.size) {
                        if (i == 0 || i == 2) {
                            val point = pa[i]
                            points.add(point)
                            val item = AreaNodeItem(point)
                            item.zOrder = 100000f
                            scene.addItem(item)
                            items.add(item)
                            item.setOnScrollListener(object : AreaNodeItem.OnScroll {
                                override fun onScroll(x: Float, y: Float) {
                                    hasMove = true
                                    scene.removeItem(area)
                                    points.clear()
                                    for (it in items) {
                                        points.add(PointF(it.x, it.y))
                                    }
                                    area = ServeAreaItem(points)
                                    area.zOrder = 100000f
                                    scene.addItem(area)
                                }
                            })
                        }
                    }
                    hasMove = true
                    area = ServeAreaItem(points)
                    area.zOrder = 100000f
                    scene.addItem(area)
                }
                /** 物业空间 */
                SpaceMapVM.SERVE_AREAS -> {
                    space.isChecked = true
                    val param = params as ArrayList<ArrayList<ArrayList<PointZ>>>
                    for (space in param) {
                        val tunableSpace = TunableSpace()
                        tunableSpace.outLine = param
                        val item = TunableSpaceItem(tunableSpace)
                        item.zOrder = 99996f
                        tunableSpaceList.add(item)
                        scene.addItem(item)
                    }
                }

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


} // Class GraphyActivity
