package cn.yyxx.eyuangame.core.impl.center.fragment

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import cn.yyxx.eyuangame.base.utils.Logger
import cn.yyxx.eyuangame.core.entity.ClickType
import cn.yyxx.eyuangame.core.entity.ResultInfo
import cn.yyxx.eyuangame.core.entity.SdkBackLoginInfo
import cn.yyxx.eyuangame.core.impl.SdkBridgeImpl
import cn.yyxx.eyuangame.core.impl.center.MemberActivity
import cn.yyxx.eyuangame.core.internal.IRequestCallback
import cn.yyxx.eyuangame.core.network.SdkRequest
import cn.yyxx.eyuangame.core.ui.EventEditText
import cn.yyxx.eyuangame.core.utils.EditTextUtils
import cn.yyxx.eyuangame.core.utils.TimeDownUtils
import cn.yyxx.support.ResUtils
import cn.yyxx.support.hawkeye.ToastUtils
import org.json.JSONObject

/**
 * @author #Suyghur.
 * Created on 2021/06/30
 */
class BindPhoneFragment : Fragment(), View.OnClickListener {

    private lateinit var mView: View
    private lateinit var memberImpl: MemberActivity

    private lateinit var llGroup1: LinearLayout
    private lateinit var llGroup2: LinearLayout
    private lateinit var clTips: ConstraintLayout

    private lateinit var ivReturn: ImageView
    private lateinit var eetPhone: EventEditText
    private lateinit var eetCaptcha: EventEditText
    private lateinit var btnCaptCha: Button
    private lateinit var btnConfirm: Button
    private lateinit var tvArea: TextView
    private lateinit var ivArrow: ImageView
    private lateinit var tvBindTips: TextView

    private lateinit var rlAreaList: RelativeLayout
    private lateinit var llAreaList: LinearLayout
    private lateinit var svAreaList: ScrollView

    private val areaCodeList = mutableListOf<String>()

    private var imgUp = 0
    private var imgDown = 0

