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.widget.ImageView
import android.widget.TextView
import androidx.core.widget.NestedScrollView
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 cn.sagacloud.android.cadengine.types.TunableSpace
import com.framework.mvvm.model.db.entity.Infos
import com.sybotan.android.demo.retrofit.Constant
import com.sybotan.android.demo.tools.LocalDataOperation
import com.sybotan.android.demo.tools.PictureUtils
import com.sybotan.android.demo.tools.ToastUtils
import com.sybotan.android.demo.tools.UploadImage
import com.sybotan.android.demo.viewmodel.GraphyVM
import com.yuyh.library.imgsel.ImageLoader
import com.yuyh.library.imgsel.ImgSelConfig
import io.reactivex.ObservableEmitter
import org.json.JSONException
import org.json.JSONObject
import java.io.File

/**
 * Created by lihao.
 * Date: 2021/9/27
 */
class SpaceDetailActivity : BaseActivity() {
    private lateinit var info: Infos

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

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

    /** 项目Id */
    private lateinit var projectId: String
    private lateinit var spaceId: String
    private lateinit var space: TunableSpace
    val beans: ArrayList<Photos> = ArrayList()

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

    /** viewModel */
    lateinit var graphyVM: GraphyVM
    var list = ArrayList<Infos>()

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

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

    private lateinit var staticInfoAdapter: StaticInfoAdapter

    private fun initData() {
        staticInfoAdapter.setOnAddPic {
            addPic()
            this.info = it
        }
        recycler.adapter = staticInfoAdapter
        graphyVM = GraphyVM(this.application, { name, params ->
            when (name) {
                GraphyVM.SPACE_INFO -> {
                    list.addAll(params as ArrayList<Infos>)
                    staticInfoAdapter.notifyDataSetChanged()
                }
            }
        }, this, buildingId, floorId, projectId)
        graphyVM.getInfosConfig(spaceId)
    }

    private fun initView() {
        val floor = intent.getBundleExtra("floor")!!
        buildingId = floor.getString("buildingId")!!
        floorId = floor.getString("floorId")!!
        projectId = floor.getString("projectId")!!
        spaceId = floor.getString("spaceId")!!
        space = floor.getParcelable("space")!!
        recycler = findViewById(R.id.recycler)
        root = findViewById(R.id.root)
        btnSubmit = findViewById(R.id.btnSubmit)
        recycler.layoutManager = LinearLayoutManager(this)
        staticInfoAdapter = StaticInfoAdapter(this, list)
        btnSubmit.setOnClickListener {
            graphyVM.refreshObject(space, staticInfoAdapter.hashMap)
        }
    }

    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>?) {
        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)
//                                        viewModel.picPathList.add(photos)
//                                        viewModel.content.pictures.add(key)
                                    }
                                }
                            } else {
                                val photos =
                                    Photos()
                                photos.itemType = 0
                                photos.path = path
                                photos.key = key
                                beans.add(photos)
//                                viewModel.picPathList.add(photos)
//                                viewModel.content.pictures.add(key)
                            }
                        }
                    }
                    emitter.onNext("")
                }
                LocalDataOperation.DEAL_DATA_NEXT -> {
                    ToastUtils.showMyToast("图片上传完毕")
                    staticInfoAdapter.hashMap.put(info.code, beans)
                }
                LocalDataOperation.DEAL_DATA_ERROR -> {
                    ToastUtils.showMyToast("图片上传失败")
                }
                else -> {
                }
            }
        }
    }
}