package com.lukouguoji.gjj.adapt

import android.app.Activity
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.model.GjjCangDanInfoItemModel
import com.lukouguoji.module_base.common.String.isValidInt
import com.lukouguoji.module_base.util.Common
import java.util.*

class GjjCangDanInfoAdapter(val activity: Activity, private val collectList: MutableList<GjjCangDanInfoItemModel>) :
    RecyclerView.Adapter<GjjCangDanInfoAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val titleName: TextView = view.findViewById(R.id.titleName)
        val isMust: TextView = view.findViewById(R.id.isMust)
        val inputLayout: LinearLayout = view.findViewById(R.id.inputLayout)
        val inputContent: EditText = view.findViewById(R.id.inputContent)
        val inputContentPreView: View = view.findViewById(R.id.inputContentPreView)
        val inputContentPre: EditText = view.findViewById(R.id.inputContentPre)
        val selContent: TextView = view.findViewById(R.id.selContent)
    }

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

        /* viewHolder.itemView.setOnClickListener {

             var adapterPosition = viewHolder.adapterPosition
             if (adapterPosition < 0 || collectList.isEmpty()) {
                return@setOnClickListener
            }
             var gncFuBang = collectList[adapterPosition]

             ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GOUT_FU_BANG_ACTIVITY).withString("userIdParam", gncFuBang.useId.toString())
                 .navigation(activity, Constant.RequestCode.gnc_shouyun_list_refresh)

         }
 */
        return viewHolder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val collect = collectList[position]
        val must = collect.isMust
        val enable = collect.isEnable
        val titleName = collect.titleName
        val isSel = collect.isSel
        val inputContent = collect.inputContent
        val inputContentPre = collect.inputContentPre
        val selList = collect.selList
        val selContentCode = collect.selContentCode
        val selContentName = collect.selContentName

        //是否必填
        if (must) {
            holder.isMust.visibility = View.VISIBLE
        } else {
            holder.isMust.visibility = View.GONE
        }
        holder.titleName.text = titleName
        //下拉框
        if (isSel) {
            holder.selContent.visibility = View.VISIBLE
            holder.inputLayout.visibility = View.GONE

            var anyMatchCode = false
            selList?.forEach { sel ->
                var selObj = sel as JSONObject
                var name = selObj.getString("name")
                var code = selObj.getString("code")
                if (selContentCode == code) {
                    anyMatchCode = true
                    holder.selContent.text = name
                }
            }
            //没匹配到，渲染成selContentName
            if (!anyMatchCode) {
                holder.selContent.text = selContentName
            }

            //是否允许
            holder.selContent.isEnabled = enable
            if (enable) {
                holder.selContent.setBackgroundResource(R.drawable.gjj_cang_dan_info_edit_shape)
            } else {
                holder.selContent.setBackgroundResource(R.drawable.gjj_cang_dan_info_edit_disable_shape)
            }
            //下拉框监听
            holder.selContent.setOnClickListener {
                Common.singleSelect(activity, titleName, selList!!, selContentCode) { _, item ->
                    val jsonObject = item as JSONObject
                    val code = jsonObject.getString("code")
                    collect.selContentCode = code
                    notifyDataSetChanged()
                }
            }
        }
        //输入框
        else {
            //输入框1
            holder.selContent.visibility = View.GONE
            holder.inputContentPreView.visibility = View.GONE
            holder.inputContentPre.visibility = View.GONE
            holder.inputLayout.visibility = View.VISIBLE
            holder.inputContent.visibility = View.VISIBLE

            //是否允许
            holder.inputContent.isEnabled = enable
            if (enable) {
                holder.inputContent.setBackgroundResource(R.drawable.gjj_cang_dan_info_edit_shape)
            } else {
                holder.inputContent.setBackgroundResource(R.drawable.gjj_cang_dan_info_edit_disable_shape)
            }
            holder.inputContent.setText(inputContent)
            holder.inputContent.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                }

                override fun afterTextChanged(s: Editable?) {
                    collect.inputContent = s.toString()
                }
            })
            //如果是订单，监听输入事件
            if (collect.titleCode == "no") {
                //失去焦点
                holder.inputContent.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
                    if (hasFocus) {

                    } else {
                        val editText = v as EditText
                        //失去焦点
                        if (editText.text.toString().length != 8 || !editText.text.toString().isValidInt()) {
                            Common.showToast(activity, "请输入正确的运单号格式！")
                            return@OnFocusChangeListener
                        }
                        val subSequence = editText.text.toString().subSequence(0, 7).toString().toInt()
                        val subSequence2 = editText.text.toString()[7].toString().toInt()
                        if (subSequence % 7 != subSequence2) {
                            Common.showToast(activity, "请输入正确的运单号格式！")
                            return@OnFocusChangeListener
                        }
                    }
                }
            }
            //如果是始发港或者目的港，监听输入事件 只能输入大写字母
            if (collect.titleCode == "origin" || collect.titleCode == "dest") {
                //失去焦点
                holder.inputContent.addTextChangedListener(object : TextWatcher {
                    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

                    }

                    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                    }

                    override fun afterTextChanged(editable: Editable?) {
                        val originText = editable.toString()
                        if (originText != null && originText != "") {
                            val regularExpression = "(^([A-Z]+)$)"
                            val matches = originText.matches(regularExpression.toRegex())
                            if(!matches){
                                val regularExpression2 = "([^A-Za-z]+)"
                                val replaceStr = originText.replace(regularExpression2.toRegex(),"")
                                val replaceStrToUpper = replaceStr.uppercase(Locale.ROOT)//小写转大写
                                holder.inputContent.setText(replaceStrToUpper)
                                holder.inputContent.setSelection(replaceStrToUpper.length)
                            }
                        }
                    }
                })
            }


            //输入框2
            if (collect.titleCodePre != null && collect.inputContentPre != null) {
                holder.inputContentPreView.visibility = View.VISIBLE
                holder.inputContentPre.visibility = View.VISIBLE

                //是否允许
                holder.inputContentPre.isEnabled = enable
                if (enable) {
                    holder.inputContentPre.setBackgroundResource(R.drawable.gjj_cang_dan_info_edit_shape)
                } else {
                    holder.inputContentPre.setBackgroundResource(R.drawable.gjj_cang_dan_info_edit_disable_shape)
                }
                holder.inputContentPre.setText(inputContentPre)
                holder.inputContentPre.addTextChangedListener(object : TextWatcher {
                    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

                    }

                    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                    }

                    override fun afterTextChanged(s: Editable?) {
                        collect.inputContentPre = s.toString()
                    }
                })
            }

        }

    }

    override fun getItemCount() = collectList.size

    fun append(gjjCangDanInfoItemModel: GjjCangDanInfoItemModel) {
        collectList.add(gjjCangDanInfoItemModel)
        notifyDataSetChanged()
    }
}