package com.lukouguoji.mit.adapt

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.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.mit.R
import com.lukouguoji.mit.activity.AccidentVisaInfoActivity
import com.lukouguoji.mit.model.AccidentVisaInfoItemModel
import com.lukouguoji.mit.viewModel.AccidentVisaInfoViewModel
import com.lukouguoji.module_base.common.String.isValidInt
import com.lukouguoji.module_base.util.Common
import java.text.SimpleDateFormat
import java.util.*

class AccidentVisaInfoAdapter(
    val activity: AccidentVisaInfoActivity,
    val viewModel: AccidentVisaInfoViewModel,
    private val collectList: MutableList<AccidentVisaInfoItemModel>
) :
    RecyclerView.Adapter<AccidentVisaInfoAdapter.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)
        val scanIcon: ImageView = view.findViewById(R.id.scanIcon)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.accident_visa_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 ymdhms = collect.ymdhms
        val selContentCode = collect.selContentCode
        val scan = collect.scan
        val scanResultCode = collect.scanResultCode

        //是否必填
        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

            //1.单选下拉框
            selList?.forEach { sel ->
                var selObj = sel as JSONObject
                var name = selObj.getString("name")
                var code = selObj.getString("code")
                if (selContentCode == code) {
                    holder.selContent.text = name
                }
            }
            //2.时间下拉框
            ymdhms?.let {
                holder.selContent.text = selContentCode
            }

            //是否允许
            holder.selContent.isEnabled = enable
            if (enable) {
                holder.selContent.setBackgroundResource(R.drawable.mit_in_pack_list_input_edit_text)
            } else {
                holder.selContent.setBackgroundResource(R.drawable.accident_visa_info_edit_disable_shape)
            }
            //下拉框监听
            holder.selContent.setOnClickListener {
                if (selList != null) {
                    Common.singleSelect(activity, titleName, selList!!, selContentCode) { _, item ->
                        val jsonObject = item as JSONObject
                        val code = jsonObject.getString("code")
                        collect.selContentCode = code
                        notifyDataSetChanged()
                    }
                } else if (ymdhms != null) {
                    if (ymdhms) {
                        Common.onYearMonthDayTime(activity, collect.selContentCode) { year, month, day, hour, minute, second ->
                            val calendar = Calendar.getInstance()
                            val ymdHmsSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")//年月日 时分秒
                            calendar.set(year, month - 1, day, hour, minute, second)
                            val dateRes = ymdHmsSdf.format(calendar.time)
                            collect.selContentCode = dateRes
                            notifyDataSetChanged()
                        }
                    } else {
                        Common.onYearMonthDay(activity, collect.selContentCode) { year, month, day ->
                            val calendar = Calendar.getInstance()
                            val ymdSdf = SimpleDateFormat("yyyy-MM-dd")//年月日
                            calendar.set(year, month - 1, day)
                            collect.selContentCode = ymdSdf.format(calendar.time)
                            //如果是fdate另算
                            if (collect.titleCode == "fdate") {
                                var fno = ""
                                collectList.forEach { c ->
                                    if (c.titleCode == "fno") {
                                        fno = c.inputContent
                                        return@forEach
                                    }
                                }
                                if (collect.selContentCode != "" && fno != "") {
                                    viewModel.queryFlight(collect.selContentCode, fno)
                                }
                            }
                            notifyDataSetChanged()
                        }
                    }
                } else {
                    Common.showToast(activity, "暂无选项！")
                }
            }
        }
        //输入框
        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.mit_in_pack_list_input_edit_text)
            } else {
                holder.inputContent.setBackgroundResource(R.drawable.accident_visa_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 (scan != null && scan) {
                holder.scanIcon.visibility = View.VISIBLE
                holder.scanIcon.setOnClickListener {
                    activity.scanCode(scanResultCode ?: -9999)
                }
            } else {
                holder.scanIcon.visibility = View.GONE
            }
            // 1.如果是订单no，监听输入事件
            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
                        }
                    }
                }
            }
            // 2.如果是订单 wbNo ，监听输入事件
            if (collect.titleCode == "wbNo") {
                //输入监听
                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) {
                        if (s != null && s.toString().length > 11) {
                            var wbNoStr = s.toString()
                            Common.alertDialog(activity, "请输入正确的运单号格式！") { dialog ->
                                dialog.dismiss()
                                wbNoStr = wbNoStr.substring(0, 11)
                                collectList.forEach { c ->
                                    if (c.titleCode == "wbNo") {
                                        c.inputContent = wbNoStr.substring(0, 11)
                                        return@forEach
                                    }
                                }
                                notifyDataSetChanged()
                            }
                        }
                    }

                    override fun afterTextChanged(s: Editable?) {

                    }
                })
                //失去焦点
                holder.inputContent.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
                    if (hasFocus) {

                    } else {
                        val editText = v as EditText
                        //失去焦点
                        val editTextStr = editText.text.toString()
                        if (editTextStr.length < 11) {
                            Common.showToast(activity, "请输入正确的运单号格式！")
                            return@OnFocusChangeListener
                        }
                    }
                }
            }
            // 3.如果是订单 fno ，监听输入事件
            if (collect.titleCode == "fno") {
                //失去焦点
                holder.inputContent.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
                    if (hasFocus) {

                    } else {
                        val editText = v as EditText
                        var fdate = ""
                        collectList.forEach { c ->
                            if (c.titleCode == "fdate") {
                                fdate = c.selContentCode
                                return@forEach
                            }
                        }
                        if (fdate != "" && editText.text.toString() != "") {
                            viewModel.queryFlight(fdate, editText.text.toString())
                        }
                    }
                }
            }


            //输入框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.mit_in_pack_list_input_edit_text)
                } else {
                    holder.inputContentPre.setBackgroundResource(R.drawable.accident_visa_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(accidentVisaInfoItemModel: AccidentVisaInfoItemModel) {
        collectList.add(accidentVisaInfoItemModel)
        notifyDataSetChanged()
    }
}