package com.sybotan.android.demo.activities

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.*
import androidx.appcompat.widget.SwitchCompat
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.sybotan.android.demo.R
import com.sybotan.android.demo.adapter.StaticInfoAdapter
import cn.sagacloud.android.cadengine.types.Photos
import com.framework.mvvm.model.db.entity.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.sybotan.android.demo.adapter.PictureAdapter
import com.sybotan.android.demo.adapter.PipeExpandAdapter
import com.sybotan.android.demo.adapter.RelationExpandAdapter
import com.sybotan.android.demo.bean.result.Position
import com.sybotan.android.demo.bean.result.Z
import com.sybotan.android.demo.retrofit.Constant
import com.sybotan.android.demo.tools.*
import com.sybotan.android.demo.tools.LocalDataOperation.*
import com.sybotan.android.demo.view.*
import com.sybotan.android.demo.viewmodel.GraphyVM
import com.sybotan.base.extensions.toBoolean
import com.yuyh.library.imgsel.ImageLoader
import com.yuyh.library.imgsel.ImgSelConfig
import com.yuyh.library.imgsel.utils.LogUtils
import io.reactivex.ObservableEmitter
import org.json.JSONException
import org.json.JSONObject
import java.io.File
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by lihao.
 * Date: 2021/9/27
 */
class EquipDetailActivity : BaseActivity(), View.OnTouchListener {
    private var equipEntity: EquipmentEntity? = null

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

    private lateinit var info: Infos
    private lateinit var recycler: RecyclerView
    private lateinit var viewRecycler: RecyclerView
    private lateinit var mtextContent: EditText
    private lateinit var localName: ListItemView
    private lateinit var localId: ListItemView
    private lateinit var location: ListItemView
    private lateinit var doneSwitch: SwitchCompat
    private lateinit var height: ListItemView
    private lateinit var locationWhere: ListItemView
    private lateinit var equipClass: ListItemView
    private lateinit var root: NestedScrollView
    private lateinit var btnSubmit: TextView
    private lateinit var expandLvPipe: SuperExpandableListView
    private lateinit var expandLvRelation: SuperExpandableListView
    private lateinit var pictureAdapter: PictureAdapter
    private lateinit var groupRelConfigEntity: RelConfigEntity
    private lateinit var groupPipeConfigEntity: PipeConfigEntity
    var list = ArrayList<Infos>()
    val beans: ArrayList<Photos> = ArrayList()
    private lateinit var staticInfoAdapter: StaticInfoAdapter
    private var spaceId = ""
    private var position: Position? = null

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

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

