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.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.ImageView
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.Infos
import com.sybotan.android.demo.adapter.PictureAdapter
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.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 EquipDetailActivity : BaseActivity(), View.OnTouchListener {
    //选择图片
    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 root: NestedScrollView
    private lateinit var pictureAdapter: PictureAdapter
    var list = ArrayList<Infos>()
    val beans: ArrayList<Photos> = ArrayList()
    private lateinit var staticInfoAdapter: StaticInfoAdapter

    // 自定义图片加载器
    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() {
        recycler = findViewById(R.id.recycler)
        viewRecycler = findViewById(R.id.viewRecycler)
        mtextContent = findViewById(R.id.mtextContent)
        root = findViewById(R.id.root)
        recycler.layoutManager = LinearLayoutManager(this)
        viewRecycler.layoutManager = GridLayoutManager(this, 3)
        mtextContent.setOnTouchListener(this)
        val photo = Photos()
        photo.itemType = 1
        beans.add(photo)
        val pictureAdapter = PictureAdapter(this, beans, "", false, 0, 85)
        viewRecycler.adapter = pictureAdapter
        pictureAdapter.setOnPicAdd { addPic() }
    }

    //重写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() {
        staticInfoAdapter = StaticInfoAdapter(this, list)
        staticInfoAdapter.setOnAddPic { addPic()
            this.info = it}
        recycler.adapter = staticInfoAdapter
    }

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