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

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import androidx.recyclerview.widget.GridLayoutManager
import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
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.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.im.router.ImIn.getUserInfo
import com.yidianling.uikit.custom.http.response.UserQuestInfoBean
import kotlinx.android.synthetic.main.im_view_collect_user_infomation.view.*
import java.util.*
import kotlin.collections.ArrayList


/**
 * @author jiucheng
 * @描述:用户信息采集view
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/12/10
 */
@SuppressLint("ViewConstructor")
class CollectUserInformationView(
    var mContext: Context,
    var skipEvent: () -> Unit,
    var backEvent: () -> Unit,
    var sendMsgEvent: (content: String, list: List<UserQuestInfoBean>) -> Unit
) : LinearLayout(mContext) {
    private var resultInfoList = ArrayList<UserQuestInfoBean>()
    private var hasAge = false
    private var hasGender = false
    private var currentIndex = 0
    private var isNeedShowCheckAgeDialog = false
    private var year = 1994
    private var dialog: CommonDialog? = null
    private var ensureAgeDialog: CommonDialog? = null
    private var ageStr = ""
    private var genderStr = ""
    private var questionStr = ""
    private var questionStyleStr = ""

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

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


    fun setData(list: List<UserQuestInfoBean>, hasCompleteInfoList: List<UserQuestInfoBean>?) {
        resultInfoList.clear()
        resultInfoList.addAll(list)
        if (hasCompleteInfoList != null && hasCompleteInfoList.isNotEmpty()) {
            repeat(hasCompleteInfoList.size) {
                if (TextUtils.equals("age", hasCompleteInfoList[it].userInfoType)) {
                    if (!TextUtils.isEmpty(hasCompleteInfoList[it].content)) {
                        hasAge = true
                        year = try {
                            hasCompleteInfoList[it].content!!.toInt()
                        } catch (e: Exception) {
                            1994
                        }
                        ageStr = "年龄：${(Calendar.getInstance().get(Calendar.YEAR) - year)}岁"
                    }
                }
                if (TextUtils.equals("gener", hasCompleteInfoList[it].userInfoType)) {
                    if (!TextUtils.isEmpty(hasCompleteInfoList[it].content)) {
                        hasGender = true
                        genderStr = "性别：${hasCompleteInfoList[it].content}"
                    }
                }
            }
        }

        addContentView(resultInfoList[0].question!!, true)
        proceedNext(list)
    }


    private fun proceedNext(list: List<UserQuestInfoBean>) {

        tv_start.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            if (hasGender || hasAge) {
                addContentView(resultInfoList[3].question!!, true)
                currentIndex += 2
                rl_question_style.visibility = View.VISIBLE
            } else {
                addContentView(resultInfoList[1].question!!, true)
                ll_gender.visibility = View.VISIBLE
            }
            tv_start.visibility = View.GONE
        }

        //性别
        tv_gender_male.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            addContentView(tv_gender_male.text.toString(), false)
            tv_gender_male.postDelayed({
                genderStr = "性别：男"
                addContentView(resultInfoList[currentIndex].question!!, true)
                ll_gender.visibility = View.GONE
                rl_age.visibility = View.VISIBLE
            }, 300)
        }
        tv_gender_fomale.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            addContentView(tv_gender_fomale.text.toString(), false)
            tv_gender_fomale.postDelayed({
                genderStr = "性别：女"

                addContentView(resultInfoList[currentIndex].question!!, true)
                ll_gender.visibility = View.GONE
                rl_age.visibility = View.VISIBLE
            }, 300)
        }


        //年龄
        ((date_pick.getChildAt(0) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(2)
            .visibility = View.GONE
        ((date_pick.getChildAt(0) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(1)
            .visibility = View.GONE
        date_pick.init(
            year,
            Calendar.getInstance().get(Calendar.MONTH),
            Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
        ) { _, year, _, _ ->
            this.year = year
        }
        date_pick.maxDate = Calendar.getInstance().timeInMillis
        tv_age_ensure.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            ageStr = "年龄：${(Calendar.getInstance().get(Calendar.YEAR) - year)}岁"
            if ((Calendar.getInstance().get(Calendar.YEAR) - year) <= 16) {
                isNeedShowCheckAgeDialog = true
            }

            addContentView("${year}年", false)
            tv_age_ensure.postDelayed({
                addContentView(resultInfoList[currentIndex].question!!, true)
                rl_age.visibility = View.GONE
                rl_question_style.visibility = View.VISIBLE
            }, 300)
        }

        if (list.size >= 3) {
            val adapter = CollectInfoStyleAdapter(list[3].answerList!!) {
                addContentView(it, false)
                rl_question_style.postDelayed({
                    questionStyleStr = "咨询类型：${it}"

                    addContentView(
                        resultInfoList[currentIndex].question!!,
                        true,
                        resultInfoList[currentIndex].answerList!![0]
                    )
                    rl_question_style.visibility = View.GONE
                    ll_input.visibility = View.VISIBLE

                    rl_question_style.postDelayed({ showInputMethod(et_input) }, 100)

                    scrollView.postDelayed({

                        scrollView.fullScroll(ScrollView.FOCUS_DOWN)
                    }, 300)
                }, 300)
            }
            val layoutManager =
                GridLayoutManager(mContext, 3)
            rl_question_style.layoutManager = layoutManager
            rl_question_style.adapter = adapter
        } else {
            rl_question_style.visibility = View.GONE
        }

        tv_send.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            val content = et_input.text.trim().toString()
            if (TextUtils.isEmpty(content)) {
                ToastUtil.toastShort("请输入内容")
            } else {
                questionStr = "问题描述：${content}"
                addContentView(content, false)
                tv_send.postDelayed({
                    addContentView(resultInfoList[currentIndex].question!!, true)
                    ll_input.visibility = View.GONE
                    tv_finish.visibility = View.VISIBLE
                    hideInputMethod(et_input)
                }, 300)
            }
        }

        tv_finish.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            val resultContent =
                ageStr + "\n" + genderStr + "\n" + questionStyleStr + "\n" + questionStr

            val genderBean =
                UserQuestInfoBean(list[1].userInfoType, "", ArrayList(), genderStr.split("：")[1])
            val ageBean = UserQuestInfoBean(list[2].userInfoType, "", ArrayList(), "$year")
            val questionStyleBean = UserQuestInfoBean(
                list[3].userInfoType,
                "",
                ArrayList(),
                questionStyleStr.split("：")[1]
            )
            val questionBean =
                UserQuestInfoBean(list[4].userInfoType, "", ArrayList(), questionStr.split("：")[1])

            val resultList = ArrayList<UserQuestInfoBean>()
            if (!hasGender) {
                resultList.add(genderBean)
            }
            if (!hasAge) {
                resultList.add(ageBean)
            }
            resultList.add(questionStyleBean)
            resultList.add(questionBean)


            if (isNeedShowCheckAgeDialog) {
                showCheckAgeEnsure(resultContent, resultList)
            } else {
                sendMsgEvent(resultContent, resultList)
            }
        }
    }


    @SuppressLint("RtlHardcoded")
    private fun addContentView(title: String, send: Boolean, subtitle: String = "") {
        val textView = TextView(mContext)
        val params =
            LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        params.topMargin = RxImageTool.dp2px(18f)
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f)
        textView.setTextColor(Color.parseColor("#242424"))
        textView.setPadding(
            RxImageTool.dp2px(13f),
            RxImageTool.dp2px(9f),
            RxImageTool.dp2px(13f),
            RxImageTool.dp2px(9f)
        )
        if (send) {
            textView.setBackgroundResource(R.drawable.im_background_collect_info_left)
            params.gravity = Gravity.LEFT
        } else {
            textView.setBackgroundResource(R.drawable.im_background_collect_info_right)
            params.gravity = Gravity.RIGHT
        }
        if (!TextUtils.isEmpty(subtitle)) {
            val resultText = "$title\n参考：\n$subtitle"
            val sbString = SpannableString(resultText)
            sbString.setSpan(
                ForegroundColorSpan(Color.parseColor("#999999")),
                title.length + 3,
                resultText.length,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            sbString.setSpan(
                AbsoluteSizeSpan(12, true),
                title.length,
                resultText.length,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            textView.text = sbString
            textView.setLineSpacing(4f, 1f)
        } else {
            textView.text = title
        }

        textView.maxWidth = RxImageTool.dp2px(255f)
        textView.layoutParams = params
        ll_content.addView(textView)
        if (send) {
            currentIndex++
        }
    }

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

    private fun showCheckAgeEnsure(content: String, list: List<UserQuestInfoBean>) {
        if (ensureAgeDialog == null) {
            ensureAgeDialog = CommonDialog.create(mContext)
                .setLeftOnclick("返回") {
                    backEvent()
                    ensureAgeDialog!!.dismiss()
                    ActionCountUtils.count("under_age_alert_page|under_age_alert_return_click")
                }
                .setRightClick("继续") {
                    SharedPreferencesEditor.putString(
                        "chat_age_ensure_${getUserInfo()!!.uid}",
                        "ensure"
                    )
                    sendMsgEvent(content, list)
                    ensureAgeDialog!!.dismiss()
                    ActionCountUtils.count("under_age_alert_page|under_age_alert_continue_clcik")
                }
                .setMessage("由于您未满16周岁，如需咨询需要在家长陪同下进行")
                .setTitle_color(R.color.im_color_242424)
                .setCancelAble(false)
        }
        if (!ensureAgeDialog!!.isShowing) {
            ensureAgeDialog!!.show()
            ActionCountUtils.count("under_age_alert_page|under_age_alert_page_visit")
        }
    }

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

}