    private var code = ""

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            if (msg.what == 101) {
                changeTimeView(msg.obj as Int)
            }
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        memberImpl = requireActivity() as MemberActivity
        mView = layoutInflater.inflate(ResUtils.getResId(requireActivity(), "yyxx_member_bind_phone", "layout"), container, false)
        initView(mView)
        return mView
    }

    private fun initView(view: View) {

        imgUp = ResUtils.getResId(context, "yyxx_pack_up_white_img", "drawable")
        imgDown = ResUtils.getResId(context, "yyxx_pack_down_white_img", "drawable")

        ivReturn = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_iv_return", "id"))
        ivReturn.apply {
            tag = ClickType.ACTION_RETURN
            setOnClickListener(this@BindPhoneFragment)
        }

        llGroup1 = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_ll_group1", "id"))
        llGroup2 = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_ll_group2", "id"))
        clTips = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_cl_tips", "id"))

        eetPhone = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_eet_phone", "id"))
        eetPhone.editText.hint = ResUtils.getResString(requireActivity(), "yyxx_hint_forget_phone")

        eetCaptcha = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_eet_captcha", "id"))
        eetCaptcha.editText.hint = ResUtils.getResString(requireActivity(), "yyxx_hint_bind_phone_captcha")

        btnCaptCha = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_btn_captcha", "id"))
        btnCaptCha.apply {
            tag = ClickType.ACTION_GET_CAPTCHA
            setOnClickListener(this@BindPhoneFragment)
        }

        btnConfirm = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_btn_confirm", "id"))
        btnConfirm.apply {
            tag = ClickType.ACTION_CONFIRM
            setOnClickListener(this@BindPhoneFragment)
        }

        rlAreaList = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_rl_area_list", "id"))
        rlAreaList.visibility = View.GONE
        llAreaList = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_ll_area_list", "id"))
        svAreaList = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_sv_area_list", "id"))


        tvArea = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_tv_area", "id"))
        ivArrow = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_iv_arrow", "id"))
        ivArrow.setOnClickListener {
            changeAreaList()
        }

        autoFillAreaList(requireActivity())

        tvBindTips = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_tv_tips2", "id"))
        val tipsPhone = if (SdkBackLoginInfo.instance.phoneNum.length > 6) {
            val head = SdkBackLoginInfo.instance.phoneNum.substring(0, 3)
            val foot = SdkBackLoginInfo.instance.phoneNum.substring(SdkBackLoginInfo.instance.phoneNum.length - 3, SdkBackLoginInfo.instance.phoneNum.length)
            "${head}xxxx${foot}"
        } else {
            SdkBackLoginInfo.instance.phoneNum
        }
        tvBindTips.text = "${ResUtils.getResString(requireActivity(), "yyxx_iv_bind_phone_tips2")}$tipsPhone"
    }

    private fun autoFillAreaList(context: Context) {
        if (SdkBridgeImpl.initBean.areaCodeList.isNullOrEmpty()) {
            //默认4个地区
            areaCodeList.add("86")
            //香港
            areaCodeList.add("852")
            //澳门
            areaCodeList.add("853")
            //台湾
            areaCodeList.add("886")
        } else {
            SdkBridgeImpl.initBean.areaCodeList.forEach {
                areaCodeList.add(it)
            }
        }
        initAreaList(context)
    }

    private fun initAreaList(context: Context) {
        llAreaList.removeAllViews()
        //单行高
        var height = 100
        tvArea.apply {
            height = if (layoutParams != null) {
                layoutParams!!.height
            } else {
                100
            }
        }
        //ScrollView高度
        var maxHeight = 0
        areaCodeList.apply {
            maxHeight = if (size < 2) {
                size * height
            } else {
                2 * height
            }
        }
        //循环添加列
        areaCodeList.apply {
            for (i in indices) {
                val areaCode = this[i]
                //添加线
                val line = View(context)
                line.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 2)
                line.setBackgroundColor(Color.parseColor("#E6FFFFFF"))
                llAreaList.apply {
                    if (childCount > 0) {
                        addView(line)
                    }
                }
                //添加区号
                val item = LayoutInflater.from(context).inflate(ResUtils.getResId(context, "yyxx_area_list_item", "layout"), null)
                item?.apply {
                    val tvAreaCode = findViewById<TextView>(ResUtils.getResId(context, "yyxx_tv_area", "id"))
                    tvAreaCode.gravity = Gravity.CENTER
                    tvAreaCode.text = areaCode
                    setOnClickListener(OnItemClick(areaCode))
                    layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height)
                    llAreaList.addView(this, llAreaList.childCount)
                }
            }
        }
        svAreaList.layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, maxHeight)
    }


    private fun changeAreaList() {
        if (rlAreaList.visibility == View.GONE) {
            ivArrow.setBackgroundResource(imgUp)
            rlAreaList.visibility = View.VISIBLE
        } else {
            ivArrow.setBackgroundResource(imgDown)
            rlAreaList.visibility = View.GONE
        }
    }

    private fun callGetCaptcha() {
        val areaCode = code
        Logger.d("$areaCode ...")
        val phoneNum = eetPhone.editText.text.trim().toString()

        if (TextUtils.isEmpty(areaCode) || areaCode == ResUtils.getResString(requireActivity(), "yyxx_tv_area_code")) {
            ToastUtils.toastInfo(requireActivity(), ResUtils.getResString(requireActivity(), "yyxx_tips_area_code_format_error"))
            return
        }

        if (!EditTextUtils.filterPwd(phoneNum)) {
            ToastUtils.toastInfo(requireActivity(), ResUtils.getResString(requireActivity(), "yyxx_tips_phone_format_error"))
            return
        }

        try {
            with(JSONObject()) {
                put("sms_type", "bind_phone")
                put("area_code", areaCode)
                put("phone_number", phoneNum)
                SdkRequest.instance.getCaptcha(requireActivity(), this, object : IRequestCallback {
                    override fun onResponse(resultInfo: ResultInfo) {
                        if (resultInfo.code == 1) {
                            ToastUtils.toastInfo(requireActivity(), resultInfo.msg)
                            changeTimeNum()
                        } else {
                            ToastUtils.toastInfo(requireActivity(), resultInfo.msg)
                        }
                    }
                })
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun callBindPhone() {
        val phoneNum = eetPhone.editText.text.trim().toString()
        val captcha = eetCaptcha.editText.text.trim().toString()

        if (TextUtils.isEmpty(captcha)) {
            ToastUtils.toastInfo(requireActivity(), ResUtils.getResString(requireActivity(), "yyxx_tips_captcha_format_error"))
            return
        }
        if (!EditTextUtils.filterPhone(phoneNum)) {
            ToastUtils.toastInfo(requireActivity(), ResUtils.getResString(requireActivity(), "yyxx_tips_phone_format_error"))
            return
        }

        try {
            with(JSONObject()) {
                put("uid", SdkBackLoginInfo.instance.userId)
                put("phone_number", phoneNum)
                put("sms_code", captcha)
                SdkRequest.instance.bindPhone(requireActivity(), this, object : IRequestCallback {
                    override fun onResponse(resultInfo: ResultInfo) {
                        if (resultInfo.code == 1) {
                            SdkBackLoginInfo.instance.phoneNum = phoneNum
                            ToastUtils.toastInfo(requireActivity(), resultInfo.msg)
                            requireActivity().onBackPressed()
                        } else {
                            ToastUtils.toastInfo(requireActivity(), resultInfo.msg)
                        }
                    }
                })
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun changeTimeView(time: Int) {
        btnCaptCha.apply {
            text = if (time <= 0) {
                this.isEnabled = true
                ResUtils.getResString(requireActivity(), "yyxx_tv_get_captcha")
            } else {
                this.isEnabled = false
                "${time}s"
            }
        }
    }

    private fun changeTimeNum() {
        if (!TimeDownUtils.isRunning) {
            TimeDownUtils.start(60, object : TimeDownUtils.TimeCallback {
                override fun onTime(time: Int) {
                    val msg = Message.obtain()
                    msg.what = 101
                    msg.obj = time
                    handler.sendMessage(msg)
                }
            })
        } else {
            TimeDownUtils.resetCallback(object : TimeDownUtils.TimeCallback {
                override fun onTime(time: Int) {
                    val msg = Message.obtain()
                    msg.what = 101
                    msg.obj = time
                    handler.sendMessage(msg)
                }
            })
        }
    }

    private fun showOrHideTips() {
        if (TextUtils.isEmpty(SdkBackLoginInfo.instance.phoneNum)) {
            llGroup1.visibility = View.VISIBLE
            llGroup2.visibility = View.VISIBLE
            clTips.visibility = View.GONE
            btnConfirm.visibility = View.VISIBLE
        } else {
            llGroup1.visibility = View.GONE
            llGroup2.visibility = View.GONE
            clTips.visibility = View.VISIBLE
            btnConfirm.visibility = View.GONE
        }
    }

    override fun onResume() {
        super.onResume()
        showOrHideTips()
    }

    override fun onDestroy() {
        super.onDestroy()
        areaCodeList.clear()
        rlAreaList.visibility = View.GONE
    }

    override fun onClick(v: View?) {
        v?.apply {
            when (tag as Int) {
                ClickType.ACTION_RETURN -> requireActivity().onBackPressed()
                ClickType.ACTION_GET_CAPTCHA -> callGetCaptcha()
                ClickType.ACTION_CONFIRM -> callBindPhone()
            }
        }
    }

    /**
     * 账号列表item点击事件
     */
    private inner class OnItemClick(val areaCode: String) : View.OnClickListener {
        override fun onClick(v: View?) {
            tvArea.apply {
                changeAreaList()
                tvArea.text = areaCode
                this@BindPhoneFragment.code = areaCode
            }
        }
    }
}