package com.yidianling.uikit.business.session.view

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ydl.ydlcommon.utils.Utils
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxKeyboardTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.listener.SoftKeyBoardListener
import com.yidianling.uikit.business.session.view.question.QuestionAdapter
import com.yidianling.uikit.business.session.view.question.QuestionMultiItem
import com.yidianling.uikit.business.session.view.question.QuestionOneCheckListener
import com.yidianling.uikit.custom.http.response.question.OptionsBean
import com.yidianling.uikit.custom.http.response.question.QuestionsInfoBean
import kotlinx.android.synthetic.main.im_view_question_infomation.view.*
import java.util.*
import kotlin.collections.ArrayList


/**
 * @author jiucheng
 * @描述:用户信息采集view
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/12/10
 */
@SuppressLint("ViewConstructor")
class QuestionInformationView(
    var mContext: Activity,
    var skipEvent: () -> Unit,
    var backEvent: () -> Unit,
    var sendMsgEvent: (content: String, list: List<QuestionsInfoBean>) -> Unit
) : LinearLayout(mContext) {

    private var dialog: CommonDialog? = null
    private lateinit var mQuestionAdapter: QuestionAdapter
    private var mData = ArrayList<QuestionMultiItem>();
    private var mQuestionBean: QuestionsInfoBean? = null
    private var problemContent = ""

    init {
        val params = LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        layoutParams = params
        View.inflate(mContext, R.layout.im_view_question_infomation, this)
        orientation = VERTICAL

        tv_skip.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            showSkipDialog()
        }

        val linearLayoutManager = LinearLayoutManager(mContext, RecyclerView.VERTICAL, false)
        recycle.layoutManager = linearLayoutManager

        mQuestionAdapter = QuestionAdapter(mData)
        recycle.adapter = mQuestionAdapter
        mQuestionAdapter.setOneCheckListener(object : QuestionOneCheckListener {
            override fun itemClick(bean: OptionsBean?, questionId: String) {
                val questionMultiItem = QuestionMultiItem()
                questionMultiItem.type2Text = bean?.name
                questionMultiItem.viewType = 2
                mData.add(questionMultiItem)
                mQuestionAdapter.notifyDataSetChanged()

                val questionMultiItem2 = QuestionMultiItem()
                // 使用问题questionId  去questionChains取到选项配置
                val options = mQuestionBean!!.questionChains[questionId]?.options
                //从配置里找到下一题id
                val nextQuestionId = options?.get(bean?.id)

                //使用下一题nextQuestionId 取到题
                val questionsBean = mQuestionBean!!.questions[nextQuestionId]
                if (questionsBean != null) {
                    //还有下一题
                    questionMultiItem2.questionsBean = questionsBean
                    if ("radio" == questionsBean?.type) {
                        questionMultiItem2.viewType = 3
                    } else {
                        questionMultiItem2.viewType = 4
                    }
                    mData.add(questionMultiItem2)
                } else {
                    //没有下一题了
                }

                mQuestionAdapter.notifyDataSetChanged()

            }

            override fun moreDefineItemClick(list: List<OptionsBean?>?) {
                //多选确定
            }

            override fun showOtherEdit(list: List<OptionsBean?>?) {
                //显示输入框
                cl_input.visibility = VISIBLE
                tv_problem.visibility = VISIBLE
                hsv_problem_tips.visibility = GONE
                var problem = "已选："
                list?.forEach {
                    problem+="# "+it?.name
                }
                tv_problem.text = problem
                et_input_problem.hint="请输入其他事件......"
                // 打开软件盘
                showInputMethod(et_input_problem)
                // 滚动到底部
                Handler().postDelayed({
                    recycle.scrollToPosition(mData.size - 1)
                }, 500L)
            }

        })
    }


    @RequiresApi(Build.VERSION_CODES.N)
    fun setData(questionInfo: QuestionsInfoBean) {
        mQuestionBean = questionInfo
        mData.clear()
        val questionMultiItem = QuestionMultiItem()
        questionMultiItem.type1Text = questionInfo.name
        questionMultiItem.viewType = 1
        mData.add(questionMultiItem)

        val questionMultiItem2 = QuestionMultiItem()
        mQuestionBean!!.questionChains.forEach { (k, v) ->
            if (v.head) {
                // 代表第一题 ,使用questionId  去questions取到对应的提
                val questionsBean = mQuestionBean!!.questions[v.questionId]
                questionMultiItem2.questionsBean = questionsBean
                if ("radio" == questionsBean?.type) {
                    questionMultiItem2.viewType = 3
                } else {
                    questionMultiItem2.viewType = 4
                }
                mData.add(questionMultiItem2)
                return@forEach
            }
        }
        tv_send.setOnClickListener {
            et_input_problem.setText("")
            hideInputMethod(et_input_problem)
        }
        tv_cur_problem.setOnClickListener {
            problemContent = et_input_problem.text.toString()
            et_input_problem.setText("$problemContent${tv_cur_problem.text}：\n")
            et_input_problem.setSelection(et_input_problem.text.toString().length - 1)
            recycle.smoothScrollToPosition(mData.size - 1)
        }
        tv_duration.setOnClickListener {
            problemContent = et_input_problem.text.toString()
            et_input_problem.setText("$problemContent\n${tv_duration.text}：\n")
            et_input_problem.setSelection(et_input_problem.text.toString().length - 1)
            recycle.smoothScrollToPosition(mData.size - 1)
        }
        tv_problem_impact.setOnClickListener {
            problemContent = et_input_problem.text.toString()
            et_input_problem.setText("$problemContent\n${tv_problem_impact.text}：\n")
            et_input_problem.setSelection(et_input_problem.text.toString().length - 1)
            recycle.smoothScrollToPosition(mData.size - 1)
        }
        et_input_problem.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                // 动态监听输入行数大于等于4行，滚动列表到底部
                if (et_input_problem.lineCount >= 4 && recycle.canScrollVertically(1)) {
                    recycle.smoothScrollToPosition(mData.size - 1)
                }
            }

            override fun beforeTextChanged(p0: CharSequence, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(char: CharSequence, p1: Int, p2: Int, p3: Int) {
                if (char.isNotEmpty()) {
                    if (char.contains("\n")) {
                        val s = char.toString().replace("\n", "")
                        if (TextUtils.isEmpty(s)) {
                            tv_send.visibility = View.GONE
                            et_input_problem.setText("")
                        } else {
                            tv_send.visibility = View.VISIBLE
                        }
                    } else {
                        tv_send.visibility = View.VISIBLE
                    }
                } else {
                    tv_send.visibility = View.GONE
                }
            }

        })
        // 监听键盘状态
        SoftKeyBoardListener.setListener(mContext,
            object : SoftKeyBoardListener.OnSoftKeyBoardChangeListener {
                override fun keyBoardShow(height: Int) {
                    recycle.smoothScrollToPosition(mData.size - 1)
                }

                override fun keyBoardHide(height: Int) {
                }
            })
    }


    // 隐藏键盘布局
    private fun hideInputMethod(et: EditText) {
        val imm = mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(et.windowToken, 0)
        et.clearFocus()
    }

    // 显示键盘布局
    private fun showInputMethod(editTextMessage: EditText) {
        editTextMessage.requestFocus()
        val imm = mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editTextMessage, 0)
    }


    fun showSkipDialog() {
        if (dialog == null) {
            dialog = CommonDialog.create(mContext)
                .setLeftOnclick("下次吧") {
                    skipEvent()
                }
                .setRightClick("继续填写") {
                    dialog!!.dismiss()
                }
                .setMessage("这个过程可以帮助您更快地改变当前的现状，确定要跳过吗？")
                .setTitle_color(R.color.im_color_242424)
                .setCancelAble(true)
        }
        if (!dialog!!.isShowing) {
            dialog!!.show()
        }
    }
}