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

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.support.v7.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.view.dialog.CommonDialog
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
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 sendMsgEvent: (content: String, list: List<UserQuestInfoBean>) -> Unit) : LinearLayout(mContext) {
    private var resultInfoList = ArrayList<UserQuestInfoBean>()
    private var currentIndex = 0
    private var year =1994
    //todo CommonDialog的样式要改
    private var dialog: 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 {
            showSkipDialog()
        }
    }


    fun setData(list: List<UserQuestInfoBean>) {
        resultInfoList.clear()
        resultInfoList.addAll(list)
        addContentView(resultInfoList[0].question!!, true)
        proceedNext(list)
    }


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

        tv_start.setOnClickListener {
            addContentView(resultInfoList[1].question!!, true)

            tv_start.visibility = View.GONE
            ll_gender.visibility = View.VISIBLE
        }


        tv_gender_male.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 {
            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 {
            ageStr = "年龄：${(Calendar.getInstance().get(Calendar.YEAR) - year)}岁"

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


        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


        tv_send.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 {
            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>()
            resultList.add(genderBean)
            resultList.add(ageBean)
            resultList.add(questionStyleBean)
            resultList.add(questionBean)

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

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

}