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>()

    /** item 展示其他的时  的选项数据数据*/
    private var otherOptionsList = ArrayList<OptionsBean>()

    /** item 展示其他时  的选项问题  */
    private var otherQuestionsBean: QuestionsBean? = null

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

    /**主诉消息*/
    private var mType71RequestList = ArrayList<AnswerQuestionType71RequestBean>()

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

    /***/
    private var problemContent = ""

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

    /**最后一题答案*/
    private var lastAnswer = ""

    private var noMore = false
    private var haveLingxiQuestion = false

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

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

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

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

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        mType70RequestList.clear()
        mType71RequestList.clear()
    }

    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) {
                answerItemClick(list, question, "")
            }

            override fun showOtherEdit(list: List<OptionsBean>, question: QuestionsBean) {
                otherOptionsList.clear()
                otherOptionsList.addAll(list)
                otherQuestionsBean = question
                //显示输入框
                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)
            }

            override fun showKeyboard() {
                //显示输入框
                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)
            }

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

            override fun zsItemClick(answer: String, postion: Int) {
                //主诉
                addType71Request(answer)
                mackType2(answer)
                makeType6(postion + 1)

            }

        })

        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)
                        }
                    }
                }
            }
        })
    }


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

        tv_send.setOnClickListener {
            if (noMore) {
                //最后一题 点击发送
                lastAnswer = et_input_problem.text.toString()
                addType71Request(et_input_problem.text.toString())

                tv_finish.visibility = View.VISIBLE
                mackType2(lastAnswer)
                //滑动到底部
                recycle.scrollToPosition(mData.size - 1)
                mData.forEachIndexed { index, _ ->
                    mData[index].type5CanClick = false
                }

            } else {
                //答题过程中点击 其他的弹窗
                otherQuestionsBean?.let { it1 ->
                    answerItemClick(
                        otherOptionsList,
                        it1, et_input_problem.text.toString()
                    )
                }
            }

            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
                }
            }
        }
    }


    /**
     * 回答问题
     * @param otherInput  点击替他输入内容
     * */
    private fun answerItemClick(
        list: List<OptionsBean>,
        question: QuestionsBean,
        otherInput: String
    ) {

        //发送回答问题信息
        sendAnswerText(list, otherInput)

        //回答问题
        anserQuestion(question, list, otherInput)

        //获取下一题
        getNextQuestion(question, list)
        //清除其他选项的数据
        otherOptionsList.clear()
        otherQuestionsBean = null
    }


    /**
     * 获取下一题
     * @param question 回答的问题
     * @param list 回答选择的选项
     * */
    private fun getNextQuestion(
        question: QuestionsBean,
        list: List<OptionsBean>
    ) {
        //寻找下一题
        val questionMultiItem2 = QuestionMultiItem()
        // 使用问题questionId  去questionChains取到选项配置
        val options = mQuestionBean!!.questionPaper.questionChains[question.id]?.options
        //  通过选择第一个选项的id 从配置里找到下一题id
        val nextQuestionId = options?.get(list[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 {
            //没有下一题了,跳转按钮展示
            tv_finish.visibility = View.VISIBLE
        }
        mQuestionAdapter.notifyDataSetChanged()
        recycle.scrollToPosition(mData.size - 1)
    }

    /**
     * 回答单选问题
     * @param question 问题
     * @param list  选中回答的选项list
     * @param otherInput  其他输入的内容
     * */
    @SuppressLint("CheckResult")
    private fun anserQuestion(
        question: QuestionsBean,
        list: List<OptionsBean>,
        otherInput: String
    ) {
        //回答问题参数创建
        val answerQuestionRequestBean = answerQuestionRequestBean(question, list, otherInput)
        //灵犀消息 参数创建
        addType70Request(answerQuestionRequestBean)

        //请求接口 回答问题
        instance.answerQuestion(answerQuestionId, JSON.toJSONString(answerQuestionRequestBean))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe()
        //滑动到底部
        recycle.scrollToPosition(mData.size - 1)
    }

    /**
     * 获取试题
     * */
    @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()
                    //取出第二条消息
                    if (resp.data.questions.size > 0) {
                        haveLingxiQuestion = true
                        setSecondQuestionByLx()
                        createExams()
                    } else {
                        haveLingxiQuestion = false
                        makeType6(0)
                    }

                } 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() {
        val questionMultiItem = QuestionMultiItem()
        questionMultiItem.type1Text = "你好，为了更好的帮助您我们需要了解些基本信息，我们将会严格保护你的隐私安全，请放心。"
        questionMultiItem.viewType = 1
        mData.add(questionMultiItem)
        mQuestionAdapter.notifyDataSetChanged()
    }

    /***问候语之后 灵犀第一道题*/
    private fun setSecondQuestionByLx() {
        val questionMultiItem2 = QuestionMultiItem()
        mQuestionBean!!.questionPaper.questionChains.forEach { (k, v) ->
            if (v.head) {
                // 代表第一题 ,使用questionId  去questions取到对应的提
                makeType3OrType4(v, questionMultiItem2)
                return@forEach
            }
        }

    }

    /**
     * 创建回答问题  并刷新多选状态为不可选
     * @param otherInput  点击其他输入文字
     * */
    private fun sendAnswerText(list: List<OptionsBean>, otherInput: String) {
        var answerStr = ""
        list.forEach {
            answerStr = "$answerStr#${it.name}"
        }
        if (otherInput.isNotEmpty()) {
            answerStr = "$answerStr \n \n otherInput"
        }

        mackType2(answerStr)

        //刷新已回答问题，将多选设置成不可再选
        mData.forEachIndexed { index, _ ->
            mData[index].type4CanClick = false
        }

    }

    /**
     * 创建消息类型2
     *
     * @param answerStr 用户展示的文字回复
     * */
    private fun mackType2(answerStr: String) {
        val questionMultiItem = QuestionMultiItem()
        questionMultiItem.type2Text = answerStr
        questionMultiItem.viewType = 2
        mData.add(questionMultiItem)
        mQuestionAdapter.notifyDataSetChanged()
    }

    /**
     * 创建消息类型3  类型4
     * */
    private fun makeType3OrType4(
        questionChain: QuestionChainsBean,
        questionMultiItem2: QuestionMultiItem
    ) {
        val questionsBean = mQuestionBean!!.questionPaper.questions[questionChain.questionId]
        questionMultiItem2.questionsBean = questionsBean
        if ("radio" == questionsBean?.type) {
            questionMultiItem2.viewType = 3
        } else {
            questionMultiItem2.viewType = 4
            questionMultiItem2.type4CanClick = true
        }
        mData.add(questionMultiItem2)
        mQuestionAdapter.notifyDataSetChanged()
    }

    /**最后一条道题*/
    private fun makeType5() {
        val questionMultiItem5 = QuestionMultiItem()
        questionMultiItem5.type5Bean = mQuestionBean!!.questions[0]
        questionMultiItem5.viewType = 5
        mData.add(questionMultiItem5)

        //最后一提，
        noMore = true

        //显示输入框
        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)
    }

    /***
     *
     * 问候语之后 主诉题消息创建
     *
     * */
    private fun makeType6(position: Int) {
        val extraQuestions = mQuestionBean!!.extraQuestions
        if (position < extraQuestions.size) {
            // 代表第一题 ,使用questionId  去questions取到对应的提
            val questionMultiItem2 = QuestionMultiItem()
            val questionsBean = mQuestionBean!!.extraQuestions[position]

            questionMultiItem2.questionsBean = questionsBean
            questionMultiItem2.type6Position = position
            questionMultiItem2.viewType = 6
            mData.add(questionMultiItem2)
            mQuestionAdapter.notifyDataSetChanged()
        } else {
            makeType5()
        }

    }


    /**
     * 创建 回答问题参数
     * */
    private fun answerQuestionRequestBean(
        question: QuestionsBean,
        list: List<OptionsBean>,
        otherInput: String
    ): AnswerQuestionRequestBean {
        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
        return answerQuestionRequestBean
    }


    /**
     * 创建灵犀消息参数
     * */
    private fun addType70Request(answerQuestionRequestBean: AnswerQuestionRequestBean) {
        val type70RequestBean = AnswerQuestionType70RequestBean()

        type70RequestBean.data = answerQuestionRequestBean
        type70RequestBean.fromUid = ImIn.getUserInfo()?.uid
        type70RequestBean.toUid = toUid

        //添加回答数据到
        mType70RequestList.add(type70RequestBean)
    }

    /**
     * 创建主诉消息参数
     * */
    private fun addType71Request(answer: String) {
        val answerQuestionType71RequestBean = AnswerQuestionType71RequestBean()
        val dataBean = AnswerQuestionType71RequestBean.DataBean()

        dataBean.answer = answer
        answerQuestionType71RequestBean.data = dataBean
        answerQuestionType71RequestBean.toUid = toUid
        answerQuestionType71RequestBean.fromUid = ImIn.getUserInfo()?.uid
        mType71RequestList.add(answerQuestionType71RequestBean)
    }

    /***
     * 判断今天是否展示过
     * */
    private fun isJumpToIm(): Boolean {
        val time = System.currentTimeMillis()

        val skipTime = SharedPreferencesEditor.getString("skip_time_")
        if (skipTime == null || skipTime.isEmpty()) {
            return false
        }
        val timeDifference = (time - skipTime.toLong()) / 1000
        val second = 1000
        val minute = second * 60
        val hour = minute * 60
        val day = hour * 24

        return timeDifference < skip_time
    }

    /**
     * 跳过填写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() {
        SharedPreferencesEditor.putString("skip_time_", System.currentTimeMillis().toString())
        mType70RequestList.forEach {
            instance.lingxiAnswerQuestion(JSON.toJSONString(it))
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe()
        }

        mType71RequestList.forEach {
            instance.lingxiAnswerQuestion(JSON.toJSONString(it))
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe()
        }


        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
    }

}