package com.yidianling.im.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.utils.Utils
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.im.R
import com.yidianling.im.api.bean.IMExpertBuild
import com.yidianling.im.helper.IMChatUtil
import com.yidianling.im.router.ImIn
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.ServiceImpl.Companion.instance
import com.yidianling.uikit.custom.http.response.question.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.im_view_question_infomation.*
import kotlinx.android.synthetic.main.im_view_question_infomation.view.*
import java.util.*
import kotlin.collections.ArrayList

/**
 * 新前置信息收集
 * */
class CmsExamQuestionPaperActivity : BaseActivity() {

    private var dialog: CommonDialog? = null

    /**界面数据流adapter*/
    private lateinit var mQuestionAdapter: QuestionAdapter

    /** 界面消息数据*/
    private var mData = ArrayList<QuestionMultiItem>();

    /**用于云信聊天界面添加数据使用*/
    private var mType70RequestList = ArrayList<AnswerQuestionType70RequestBean>();

    /**题库*/
    private var mQuestionBean: QuestionsInfoBean? = null

    /***/
    private var problemContent = ""

    /**答题id*/
    private var answerQuestionId = ""

    companion object {
        private lateinit var expertInfo: IMExpertBuild
        private lateinit var toUid: String
        private var isFromQingShu: Int = 0

        @JvmStatic
        fun start(context: Context, toUid: String, expertInfo: IMExpertBuild, isFromQingShu: Int) {
            val starter = Intent(context, CmsExamQuestionPaperActivity::class.java)
            this.expertInfo = expertInfo
            this.toUid = toUid
            this.isFromQingShu = isFromQingShu
            context.startActivity(starter)
        }
    }

    override fun layoutResId(): Int {
        return R.layout.im_view_question_infomation
    }

    override fun initDataAndEvent() {
//        if (isJumpToIm()) {
//            //如果今天打过题，跳转到聊天界面
//            skipToIm()
//            return
//        }
        //初始化
        initRecycle()
        //设置view事件
        addVIewListener()
        //-------------请求数据----------------
        preExamQuestionPaper()
        createExams()
    }

    private fun initRecycle() {
        val linearLayoutManager = LinearLayoutManager(mContext, RecyclerView.VERTICAL, false)
        recycle.layoutManager = linearLayoutManager

        mQuestionAdapter = QuestionAdapter(mData)
        recycle.adapter = mQuestionAdapter


        mQuestionAdapter.setOneCheckListener(object : QuestionOneCheckListener {
            override fun itemClick(list: List<OptionsBean>?, question: QuestionsBean) {
                itemClick(list, question)
            }

            override fun moreDefineItemClick(list: List<OptionsBean>?, question: QuestionsBean) {
                moreDefineItemClick(list, question)
            }

            override fun showOtherEdit(list: List<OptionsBean?>?, question: QuestionsBean) {
                //显示输入框
                cl_input.visibility = LinearLayout.VISIBLE
                tv_problem.visibility = LinearLayout.VISIBLE
                hsv_problem_tips.visibility = LinearLayout.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)
            }

            override fun hideOtherEdit() {
                //隐藏其他软键盘
                et_input_problem.setText("")
                hideInputMethod(et_input_problem)
            }

        })

        mQuestionAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.tv_notes) {
                //如何描述点击事件 ，展开后滑动到列表底部
                mQuestionAdapter.data[position].type5Open = true
                mQuestionAdapter.notifyDataSetChanged()
                recycle.smoothScrollToPosition(mQuestionAdapter.data.size)
            }
        }

        recycle.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING && mData.size > 0) {
                    //监听滑动   如果是
                    for ((index, item) in mData.withIndex()) {
                        if (item.viewType == 5 && item.type5Open) {
                            mQuestionAdapter.data[index].type5Open = false
                            mQuestionAdapter.notifyItemChanged(index)
                        }
                    }
                }
            }
        })
    }

    private fun moreDefineItemClick(
        list: List<OptionsBean>?,
        question: QuestionsBean
    ) {
        //多选确定
        var anwserStr = ""
        list?.forEach {
            if (anwserStr.isNotEmpty()) {
                anwserStr = anwserStr + "、" + it?.name
            } else {
                anwserStr += it?.name
            }
        }
        //创建回答消息
        val bean = list?.get(0)
        val questionMultiItem = QuestionMultiItem()
        questionMultiItem.type2Text = anwserStr
        questionMultiItem.viewType = 2
        mData.add(questionMultiItem)
        mQuestionAdapter.notifyDataSetChanged()

        //回答问题
        list?.let { anserOneChek(question, it, "") }

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

        //使用下一题nextQuestionId 取到题
        val questionsBean = mQuestionBean!!.questionPaper.questions[nextQuestionId]
        if (questionsBean != null) {
            //还有下一题
            questionMultiItem2.questionsBean = questionsBean
            if ("radio" == questionsBean.type) {
                questionMultiItem2.viewType = 3
            } else {
                questionMultiItem2.viewType = 4
                questionMultiItem2.type4CanClick = true
            }
            mData.add(questionMultiItem2)
        } else {
            //没有下一题了,展示描述=题
            for ((index, item) in mData.withIndex()) {
                mData[index].type4CanClick = false
            }
            val questionMultiItem5 = QuestionMultiItem()
            questionMultiItem5.type5Bean = mQuestionBean!!.questions[1]
            questionMultiItem5.viewType = 5
            mData.add(questionMultiItem5)

            //显示输入框
            cl_input.visibility = LinearLayout.VISIBLE
            tv_problem.visibility = LinearLayout.GONE
            hsv_problem_tips.visibility = LinearLayout.VISIBLE
            et_input_problem.hint = "请简单描述遇到的问题……\n\n\n"
            // 打开软件盘
            showInputMethod(et_input_problem)
            // 滚动到底部
            Handler().postDelayed({
                recycle.scrollToPosition(mData.size - 1)
            }, 500L)

        }

        mQuestionAdapter.notifyDataSetChanged()
        recycle.scrollToPosition(mData.size - 1)
    }

    private fun itemClick(
        list: List<OptionsBean>?,
        question: QuestionsBean
    ) {
        var anwserStr = ""
        list?.forEach {
            if (anwserStr.isNotEmpty()) {
                anwserStr = anwserStr + "、" + it?.name
            } else {
                anwserStr += it?.name
            }
        }
        //发送回答问题信息
        val questionMultiItem = QuestionMultiItem()
        questionMultiItem.type2Text = anwserStr
        questionMultiItem.viewType = 2
        mData.add(questionMultiItem)
        mQuestionAdapter.notifyDataSetChanged()

        //回答问题
        list?.let { anserOneChek(question, it, "") }

        recycle.scrollToPosition(mData.size - 1)
        val questionMultiItem2 = QuestionMultiItem()
        // 使用问题questionId  去questionChains取到选项配置
        val options = mQuestionBean!!.questionPaper.questionChains[question.id]?.options
        //从配置里找到下一题id
        val nextQuestionId = options?.get(list?.get(0)?.id)

        //使用下一题nextQuestionId 取到题
        val questionsBean = mQuestionBean!!.questionPaper.questions[nextQuestionId]
        if (questionsBean != null) {
            //还有下一题
            questionMultiItem2.questionsBean = questionsBean
            if ("radio" == questionsBean?.type) {
                questionMultiItem2.viewType = 3
            } else {
                questionMultiItem2.viewType = 4
                questionMultiItem2.type4CanClick = true
            }
            mData.add(questionMultiItem2)
        } else {
            //没有下一题了,展示描述=题
            for ((index, item) in mData.withIndex()) {
                mData[index].type4CanClick = false
            }
            val questionMultiItem5 = QuestionMultiItem()
            questionMultiItem5.type5Bean = mQuestionBean!!.questions[1]
            questionMultiItem5.viewType = 5
            mData.add(questionMultiItem5)

            //显示输入框
            cl_input.visibility = LinearLayout.VISIBLE
            tv_problem.visibility = LinearLayout.GONE
            hsv_problem_tips.visibility = LinearLayout.VISIBLE
            et_input_problem.hint = "请简单描述遇到的问题……\n\n\n"
            // 打开软件盘
            showInputMethod(et_input_problem)
            // 滚动到底部
            Handler().postDelayed({
                recycle.scrollToPosition(mData.size - 1)
            }, 500L)
        }

        mQuestionAdapter.notifyDataSetChanged()
        recycle.scrollToPosition(mData.size - 1)
    }

    /**
     * 回答单选问题
     * @param question 问题
     * @param list  选中回答的选项list
     * @param otherInput  其他输入的内容
     * */
    @SuppressLint("CheckResult")
    private fun anserOneChek(
        question: QuestionsBean,
        list: List<OptionsBean>,
        otherInput: String
    ) {
        val answerQuestionRequestBean = AnswerQuestionRequestBean()
        answerQuestionRequestBean.examId = answerQuestionId
        answerQuestionRequestBean.questionId = question.id
        answerQuestionRequestBean.questionPaperId = question.questionPaperId
        answerQuestionRequestBean.uid = ImIn.getUserInfo()?.uid

        var answersBeanList = ArrayList<AnswersBean>()
        for (optionsBean in list) {
            var answersBean = AnswersBean()
            answersBean.name = optionsBean.name
            answersBean.optionId = optionsBean.id

            answersBean.relates = optionsBean.relates
            if ("其他" == optionsBean.name && otherInput.isNotEmpty()) {
                answersBean.other = otherInput
            }
            answersBeanList.add(answersBean)
        }
        answerQuestionRequestBean.answers = answersBeanList

        val type70RequestBean = AnswerQuestionType70RequestBean()
        type70RequestBean.data = answerQuestionRequestBean
        //添加回答数据到
        mType70RequestList.add(type70RequestBean)

        instance.answerQuestion(answerQuestionId, JSON.toJSONString(answerQuestionRequestBean))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe()
    }

    /**
     * 获取试题
     * */
    @SuppressLint("CheckResult")
    fun preExamQuestionPaper() {
        instance.preExamQuestionPaper()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                if (resp.data != null) {
                    mQuestionBean = resp.data
                    //设置数据，清空list数据
                    mData.clear()
                    //取到问候语
                    getFirstQuestion(resp.data)
                    //取出第二条消息
                    setSecondQuestion()
                } else {
                    //无答题数据，跳转到聊天界面
                    IMChatUtil.startChatSessionByCms(
                        toUid, expertInfo, isFromQingShu, this@CmsExamQuestionPaperActivity
                    )
                }
            }, {
                //接口请求报错，跳转到聊天页面
                IMChatUtil.startChatSessionByCms(
                    toUid, expertInfo, isFromQingShu, this@CmsExamQuestionPaperActivity
                )
            })
    }

    @SuppressLint("CheckResult")
    private fun createExams() {
        val createExamsRequestBean =
            CreateExamsRequestBean()
        createExamsRequestBean.name = mQuestionBean?.questionPaper?.name
        createExamsRequestBean.questionPaperId = mQuestionBean?.questionPaper?.id
        createExamsRequestBean.type = "first_entry_lingxi"
        createExamsRequestBean.uid = ImIn.getUserInfo()?.uid

        instance.createEexams(JSON.toJSONString(createExamsRequestBean))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                if (resp.data != null) {
                    answerQuestionId = resp.data
                } else {
                    //未获取到答题id跳转到聊天页面
                    skipToIm()
                }
            }, {
                //获取到答题id错误，跳转到聊天页面
                skipToIm()
            })
    }

    /***取到问候语*/
    private fun getFirstQuestion(questionInfo: QuestionsInfoBean) {
        val questionMultiItem = QuestionMultiItem()
        questionMultiItem.type1Text = questionInfo.questions[0].question
        questionMultiItem.viewType = 1
        mData.add(questionMultiItem)
        mQuestionAdapter.notifyDataSetChanged()
    }

    /***问候语之后第一道题*/
    private fun setSecondQuestion() {
        val questionMultiItem2 = QuestionMultiItem()
        mQuestionBean!!.questionPaper.questionChains.forEach { (k, v) ->
            if (v.head) {
                // 代表第一题 ,使用questionId  去questions取到对应的提
                val questionsBean = mQuestionBean!!.questionPaper.questions[v.questionId]
                questionMultiItem2.questionsBean = questionsBean
                if ("radio" == questionsBean?.type) {
                    questionMultiItem2.viewType = 3
                } else {
                    questionMultiItem2.viewType = 4
                    questionMultiItem2.type4CanClick = true
                }
                mData.add(questionMultiItem2)
                mQuestionAdapter.notifyDataSetChanged()

                return@forEach
            }
        }
    }

    /**添加view事件*/
    private fun addVIewListener() {
        tv_skip.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            showSkipDialog()
        }

        tv_send.setOnClickListener {
            et_input_problem.setText("")
            hideInputMethod(et_input_problem)
            //隐藏输入框
            cl_input.visibility = LinearLayout.GONE
        }
        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 >= 3 && 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 = LinearLayout.GONE
                            et_input_problem.setText("")
                        } else {
                            tv_send.visibility = LinearLayout.VISIBLE
                        }
                    } else {
                        tv_send.visibility = LinearLayout.VISIBLE
                    }
                } else {
                    tv_send.visibility = LinearLayout.GONE
                }
            }

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

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

        recycle.setOnTouchListener { _: View?, event: MotionEvent ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    // 手势按下空白处的时候检测软件盘是否弹出
                    if (isShouldHideInput(et_input_problem, event)) {
                        hideInputMethod(et_input_problem)
                    }
                    true
                }
                MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                    false
                }
                else -> {
                    false
                }
            }
        }
    }

    /***
     * 判断今天是否展示过
     * */
    private fun isJumpToIm(): Boolean {
        val time =
            Calendar.getInstance()[Calendar.YEAR].toString() + "-" + Calendar.getInstance()[Calendar.MONTH] + Calendar.getInstance()[Calendar.DAY_OF_MONTH]
        return TextUtils.equals(
            time,
            SharedPreferencesEditor.getString("skip_time_" + ImIn.getUserInfo()?.uid)
        )
    }

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

    /**
     * 跳过，直接取IM界面
     * */
    private fun skipToIm() {
        IMChatUtil.startChatSessionByCms(
            toUid, expertInfo, isFromQingShu, this@CmsExamQuestionPaperActivity
        )
        finish()
    }


    // 隐藏键盘布局
    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)
    }


    /**
     * 判断软键盘是否需要隐藏
     * @param v
     * @param event
     * @return
     */
    private fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }

}