    /** viewModel */
    lateinit var graphyVM: GraphyVM
    private lateinit var dialog: EquipListDialog
    var equips: List<EquipmentEntity> = ArrayList()

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_equip_detail)
        initView()
        initData()
        return
    } // Function onCreate()

    private fun initView() {
        val intent = intent
        val bundle = intent.getBundleExtra("equip")
        buildingId = bundle?.getString("buildingId")!!
        floorId = bundle?.getString("floorId")!!
        spaceId = bundle?.getString("spaceId") ?: ""
        position = bundle?.getSerializable("position") as? Position
        projectId = bundle?.getString("projectId")!!
        deviceId = bundle?.getString("deviceId", "")
        uuid = IdGenerator.getId(projectId, IdGenerator.EQUIPMENT)
        recycler = findViewById(R.id.recycler)
        height = findViewById(R.id.height)
        locationWhere = findViewById(R.id.locationWhere)
        equipClass = findViewById(R.id.equipClass)
        location = findViewById(R.id.location)
        doneSwitch = findViewById(R.id.doneSwitch)
        viewRecycler = findViewById(R.id.viewRecycler)
        mtextContent = findViewById(R.id.mtextContent)
        localName = findViewById(R.id.localName)
        localId = findViewById(R.id.localId)
        root = findViewById(R.id.root)
        btnSubmit = findViewById(R.id.btnSubmit)
        expandLvPipe = findViewById(R.id.expandLvPipe)
        expandLvRelation = findViewById(R.id.expandLvRelation)
        expandLvPipe.setGroupIndicator(null)
        expandLvPipe.divider = null
        expandLvRelation.setGroupIndicator(null)
        expandLvRelation.divider = null
        localName.setTvLeft("设备名称")
        localId.setTvLeft("设备编码")
        localId.setRightIconGone(true)
        recycler.layoutManager = LinearLayoutManager(this)
        viewRecycler.layoutManager = GridLayoutManager(this, 3)
        mtextContent.setOnTouchListener(this)
        val photo = Photos()
        photo.itemType = 1
        beans.add(photo)
        pictureAdapter = PictureAdapter(this, beans, "", false, 0, 85)
        viewRecycler.adapter = pictureAdapter
        pictureAdapter.setOnPicAdd { addPic() }
        height.setTvRight(position!!.z.offset)
        locationWhere.setTvRight(position!!.z.region)
        location.setTvRight("(x=${position!!.x},y=${position!!.y})")
        equipClass.setOnClickListener {
            dialog.show()
        }
        btnSubmit.setOnClickListener {
            var localNameString = (localName.getView(R.id.et_right)) as EditText
            var localIdString = (localId.getView(R.id.et_right)) as EditText
            if (equipEntity == null) {
                ToastUtils.showMyToast("请选择设备类")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(localIdString.text.trim())) {
                ToastUtils.showMyToast("请输入设备编码")
                return@setOnClickListener
            }
            graphyVM.insEquip(
                uuid,
                deviceId,
                staticInfoAdapter.hashMap,
                mtextContent.text.toString(),
                beans,
                equipEntity!!,
                localNameString.text.toString(),
                localIdString.text.toString(),
                doneSwitch.isChecked, position!!
            )
        }
    }

    //重写onTouch方法
    override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
        //触摸的是EditText控件，且当前EditText可以滚动，则将事件交给EditText处理；否则将事件交由其父类处理
        if (view.id == R.id.mtextContent && canVerticalScroll(mtextContent)) {
            view.parent.requestDisallowInterceptTouchEvent(true)
            if (motionEvent.action == MotionEvent.ACTION_UP) {
                view.parent.requestDisallowInterceptTouchEvent(false)
            }
        }
        return false
    }

    /**
     * EditText竖直方向是否可以滚动
     * @param editText  需要判断的EditText
     * @return  true：可以滚动   false：不可以滚动
     */
    private fun canVerticalScroll(editText: EditText): Boolean {
        return if (editText.canScrollVertically(-1) || editText.canScrollVertically(1)) {
            //垂直方向上可以滚动
            true
        } else false
    }

    private fun initData() {
        dialog = EquipListDialog(this)
        dialog.setOnSubmit {
            this.equipEntity = it
            equipClass.setTvRight(it.systemName + "/" + it.name)
            graphyVM.getEquipInfosConfig(it)
            graphyVM.getRelConfig(it, deviceId, uuid)

        }
        staticInfoAdapter = StaticInfoAdapter(this, list)
        staticInfoAdapter.setOnAddPic {
            addPic()
            this.info = it
        }
        recycler.adapter = staticInfoAdapter
        graphyVM = GraphyVM(this.application, { name, params ->
            when (name) {
                GraphyVM.EQUIP_CLASS -> {
                    equips = params as List<EquipmentEntity>
                    dialog.setList(equips);
                }
                GraphyVM.EQUIP_INFO -> {
                    if (params != null) {
                        list.clear()
                        list.addAll(params as ArrayList<Infos>)
                        staticInfoAdapter.notifyDataSetChanged()
                    }
                }

                GraphyVM.SPACE_INFOS -> {
                    if (params != null) {
                        staticInfoAdapter.hashMap = params as HashMap<String, Any>?
                        if (staticInfoAdapter.hashMap != null && staticInfoAdapter.hashMap.get("equipContent") != null) {
                            mtextContent.setText(
                                staticInfoAdapter.hashMap.get("equipContent").toString()
                            )
                        }
                        if (staticInfoAdapter.hashMap != null && staticInfoAdapter.hashMap.get("equipCheck") != null) {
                            val boo = staticInfoAdapter.hashMap.get("equipCheck")
                            doneSwitch.isChecked = boo!!.toString().equals("true")
                        }
                        if (staticInfoAdapter.hashMap != null && staticInfoAdapter.hashMap.get("zRegion") != null) {
                            val zRegion = staticInfoAdapter.hashMap.get("zRegion")
                            locationWhere.setTvRight(zRegion.toString())
                            if (position!!.z == null) {
                                val z = Z()
                                z.region = zRegion.toString()
                                position!!.z = z
                            } else {
                                position!!.z.region = zRegion.toString()
                            }
                        }
                        if (staticInfoAdapter.hashMap != null && staticInfoAdapter.hashMap.get("equipPhoto") != null) {
                            val infoList = Gson().fromJson<List<Photos>>(
                                staticInfoAdapter.hashMap.get("equipPhoto").toString(),
                                object : TypeToken<List<Photos?>?>() {}.type
                            )
                            beans.clear()
                            beans.addAll(infoList)
                            pictureAdapter.notifyDataSetChanged()

                        } else {
                            LogUtils.e("mei")
                        }
                    }
                }
                GraphyVM.Equip_INFOS -> {
                    var equip = params as ObjectEntity
                    localId.setEtRight(equip.localId)
                    deviceId = equip.id
                    val strInfo = Gson().fromJson(equip.strInfos, StrInfosforEquip::class.java)
                    height.setTvRight(strInfo.location.z.toString())
                    if (position!!.z == null) {
                        val z = Z()
                        z.offset = strInfo.location.z.toString()
                        position!!.z = z
                    } else {
                        position!!.z.offset = strInfo.location.z.toString()
                    }
                    if (this.equipEntity == null) {
                        for (eq in equips) {
                            if (equip.classCode.equals(eq.code)) {
                                this.equipEntity = eq
//                            graphyVM.getRelConfig(eq, deviceId, uuid)
                                equipClass.setTvRight(equipEntity!!.systemName + "/" + equipEntity!!.name)
                                graphyVM.getEquipInfosConfig(equipEntity!!)
                                graphyVM.getEquipment(deviceId)
                                break
                            }
                        }
                    }
                }
                GraphyVM.EQUIP_REL -> {
                    val hashMap = params as HashMap<String, Any>
                    val parent = hashMap.get("parent") as ArrayList<RelConfigEntity>
                    val children = hashMap.get("child") as MutableList<List<RelationEntity>>
                    val relAdapter =
                        RelationExpandAdapter(this@EquipDetailActivity, parent, children)
                    relAdapter.setOnAdd(object : RelationExpandAdapter.AddRel {
                        override fun onAdd(group: RelConfigEntity) {
                            this@EquipDetailActivity.groupRelConfigEntity = group
                            graphyVM.getRelObj(group, equipEntity!!.code!!)
                        }
                    })
                    relAdapter.setOnDelete(object : RelationExpandAdapter.DeleteRel {
                        override fun ondelete(item: RelationEntity) {
                            graphyVM.deleteRel(item, equipEntity, deviceId, uuid)
                        }
                    })
                    expandLvRelation.setAdapter(relAdapter)
                    for (index in 0 until expandLvRelation.count) {
                        expandLvRelation.expandGroup(index)
                    }
                }
                GraphyVM.REL_OBJECT -> {
                    val equipObjects = params as List<ObjectEntity>
                    val pop = SelectListPopupWindow(this)
                    pop.setList(equipObjects, Constant.TYPE2)
                    pop.setTitle(true, "单选选择对象")
                    pop.showAtLocation(root, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
                    pop.setOnCommit(object : SelectListPopupWindow.Commit {
                        override fun onCommit(list: java.util.ArrayList<Int>?) {
                            if (!CommonUtils.IsNull(list)) {
                                val equip = equipObjects.get(list!!.get(0))
                                val localIdString = (localId.getView(R.id.et_right)) as EditText
                                val dialog = ObjectRelationDialog(
                                    this@EquipDetailActivity,
                                    localIdString.text.toString(),
                                    equip,
                                    groupRelConfigEntity
                                )
                                dialog.show()
                                dialog.setOnSubmit {
                                    graphyVM.addRel(
                                        deviceId,
                                        uuid,
                                        equipEntity!!,
                                        equip,
                                        groupRelConfigEntity
                                    )
                                }
                            }
                        }
                    })
                }
                GraphyVM.PIPE -> {
                    val hashMap = params as HashMap<String, Any>
                    val parent = hashMap.get("parent") as ArrayList<PipeConfigEntity>
                    val children = hashMap.get("child") as MutableList<List<PipeEntity>>
                    val pipeAdapter = PipeExpandAdapter(this, parent, children)
                    pipeAdapter.setOnAdd(object : PipeExpandAdapter.AddRel {
                        override fun onAdd(group: PipeConfigEntity) {
                            this@EquipDetailActivity.groupPipeConfigEntity = group
                            graphyVM.getPipeObj(group, equipEntity!!.code!!)
                        }
                    })
                    expandLvPipe.setAdapter(pipeAdapter)
                    pipeAdapter.setOnDelete(object : PipeExpandAdapter.DeleteRel {
                        override fun ondelete(item: PipeEntity) {
                            graphyVM.deletePipe(item, equipEntity, deviceId, uuid)
                        }
                    })
                    for (index in 0 until expandLvPipe.count) {
                        expandLvPipe.expandGroup(index)
                    }
                }
                GraphyVM.PIPE_OBJECT -> {
                    val equipObjects = params as List<ObjectEntity>
                    val pop = SelectListPopupWindow(this)
                    pop.setList(equipObjects, Constant.TYPE2)
                    pop.setTitle(true, "单选选择对象")
                    pop.showAtLocation(root, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
                    pop.setOnCommit(object : SelectListPopupWindow.Commit {
                        override fun onCommit(list: ArrayList<Int>?) {
                            if (!CommonUtils.IsNull(list)) {
                                val equip = equipObjects.get(list!!.get(0))
                                val localIdString = (localId.getView(R.id.et_right)) as EditText
                                val dialog = PipeDialog(
                                    this@EquipDetailActivity,
                                    localIdString.text.toString(),
                                    equip,
                                    groupPipeConfigEntity
                                )
                                dialog.show()
                                dialog.setOnSubmit {
                                    graphyVM.addPipe(
                                        deviceId,
                                        uuid,
                                        equipEntity!!,
                                        equip,
                                        groupPipeConfigEntity
                                    )
                                }
                            }
                        }
                    })
                }
            }
        }, this, buildingId, floorId, projectId)
        graphyVM.getEquipment(deviceId)
    }

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

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_PIC) {
            if (data != null) {
                val pathList: List<String>? =
                    data.getStringArrayListExtra(Repair_ImgSelActivity.INTENT_RESULT)
                doPicDatas(pathList)
            }
        }
    }

    private fun doPicDatas(pathList: List<String>?) {
        getInstance().dealLocalData<Photos>(this) { name, params ->
            when (name) {
                SHOW_DIALOG_IN_MAIN -> ToastUtils.showMyToast("图片上传中")
                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("")
                }
                DEAL_DATA_NEXT -> {
                    ToastUtils.showMyToast("图片上传完毕")
                    pictureAdapter.notifyDataSetChanged()
                    staticInfoAdapter.valueList.clear()
                    staticInfoAdapter.notifyDataSetChanged()
//                    if (info != null) {
//                        staticInfoAdapter.hashMap.put(info.code, beans)
//                    }
                }
                DEAL_DATA_ERROR -> {
                    ToastUtils.showMyToast("图片上传失败")
                }
                else -> {
                }
            }
        }
    }
}