package com.lukouguoji.mit.adapt

import android.app.Activity
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.luck.picture.lib.entity.LocalMedia
import com.lukouguoji.mit.R
import com.lukouguoji.mit.viewModel.AccidentVisaInfoViewModel
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import com.lukouguoji.module_base.util.Common


class PictureAdapter(
    val activity: Activity,
    private val viewModel: AccidentVisaInfoViewModel,
    private val list: ArrayList<LocalMedia>
) :
    RecyclerView.Adapter<PictureAdapter.ViewHolder>() {

    private var selectMax = 9
    val TYPE_CAMERA = 1
    val TYPE_PICTURE = 2

    fun setSelectMax(selectMax: Int) {
        this.selectMax = selectMax
    }

    fun getSelectMax(): Int {
        return selectMax
    }

    fun getData(): ArrayList<LocalMedia>? {
        return list
    }

    fun remove(position: Int) {
        if (position < list.size) {
            list.removeAt(position)
        }
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val mImg: ImageView = view.findViewById(R.id.fiv)
        val mIvDel: ImageView = view.findViewById(R.id.iv_del)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.accident_visa_image_item, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {

        //少于MaxSize张，显示继续添加的图标
        if (getItemViewType(position) == TYPE_CAMERA) {
            viewHolder.mImg.setImageResource(R.mipmap.ic_add_image)
            viewHolder.mImg.setOnClickListener(View.OnClickListener {
                mItemClickListener?.openPicture()
            })
            viewHolder.mIvDel.setVisibility(View.INVISIBLE)
        } else {
            viewHolder.mIvDel.setVisibility(View.VISIBLE)
            //删除图片
            viewHolder.mIvDel.setOnClickListener(View.OnClickListener { view: View? ->
                Common.secondConfirmDialog(activity, "确认删除?") { dialog ->
                    dialog.dismiss()
                    val index: Int = viewHolder.absoluteAdapterPosition
                    if (index != RecyclerView.NO_POSITION && list.size > index) {
                        //删除服务器图片
                        var delModel = list[index]
                        var fileName = delModel.fileName
                        var realName = viewModel.imageKeyValue[fileName]
                        if (realName != null && realName != "") {
                            viewModel.deleteImg(realName)
                        } else {
                            viewModel.deleteImg(fileName)
                        }
                        //删除本地图片
                        list.removeAt(index)
                        notifyItemRemoved(index)
                        notifyItemRangeChanged(index, list.size)
                    }
                }
            })
            val media: LocalMedia = list[position]
            val path = media.availablePath

            val tokenGlide = GlideUrl(
                path,
                LazyHeaders.Builder().addHeader("Authorization", SharedPreferenceUtil.getString(Constant.Share.token)).build()
            )
            //网络图片地址渲染
            if(media.realPath == null){
                Glide.with(viewHolder.itemView.getContext())
                    .load(tokenGlide)
                    .centerCrop()
                    .placeholder(R.color.white)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(viewHolder.mImg)
            }
            //本地渲染
            else{
                Glide.with(viewHolder.itemView.getContext())
                    .load(path)
                    .centerCrop()
                    .placeholder(R.color.white)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(viewHolder.mImg)
            }


            //itemView 的点击事件
            if (mItemClickListener != null) {
                viewHolder.itemView.setOnClickListener(View.OnClickListener { v: View? ->
                    val adapterPosition: Int = viewHolder.getAbsoluteAdapterPosition()
                    mItemClickListener!!.onItemClick(v, adapterPosition)
                })
            }
        }
    }

    override fun getItemCount() = if (list.size < getSelectMax()) {
        list.size + 1
    } else {
        list.size
    }

    override fun getItemViewType(position: Int): Int {
        return if (isShowAddItem(position)) {
            TYPE_CAMERA
        } else {
            TYPE_PICTURE
        }
    }

    private fun isShowAddItem(position: Int): Boolean {
        val size: Int = list.size
        return position == size
    }

    private var mItemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(l: OnItemClickListener?) {
        mItemClickListener = l
    }


    interface OnItemClickListener {
        /**
         * Item click event
         *
         * @param v
         * @param position
         */
        fun onItemClick(v: View?, position: Int)

        /**
         * Open PictureSelector
         */
        fun openPicture()
    }
}