package com.halo.assistant.fragment.user

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup.MarginLayoutParams
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProviders
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.*
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.retrofit.ApiResponse
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.databinding.FragmentUserinfoBinding
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.login.user.UserViewModel
import com.halo.assistant.fragment.user.avatar.ChangeAvatarDialog

class UserInfoFragment : ToolbarFragment() {

    private lateinit var mBinding: FragmentUserinfoBinding
    private val mViewModel: UserInfoViewModel by viewModels()

    override fun getLayoutId() = 0

    override fun getInflatedLayout() =
        FragmentUserinfoBinding.inflate(layoutInflater).apply { mBinding = this }.root

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setNavigationTitle(getString(R.string.title_userinfo))

        val factory = UserViewModel.Factory(
            requireActivity().application
        )
        val userViewModel = ViewModelProviders.of(this, factory).get(
            UserViewModel::class.java
        )
        userViewModel.loginObsUserinfo.observe(this) { userInfoEntity: ApiResponse<UserInfoEntity?>? ->
            if (userInfoEntity != null && userInfoEntity.data != null) {
                initView(userInfoEntity.data)
            }
        }

        mViewModel.certificationSwitch.observe(this) {
            mBinding.bbsCertItem.root.goneIf(!it)
            mBinding.bbsCertDivider.root.goneIf(!it)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data != null) {
            val avatarUrl = data.getStringExtra(EntranceConsts.KEY_DATA)
            if (avatarUrl != null) {
                ImageUtils.display(mBinding.userIcon, avatarUrl)
            }
        }
    }

    private fun initView(userInfo: UserInfoEntity?) {
        mBinding.userIcon.setOnClickListener {
            MtaHelper.onEvent("个人主页详情", "个人中心", "头像")
            ChangeAvatarDialog.show(requireActivity() as AppCompatActivity, tag ?: "")
        }
        mBinding.nicknameItem.run {
            titleTv.text = getString(R.string.userinfo_nickname)
            contentTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("个人主页详情", "个人中心", "昵称")
                startActivity(UserInfoEditActivity.getIntent(requireContext(), UserViewModel.TYPE_NAME))
            }
        }
        mBinding.sexItem.run {
            titleTv.text = getString(R.string.userinfo_gender)
            contentTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("个人主页详情", "个人中心", "性别")
                startActivity(UserInfoEditActivity.getIntent(requireContext(), UserViewModel.TYPE_GENDER))
            }
        }
        mBinding.areaItem.run {
            titleTv.text = getString(R.string.userinfo_region)
            contentTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("个人主页详情", "个人中心", "地区")
                startActivity(UserRegionActivity.getIntent(requireContext()))
            }
        }
        mBinding.introduceItem.run {
            titleTv.text = getString(R.string.userinfo_introduce)
            contentTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("个人主页详情", "个人中心", "个性签名")
                startActivity(UserInfoEditActivity.getIntent(requireContext(), UserViewModel.TYPE_INTRODUCE))
            }
        }
        mBinding.userVerifyItem.run {
            root.goneIf(userInfo?.auth == null)
            mBinding.userVerifyDivider.root.goneIf(userInfo?.auth == null)
            titleTv.text = "用户认证"
            textMoreTv.text = userInfo?.auth?.text
            textMoreTv.visibility = View.VISIBLE
            root.setOnClickListener {
                startActivity(UserAuthActivity.getIntent(requireContext()))
            }
        }
        mBinding.realNameVerifyItem.run {
            titleTv.text = "实名认证"
            contentTv.visibility = View.VISIBLE
            root.layoutParams = (root.layoutParams as MarginLayoutParams).apply {
                setMargins(0, if (userInfo?.auth == null) 8F.dip2px() else 0, 0, 0)
            }
            root.setOnClickListener {
                MtaHelper.onEvent("个人主页详情", "个人中心", "实名认证")
                startActivity(ShellActivity.getIntent(requireContext(), ShellActivity.Type.REAL_NAME_INFO, null))
            }
        }
        mBinding.bbsCertItem.run {
            root.goneIf(!SPUtils.getBoolean(Constants.SP_CERTIFICATION_SWITCH))
            mBinding.bbsCertDivider.root.goneIf(!SPUtils.getBoolean(Constants.SP_CERTIFICATION_SWITCH))
            titleTv.text = "社区交流身份认证"
            contentTv.visibility = View.VISIBLE
        }
        mBinding.qqItem.run {
            titleTv.text = "QQ"
            contentTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("个人主页详情", "个人中心", "QQ")
                startActivity(UserInfoEditActivity.getIntent(requireContext(), UserViewModel.TYPE_QQ))
            }
        }
        mBinding.mobileItem.run {
            titleTv.text = "手机"
            contentTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("个人主页详情", "个人中心", "手机")
                startActivity(UserInfoEditActivity.getIntent(requireContext(), UserViewModel.TYPE_MOBILE))
            }
        }
        mBinding.userinfoSafeTutorialTv.setOnClickListener {
            MtaHelper.onEvent("个人主页详情", "个人中心", "账号安全指南")
            DirectUtils.directToWebView(
                requireContext(),
                "https://and-static.ghzs66.com/page/guide_page/safety_guide.html",
                "(个人中心)"
            )
        }
        if (userInfo != null) {
            ImageUtils.display(mBinding.userIcon, userInfo.icon)
            mBinding.nicknameItem.contentTv.text = userInfo.name
            val region = userInfo.region
            if (!TextUtils.isEmpty(region)) {
                mBinding.areaItem.contentTv.text = region
            } else {
                mBinding.areaItem.contentTv.setText(R.string.userinfo_region_empty)
            }
            val gender = userInfo.gender
            if (!TextUtils.isEmpty(gender)) {
                mBinding.sexItem.contentTv.text = gender
            } else {
                mBinding.sexItem.contentTv.setText(R.string.userinfo_gender_empty)
            }
            val qq = userInfo.qq
            if (!TextUtils.isEmpty(qq)) {
                mBinding.qqItem.contentTv.text = qq
            } else {
                mBinding.qqItem.contentTv.text = "仅用于意见反馈时自动填写联系方式"
            }
            val mobile = userInfo.mobile
            if (!TextUtils.isEmpty(mobile)) {
                mBinding.mobileItem.contentTv.text = mobile
            } else {
                mBinding.mobileItem.contentTv.text = "仅用于预约游戏时自动填写联系方式"
            }
            var introduce = userInfo.introduce
            if (!TextUtils.isEmpty(introduce)) {
                introduce = StringUtils.shrinkStringWithDot(introduce, 15)
                mBinding.introduceItem.contentTv.text = introduce
            } else {
                mBinding.introduceItem.contentTv.setText(R.string.userinfo_contact_empty)
            }
            val idCard = userInfo.idCard
            if (idCard != null && !TextUtils.isEmpty(idCard.name)) {
                val name = StringBuilder(idCard.name)
                val replacement = StringBuilder()
                for (i in 0 until name.length - 1) replacement.append("*")
                mBinding.realNameVerifyItem.contentTv.text = name.replace(1, name.length, replacement.toString())
            } else {
                mBinding.realNameVerifyItem.contentTv.setText(R.string.userinfo_contact_empty)
            }

            val isRealName = idCard != null && !TextUtils.isEmpty(idCard.name) // 是否实名认证
            val isBindPhone = userInfo.loginMobile?.isNotBlank() ?: false // 是否绑定手机
            val isVerifyPhone = userInfo.mobileAuth != null && userInfo.mobileAuth!!.auth // 是否完成手机号验证
            val isCertResult = isRealName || isBindPhone || isVerifyPhone
            if (isCertResult) {
                mBinding.bbsCertItem.contentTv.text = "已认证"
            } else {
                mBinding.bbsCertItem.contentTv.text = "未认证"
            }

            mBinding.bbsCertItem.root.setOnClickListener {
                if (isCertResult) {
                    startActivity(BbsCertificationActivity.getIntent(requireContext()))
                } else {
                    startActivity(VerifyPhoneActivity.getIntent(requireContext()))
                    NewFlatLogUtils.logPhoneNumberVerifyDialogShow("个人中心-社区交流身份认证")
                }
            }
        }
    }
}