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

import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.text.InputType
import android.text.TextUtils
import android.view.*
import android.widget.*
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.LoginType
import cn.yyxx.eyuangame.core.entity.ResultInfo
import cn.yyxx.eyuangame.core.entity.Session
import cn.yyxx.eyuangame.core.impl.SdkBridgeImpl
import cn.yyxx.eyuangame.core.impl.login.LoginActivity
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.ui.dialog.AgreementDialog
import cn.yyxx.eyuangame.core.ui.dialog.ForgetPwdDialog
import cn.yyxx.eyuangame.core.utils.EditTextUtils
import cn.yyxx.eyuangame.core.utils.SessionUtils
import cn.yyxx.support.ResUtils
import cn.yyxx.support.hawkeye.ToastUtils
import org.json.JSONObject

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

    private lateinit var mView: View
    private lateinit var mInflater: LayoutInflater

    private lateinit var loginImpl: LoginActivity

    private lateinit var eetAccount: EventEditText
    private lateinit var eetPwd: EventEditText

    private lateinit var tvForget: TextView

    private lateinit var btnLauncher: Button

    private lateinit var ivCheck: ImageView
    private lateinit var tvAgreement: TextView

    private lateinit var ivGoogle: ImageView
    private lateinit var ivFacebook: ImageView
    private lateinit var ivGuest: ImageView

    private lateinit var rlAccountList: RelativeLayout
    private lateinit var llAccountList: LinearLayout
    private lateinit var svAccountList: ScrollView

    private var imgUp = 0
    private var imgDown = 0
    private var imgShow = 0
    private var imgHide = 0
    private var imgCheck = 0
    private var imgUnCheck = 0

    private var check = true
    private var isShowText = false

    private var agreementDialog: AgreementDialog? = null
    private var forgetPwdDialog: ForgetPwdDialog? = null

    private val userLists = mutableListOf<Session>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        loginImpl = requireActivity() as LoginActivity
        mInflater = inflater
        mView = inflater.inflate(ResUtils.getResId(requireActivity(), "yyxx_login_launcher", "layout"), container, false)
        initView(mView)
        return mView
    }

    private fun initView(view: View) {
        imgUp = ResUtils.getResId(requireActivity(), "yyxx_pack_up_img", "drawable")
        imgDown = ResUtils.getResId(requireActivity(), "yyxx_pack_down_img", "drawable")
        imgShow = ResUtils.getResId(requireActivity(), "yyxx_show_img", "drawable")
        imgHide = ResUtils.getResId(requireActivity(), "yyxx_hide_img", "drawable")
        imgCheck = ResUtils.getResId(requireActivity(), "yyxx_check_img", "drawable")
        imgUnCheck = ResUtils.getResId(requireActivity(), "yyxx_uncheck_img", "drawable")

        eetAccount = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_eet_account", "id"))
        eetAccount.apply {
            leftImageView.setBackgroundResource(ResUtils.getResId(requireActivity(), "yyxx_account_img", "drawable"))
            leftImageView.visibility = View.VISIBLE
            rightImageView.setBackgroundResource(imgDown)
            rightImageView.visibility = View.GONE
            editText.setHint(ResUtils.getResId(requireActivity(), "yyxx_hint_account", "string"))
            rightImageView.setOnClickListener {
                changeAccountList()
            }
        }

        eetPwd = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_eet_pwd", "id"))
        eetPwd.apply {
            editText.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
            leftImageView.setBackgroundResource(ResUtils.getResId(requireActivity(), "yyxx_pwd_img", "drawable"))
            leftImageView.visibility = View.VISIBLE
            editText.setHint(ResUtils.getResId(requireActivity(), "yyxx_hint_pwd", "string"))
            rightImageView.setBackgroundResource(imgShow)
            rightImageView.visibility = View.VISIBLE
            rightImageView.setOnClickListener {
                if (!isShowText) {
                    isShowText = true
                    rightImageView.setBackgroundResource(imgHide)
                    editText.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                } else {
                    isShowText = false
                    rightImageView.setBackgroundResource(imgShow)
                    editText.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
                }
                editText.setSelection(editText.length())
            }
        }

        tvForget = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_tv_forget", "id"))

        btnLauncher = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_btn_launcher", "id"))

        ivCheck = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_iv_check", "id"))
        tvAgreement = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_tv_agreement", "id"))
        if (SdkBridgeImpl.initBean.privacyCfg.switch == 0 || TextUtils.isEmpty(SdkBridgeImpl.initBean.privacyCfg.url)) {
            ivCheck.visibility = View.GONE
            tvAgreement.visibility = View.GONE
        } else {
            ivCheck.visibility = View.VISIBLE
            tvAgreement.visibility = View.VISIBLE
        }

        ivGoogle = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_iv_google", "id"))
        ivFacebook = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_iv_facebook", "id"))
        ivGuest = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_iv_guest", "id"))

        rlAccountList = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_rl_account_list", "id"))
        rlAccountList.visibility = View.GONE
        llAccountList = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_ll_account_list", "id"))
        svAccountList = view.findViewById(ResUtils.getResId(requireActivity(), "yyxx_sv_account_list", "id"))

        initViewAction()
        initViewListener()
        autoFillUserInfo()
    }

    private fun initViewAction() {
        tvForget.tag = ClickType.ACTION_FORGET
        btnLauncher.tag = ClickType.ACTION_LAUNCHER
        ivCheck.tag = ClickType.ACTION_CLICK_CHECK
        tvAgreement.tag = ClickType.ACTION_CLICK_AGREEMENT
        ivGoogle.tag = ClickType.ACTION_GOOGLE_MODE
        ivFacebook.tag = ClickType.ACTION_FACEBOOK_MODE
        ivGuest.tag = ClickType.ACTION_GUEST_MODE
    }

    private fun initViewListener() {
        tvForget.setOnClickListener(this)
        btnLauncher.setOnClickListener(this)
        ivCheck.setOnClickListener(this)
        tvAgreement.setOnClickListener(this)
        ivGoogle.setOnClickListener(this)
        ivFacebook.setOnClickListener(this)
        ivGuest.setOnClickListener(this)
    }

    private fun autoFillUserInfo() {
        val temp = SessionUtils.instance.getLocalSessionLimit3(requireActivity())
        if (temp.size == 0) {
            //本地没有缓存账号，直接返回
            eetAccount.rightImageView.visibility = View.GONE
            return
        } else {
            temp.forEach { session ->
                if (session.loginType != LoginType.TYPE_ACCOUNT_LOGIN) {
                    //游客账号显示
                    return@forEach
                }
                Logger.d("autoFillUserInfo $session")
                userLists.add(session)
            }

            userLists.apply {
                if (size > 0) {
                    val session = this[0]
                    eetAccount.editText.setText(session.userName)
                    eetPwd.editText.setText(session.pwd)
                }
                if (size > 1) {
                    initAccountList()
                    eetAccount.rightImageView.visibility = View.VISIBLE
                } else {
                    eetAccount.rightImageView.visibility = View.GONE
                    rlAccountList.visibility = View.GONE
                }
            }

            if (userLists.size == 0) {
                eetAccount.rightImageView.visibility = View.GONE
                rlAccountList.visibility = View.GONE
            }
        }
    }

    private fun changeAccountList() {
        if (rlAccountList.visibility == View.GONE) {
            eetAccount.rightImageView.setBackgroundResource(imgUp)
            rlAccountList.visibility = View.VISIBLE
        } else {
            eetAccount.rightImageView.setBackgroundResource(imgDown)
            rlAccountList.visibility = View.GONE
        }
    }

    private fun initAccountList() {
        llAccountList.removeAllViews()
        //单行高
        var height = 100
        eetAccount.apply {
            height = if (layoutParams != null) {
                layoutParams!!.height
            } else {
                100
            }
        }
        //ScrollView最大高度
        var maxHeight = 0
        userLists.apply {
            if (size > 0) {
                maxHeight = if (size < 5) {
                    size * height
                } else {
                    (size - 1) * height
                }
            }
        }
        //循环添加列
        userLists.apply {
            for (i in indices) {
                val session = this[i]
                //添加线
                val line = View(requireContext())
                line.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 2)
                line.setBackgroundColor(Color.parseColor("#4D505050"))
                llAccountList.apply {
                    if (childCount > 0) {
                        addView(line)
                    }
                }

                //添加账号
                val item = mInflater.inflate(ResUtils.getResId(requireActivity(), "yyxx_account_list_item", "layout"), null)
                item?.apply {
                    val tvAccountName = findViewById<TextView>(ResUtils.getResId(requireActivity(), "yyxx_tv_name", "id"))
                    tvAccountName.gravity = Gravity.CENTER_VERTICAL
                    tvAccountName.setPadding(15, 0, 0, 0)
                    tvAccountName.text = session.userName
                    val ivDelete = findViewById<ImageView>(ResUtils.getResId(requireActivity(), "yyxx_iv_delete", "id"))
                    setOnClickListener(AccountItemClick(session))
                    ivDelete.setOnClickListener(AccountDeleteClick(session))
                    layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height)
                    llAccountList.addView(this, llAccountList.childCount)
                }
            }
        }
        svAccountList.layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, maxHeight)
    }

    fun hideAccountList(): Boolean {
        userLists.let {
            if (it.size > 0 && rlAccountList.visibility == View.VISIBLE) {
                eetAccount.rightImageView.setBackgroundResource(imgDown)
                rlAccountList.visibility = View.GONE
                return true
            }
        }
        return false
    }

    private fun changeCheck() {
        if (check) {
            check = false
            ivCheck.setBackgroundResource(imgUnCheck)
        } else {
            check = true
            ivCheck.setBackgroundResource(imgCheck)
        }
    }

    private fun showForgetPwdDialog() {
        forgetPwdDialog?.apply {
            dismiss()
            forgetPwdDialog = null
        }
        forgetPwdDialog = ForgetPwdDialog(requireContext(), SdkBridgeImpl.isLand, SdkBridgeImpl.initBean.areaCodeList)
        forgetPwdDialog?.apply {
            loginImpl.hideLoginView()
            ivReturn.setOnClickListener {
                dismiss()
                loginImpl.showLoginView()
            }
            setOnKeyListener(object : DialogInterface.OnKeyListener {
                override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        dismiss()
                        loginImpl.showLoginView()
                        return true
                    }
                    return false
                }

            })
            btnConfirm.setOnClickListener {
                invokeForgetPwd()
            }
            show()
        }
    }

    private fun showAgreementDialog() {
        agreementDialog?.apply {
            dismiss()
            agreementDialog = null
        }
        agreementDialog = AgreementDialog(requireContext(), SdkBridgeImpl.initBean.privacyCfg.url, SdkBridgeImpl.isLand)
//        agreementDialog = AgreementDialog(requireContext(), "http://www.eyuangame.com/agreement_user.html", SdkBridgeImpl.isLand)
        agreementDialog?.apply {
            loginImpl.hideLoginView()
            ivReturn.setOnClickListener {
                dismiss()
                loginImpl.showLoginView()
            }
            setOnKeyListener(object : DialogInterface.OnKeyListener {
                override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        dismiss()
                        loginImpl.showLoginView()
                        return true
                    }
                    return false
                }
            })
            show()
        }
    }

    private fun invokeForgetPwd() {
        forgetPwdDialog?.apply {
            val userName = eetAccount.editText.text.trim().toString()
            val areaCode = code
            val phoneNum = eetPhone.editText.text.trim().toString()

            if (!EditTextUtils.filterAccount(userName)) {
                ToastUtils.toastInfo(requireActivity(), ResUtils.getResString(requireActivity(), "yyxx_tips_account_format_error"))
                return
            }

            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.filterPhone(phoneNum)) {
                ToastUtils.toastInfo(requireActivity(), ResUtils.getResString(requireActivity(), "yyxx_tips_phone_format_error"))
                return
            }

            with(JSONObject()) {
                put("uname", userName)
                put("area_code", areaCode)
                put("phone_number", phoneNum)
                SdkRequest.instance.forgetUserPwd(requireActivity(), this, object : IRequestCallback {
                    override fun onResponse(resultInfo: ResultInfo) {
                        if (resultInfo.code == 1) {
                            ToastUtils.toastInfo(requireActivity(), resultInfo.msg)
                            this@apply.dismiss()
                        } else {
                            ToastUtils.toastInfo(requireActivity(), resultInfo.msg)
                        }
                    }
                })
            }
        }
    }

    override fun onClick(v: View?) {
        v?.apply {
            when (tag as Int) {
                ClickType.ACTION_FORGET -> showForgetPwdDialog()
                ClickType.ACTION_LAUNCHER -> {
                    val userName = eetAccount.editText.text.trim().toString()
                    val pwd = eetPwd.editText.text.trim().toString()
                    if (!EditTextUtils.filterAccount(userName)) {
                        ToastUtils.toastInfo(requireActivity(), ResUtils.getResString(requireActivity(), "yyxx_tips_account_format_error"))
                        return
                    }
                    if (!EditTextUtils.filterPwd(pwd)) {
                        ToastUtils.toastInfo(requireActivity(), ResUtils.getResString(requireActivity(), "yyxx_tips_pwd_format_error"))
                        return
                    }
                    loginImpl.userSignInImpl.accountLogin(requireActivity(), userName, pwd)
                }
                ClickType.ACTION_CLICK_CHECK -> changeCheck()
                ClickType.ACTION_CLICK_AGREEMENT -> showAgreementDialog()
                ClickType.ACTION_GOOGLE_MODE -> loginImpl.userSignInImpl.googleLogin(requireActivity())
                ClickType.ACTION_FACEBOOK_MODE -> loginImpl.userSignInImpl.facebookLogin(requireActivity())
                ClickType.ACTION_GUEST_MODE -> loginImpl.userSignInImpl.guestLogin(requireActivity())
            }
        }
    }

    /**
     * 账号列表item点击事件
     */
    private inner class AccountItemClick(val session: Session) : View.OnClickListener {
        override fun onClick(v: View?) {
            eetAccount.apply {
                rightImageView.setBackgroundResource(imgUp)
                hideAccountList()
                editText.setText(session.userName)
                eetPwd.editText.setText(session.pwd)
            }
        }
    }

    private inner class AccountDeleteClick(val session: Session) : View.OnClickListener {
        override fun onClick(v: View?) {
            SessionUtils.instance.deleteUserInfo(requireActivity(), session.userId)
            userLists.clear()
            autoFillUserInfo()
        }

    }
}