package com.yidianling.im.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
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.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.im.api.bean.IMExpertBuild
import com.yidianling.im.helper.IMChatUtil
import com.yidianling.im.http.ImRetrofitApi
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 var toUid: String? = null
        private var isFromQingShu: Int = 0

        private var location: Int = 0
        private var ffrom2: String? = null

        /**单选类型*/
        private const val RADIO_KEY = "radio"

        @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)
            val activity = context as Activity
            activity.overridePendingTransition(
                R.anim.platform_activity_anim_in,
                R.anim.platform_activity_anim_in
            )
        }

        @JvmStatic
        fun start(context: Context, location: Int, ffrom2: String?) {
            val starter = Intent(context, CmsExamQuestionPaperActivity::class.java)
            this.location = location
            this.ffrom2 = ffrom2
            context.startActivity(starter)
        }
    }

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

    override fun initDataAndEvent() {
        mType70RequestList.clear()
        mType71RequestList.clear()
        //初始化
        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) {
                var otherInput = ""
                list.forEachIndexed { index, optionsBean ->
                    if ("其他" == optionsBean.name) {
                        otherInput = et_input_problem.text.toString()
                    }
                }
                answerItemClick(list, question, otherInput)
                hideInputAndKeyboark()
            }

            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() {
                //隐藏其他软键盘
                hideInputAndKeyboark()
            }

            override fun zsItemClick(
                list: List<OptionsBean>,
                question: QuestionsBean,
                postion: Int
            ) {
                var otherInput = ""
                list.forEachIndexed { index, optionsBean ->
                    if ("其他" == optionsBean.name) {
                        otherInput = et_input_problem.text.toString()
                    }
                }
                //发送回答问题信息
                sendAnswerText(list, otherInput)
                //灵犀消息 参数创建
                addType71Request(list[0].name, list[0].id)
                makeType6(postion + 1)
            }

        })
    }


    /**添加view事件*/
    private fun addVIewListener() {
        left_back_btn.setOnClickListener {
            ActionCountUtils.count("daoyi_consult_assess_page|return_click")
            finish()
        }
        tv_skip.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            ActionCountUtils.count("daoyi_consult_assess_page|skip_click")
            showSkipDialog()
        }
        tv_finish.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            ActionCountUtils.count("daoyi_consult_assess_page|go_communication_click")
            skipToIm()
        }
        //发送按钮
        tv_send.setOnClickListener {
            if (noMore) {
                //最后一题 点击发送
                lastAnswerSend()

            } else {
                //答题过程中点击 其他的弹窗
                otherQuestionsBean?.let { it1 ->
                    answerItemClick(
                        otherOptionsList,
                        it1, et_input_problem.text.toString()
                    )
                }
            }
            hideInputAndKeyboark()
        }
        //当前问题
        tv_cur_problem.setOnClickListener {
            problemContent = et_input_problem.text.toString()
            if (!TextUtils.isEmpty(problemContent)) {
                problemContent = "$problemContent\n\n"
            }
            et_input_problem.setText("$problemContent${tv_cur_problem.text}：")
            et_input_problem.setSelection(et_input_problem.text.toString().length)
            recycle.smoothScrollToPosition(mData.size - 1)
        }
        //持续时间
        tv_duration.setOnClickListener {
            problemContent = et_input_problem.text.toString()
            if (!TextUtils.isEmpty(problemContent)) {
                problemContent = "$problemContent\n\n"
            }
            et_input_problem.setText("$problemContent${tv_duration.text}：")
            et_input_problem.setSelection(et_input_problem.text.toString().length)
            recycle.smoothScrollToPosition(mData.size - 1)
        }
        //问题影响
        tv_problem_impact.setOnClickListener {
            problemContent = et_input_problem.text.toString()
            if (!TextUtils.isEmpty(problemContent)) {
                problemContent = "$problemContent\n\n"
            }
            et_input_problem.setText("$problemContent${tv_problem_impact.text}：")
            et_input_problem.setSelection(et_input_problem.text.toString().length)
            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)) {
                            et_input_problem.setText("")
                        }
                    }
                }
            }

        })
        // 监听键盘状态
        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 lastAnswerSend() {
        lastAnswer = et_input_problem.text.toString()

        if (mType71RequestList.size > 0) {
            addType71Request(
                et_input_problem.text.toString(),
                mType71RequestList[0].data.cateId
            )
        } else {
            addType71Request(et_input_problem.text.toString(), "")
        }
        //最后一题答玩展示立即前往按钮，隐藏跳过按钮
        tv_finish.visibility = View.VISIBLE
        tv_skip.visibility = View.GONE
        mackType2(lastAnswer, "")
        setFirstAndLatQuestion(mQuestionBean!!.questions[2].question)

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

    /**
     * 隐藏输入框
     * */
    private fun hideInputAndKeyboark() {
        et_input_problem.setText("")
        hideInputMethod(et_input_problem)
        //隐藏输入框
        cl_input.visibility = LinearLayout.GONE
    }


    /**
     * 回答问题
     * @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_KEY == questionsBean.type) {
                if (!TextUtils.isEmpty(questionsBean.image) || !TextUtils.isEmpty(questionsBean.url)) {
                    tv_skip.visibility = View.GONE
                    questionMultiItem2.viewType = 7
                } else {
                    questionMultiItem2.viewType = 3
                }
            } else {
                questionMultiItem2.viewType = 4
                questionMultiItem2.type4CanClick = true
            }
            mData.add(questionMultiItem2)
        } else {
            //没有下一题了,跳转按钮展示
            setFirstAndLatQuestion(mQuestionBean!!.questions[2].question)
            tv_finish.visibility = View.VISIBLE
            tv_skip.visibility = View.GONE
        }
        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()
                    //取到问候语
                    setFirstAndLatQuestion(mQuestionBean!!.questions[0].question)
                    //取出第二条消息
                    if (resp.data.questionPaper != null) {
                        haveLingxiQuestion = true
                        setSecondQuestionByLx()
                        createExams()
                    } else {
                        haveLingxiQuestion = false
                        makeType6(0)
                    }

                } else {
                    //无答题数据，跳转到聊天界面
                    jumpToIm()

                }
            }, {
                //接口请求报错，跳转到聊天页面
                jumpToIm()
            })
    }


    @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 setFirstAndLatQuestion(str: String) {
        val questionMultiItem = QuestionMultiItem()
        questionMultiItem.type1Text = str
        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 ("#其他" == answerStr) {
            answerStr = "其他"
        } else {
            if (!answerStr.contains("其他") || otherInput.isEmpty()) {
                answerStr = answerStr.substring(1).replace("#", "、")
            }
        }

        mackType2(answerStr.trim(), otherInput)

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

    }

    /**
     * 创建消息类型2
     *
     * @param answerStr 用户展示的文字回复
     * */
    private fun mackType2(answerStr: String, other: String) {
        val questionMultiItem = QuestionMultiItem()
        questionMultiItem.type2Text = answerStr
        questionMultiItem.type2Other = other
        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_KEY == questionsBean?.type) {
            if (!TextUtils.isEmpty(questionsBean.image) || !TextUtils.isEmpty(questionsBean.url)) {
                tv_skip.visibility = View.GONE
                questionMultiItem2.viewType = 7
            } else {
                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[1]
        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
        toUid.let {
            type70RequestBean.toUid = toUid
        }

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

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

        dataBean.answer = answer
        dataBean.cateId = optionId

        answerQuestionType71RequestBean.data = dataBean

        toUid.let {
            answerQuestionType71RequestBean.toUid = toUid
        }
        answerQuestionType71RequestBean.fromUid = ImIn.getUserInfo()?.uid
        mType71RequestList.add(answerQuestionType71RequestBean)
    }

    /**
     * 跳过填写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界面
     * */
    @SuppressLint("CheckResult")
    private fun skipToIm() {
        showProgressDialog()
        SharedPreferencesEditor.putString("skip_time_", System.currentTimeMillis().toString())

        if (toUid != null) {
            //代表是聊天列表进来的
            instance.batchSendCustomizeMessage(JSON.toJSONString(mType70RequestList))
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe()

            Handler().postDelayed({
                instance.batchSendCustomizeMessage(JSON.toJSONString(mType71RequestList))
                    .subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.io())
                    .subscribe()
            }, 100L)


            Handler().postDelayed({
                IMChatUtil.startChatSessionByCms(
                    toUid!!,
                    expertInfo,
                    isFromQingShu,
                    this@CmsExamQuestionPaperActivity
                )
            }, 200L)

            Handler().postDelayed({
                finish()
            }, 1000L)
        } else {
            //代表是导医进来的  导医进来的需要获取导医后再发送消息
            var questionPaperId = ""
            mQuestionBean?.questionPaper?.id?.let { questionPaperId = it }

            ImRetrofitApi.getImJavaApi()
                .getConsultAssistantUidRequest(location, ffrom2, answerQuestionId, questionPaperId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ uidBean ->
                    if (uidBean.code == "200" && uidBean.data != 0.toLong()) {
                        mType70RequestList.forEachIndexed { index, answerQuestionType70RequestBean ->
                            mType70RequestList[index].toUid = uidBean.data.toString()
                        }

                        instance.batchSendCustomizeMessage(JSON.toJSONString(mType70RequestList))
                            .subscribeOn(Schedulers.io())
                            .observeOn(Schedulers.io())
                            .subscribe()

                        mType71RequestList.forEachIndexed { index, answerQuestionType71RequestBean ->
                            mType71RequestList[index].toUid = uidBean.data.toString()
                        }

                        Handler().postDelayed({
                            instance.batchSendCustomizeMessage(JSON.toJSONString(mType71RequestList))
                                .subscribeOn(Schedulers.io())
                                .observeOn(Schedulers.io())
                                .subscribe()
                        }, 100L)

                        Handler().postDelayed({
                            IMChatUtil.startChat(
                                this@CmsExamQuestionPaperActivity,
                                uidBean.data.toString(),
                                0
                            )
                        }, 200L)

                        Handler().postDelayed({
                            finish()
                        }, 1000L)
                    } else {
                        dismissProgressDialog()
                        ToastUtil.toastShort("咨询助理忙碌中，请稍后再试")
                    }

                }, {
                    dismissProgressDialog()
                    ToastUtil.toastShort("咨询助理忙碌中，请稍后再试")
                })

        }
    }

    /**
     * 导医进来的跳转到咨询
     * */
    @SuppressLint("CheckResult")
    private fun jumpToIm() {
        if (toUid != null) {
            IMChatUtil.startChatSessionByCms(
                toUid!!, expertInfo, isFromQingShu, this@CmsExamQuestionPaperActivity
            )
        } else {
            ImRetrofitApi.getImJavaApi()
                .getConsultAssistantUidRequest(location, ffrom2)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ uidBean ->
                    if (uidBean.code == "200" && uidBean.data != 0.toLong()) {
                        IMChatUtil.startChat(
                            this@CmsExamQuestionPaperActivity,
                            uidBean.data.toString(),
                            0
                        )

                        finish()
                    } else {
                        ToastUtil.toastShort("咨询助理忙碌中，请稍后再试")
                        finish()
                    }

                }, {
                    ToastUtil.toastShort("咨询助理忙碌中，请稍后再试")
                    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
    }

    override fun finish() {
        super.finish()
        dismissProgressDialog()
        overridePendingTransition(
            R.anim.platform_activity_anim_in,
            R.anim.platform_activity_anim_in
        )
    }

}