package com.halo.assistant.fragment.user

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
import com.gh.gamecenter.common.constant.Constants
import com.gh.common.util.*
import com.gh.gamecenter.common.view.UrlInterceptedLinkMovementMethod
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.common.utils.fromHtml
import com.gh.gamecenter.common.utils.TextHelper
import com.gh.gamecenter.databinding.FragmentUserinfoEditBinding
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.retrofit.JSONObjectResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.common.retrofit.ApiResponse
import com.gh.gamecenter.login.user.UserViewModel
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.json.JSONException
import org.json.JSONObject
import java.lang.StringBuilder
import java.util.*

class UserInfoEditFragment : ToolbarFragment() {
    private lateinit var mBinding: FragmentUserinfoEditBinding

    private var mSaveMenuItem: MenuItem? = null
    private var mUserViewModel: UserViewModel? = null
    private var mUserInfoEntity: UserInfoEntity? = null
    private var mLoadingDialog: Dialog? = null

    private var mEditType = ""
    private var mIsForcedToCertificate = false

    override fun getLayoutId() = 0

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
        mEditType = requireArguments().getString(UserViewModel.KEY_EDIT_TYPE)!!
        mIsForcedToCertificate = requireArguments().getBoolean(EntranceConsts.KEY_IS_FORCED_TO_CERTIFICATE)

        initMenu(R.menu.menu_button)
        mSaveMenuItem = getItemMenu(R.id.menu_button)
        // sentry上报mSaveMenuItem、mSaveMenuItem.getActionView()可能为空
        if (mSaveMenuItem != null && mSaveMenuItem!!.actionView != null) {
            val menuView = mSaveMenuItem!!.actionView?.findViewById<TextView>(R.id.tv_menu_button)
            menuView?.setText(R.string.menu_text_save)
        }
        if (UserViewModel.TYPE_ID_CARD == mEditType) {
            getAuthText()
        }

        mUserInfoEntity = UserManager.getInstance().userInfoEntity

        val factory = UserViewModel.Factory(requireActivity().application)
        mUserViewModel = ViewModelProviders.of(this, factory).get(
            UserViewModel::class.java
        )
        mUserViewModel?.editObsUserinfo?.observe(this) { userInfoEntity: ApiResponse<UserInfoEntity?>? ->
            if (mLoadingDialog != null) {
                mLoadingDialog!!.dismiss()
            }
            if (mLoadingDialog != null && userInfoEntity != null && userInfoEntity.data != null) {
                if (TextUtils.equals(UserViewModel.TYPE_ID_CARD, mEditType)) {
                    mBinding.userinfoVerifiedSuccess.visibility = View.VISIBLE
                    mBinding.userinfoInformationTv.visibility = View.GONE
                    mBinding.userinfoCommit.visibility = View.GONE
                    mBinding.userinfoIdCardNameEt.isEnabled = false
                    mBinding.userinfoIdCardEt.isEnabled = false
                    val sb = StringBuilder(mBinding.userinfoIdCardNameEt.text.toString().substring(0, 1))
                    for (i in 0 until mBinding.userinfoIdCardNameEt.text.toString().length - 1) {
                        sb.append("*")
                    }
                    mBinding.userinfoIdCardNameEt.setText(sb.toString())
                    mBinding.userinfoIdCardEt.setText(
                        mBinding.userinfoIdCardEt.text.toString().replace(
                            "(\\d)\\d{16}([0-9,x-y])".toRegex(),
                            "$1****************$2"
                        )
                    )
                    if (mSaveMenuItem != null) mSaveMenuItem!!.isVisible = false
                    requireActivity().setResult(
                        Activity.RESULT_OK,
                        Intent().putExtra(AUTH_SUCCESS, true)
                    )
                    return@observe
                }
                requireActivity().finish()
            }
        }

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (mUserInfoEntity != null || UserViewModel.TYPE_ID_CARD == mEditType) {
            initView()
        }
    }

    private fun initView() {
        mBinding.contactItem.run {
            inputEt.setHint(R.string.userinfo_edit_contact_hint)
        }
        mBinding.contactDesItem.root.text = getString(R.string.userinfo_edit_contact_explain)

        val title: String
        when (mEditType) {
            UserViewModel.TYPE_GENDER -> {
                mBinding.userinfoEditSex.visibility = View.VISIBLE
                title = getString(R.string.title_gender_select)
                mBinding.maleItem.run {
                    titleTv.text = getString(R.string.userinfo_edit_man)
                    root.setOnClickListener {
                        change(getString(R.string.gender_male))
                    }
                }
                mBinding.femaleItem.run {
                    titleTv.text = getString(R.string.userinfo_edit_woman)
                    root.setOnClickListener {
                        change(getString(R.string.gender_female))
                    }
                }
                val gender = mUserInfoEntity?.gender
                mSaveMenuItem?.isVisible = false
                if (!TextUtils.isEmpty(gender)) {
                    if (getString(R.string.gender_male) == gender) {
                        mBinding.maleItem.selectedIv.visibility = View.VISIBLE
                        mBinding.femaleItem.selectedIv.visibility = View.GONE
                    } else {
                        mBinding.maleItem.selectedIv.visibility = View.GONE
                        mBinding.femaleItem.selectedIv.visibility = View.VISIBLE
                    }
                }
            }
            UserViewModel.TYPE_NAME -> {
                mBinding.nicknameItem.run {
                    root.visibility = View.VISIBLE
                    inputEt.setHint(R.string.nickname_hint)
                    countTv.visibility = View.VISIBLE
                    inputEt.addTextChangedListener(UserInfoEditTextWatcher(inputEt))
                    inputEt.filters = arrayOf(TextHelper.getFilter(12, "最多12个字"))
                    val name = mUserInfoEntity?.name
                    if (!TextUtils.isEmpty(name)) {
                        inputEt.setText(name)
                        inputEt.setSelection(inputEt.text.toString().trim { it <= ' ' }.length)
                    }
                }
                mSaveMenuItem?.isVisible = true
                title = getString(R.string.title_nickname_change)

            }
            UserViewModel.TYPE_QQ -> {
                mBinding.userinfoEditQq.visibility = View.VISIBLE
                mSaveMenuItem?.isVisible = true
                mBinding.qqItem.run {
                    inputEt.hint = "输入你的常用QQ"
                    inputEt.addTextChangedListener(UserInfoEditTextWatcher(inputEt))
                    inputEt.filters = arrayOf(TextHelper.getFilter(12, "QQ号最多12位"))
                    val qq = mUserInfoEntity?.qq
                    if (!TextUtils.isEmpty(qq)) {
                        inputEt.setText(qq)
                        inputEt.setSelection(inputEt.text.toString().trim { it <= ' ' }.length)
                    }
                }
                mBinding.qqDesItem.root.text = getString(R.string.userinfo_edit_contact_explain)
                title = getString(R.string.title_contact)
            }
            UserViewModel.TYPE_MOBILE -> {
                mBinding.userinfoEditMobile.visibility = View.VISIBLE
                mSaveMenuItem?.isVisible = true
                mBinding.mobileItem.run {
                    inputEt.hint = "输入你的常用手机"
                    inputEt.addTextChangedListener(UserInfoEditTextWatcher(inputEt))
                    val mobile = mUserInfoEntity?.mobile
                    if (!TextUtils.isEmpty(mobile)) {
                        inputEt.setText(mobile)
                        inputEt.setSelection(inputEt.text.toString().trim { it <= ' ' }.length)
                    }
                    inputEt.filters = arrayOf(TextHelper.getFilter(11, "手机号最多11位"))
                }
                mBinding.mobileDesItem.root.text = "常用手机仅用于预约游戏时自动填写联系方式"
                title = getString(R.string.title_contact)
            }
            UserViewModel.TYPE_ID_CARD -> {
                if (mSaveMenuItem != null) mSaveMenuItem!!.isVisible = false
                mBinding.userinfoEditIdCard.visibility = View.VISIBLE
                title = "实名认证"
                val certificationOnlyInfoEntity: UserInfoEntity?
                val deviceCertificationInfoString =
                    SPUtils.getString(Constants.SP_DEVICE_CERTIFICATION_PREFIX + HaloApp.getInstance().gid)
                if (!TextUtils.isEmpty(deviceCertificationInfoString)) {
                    certificationOnlyInfoEntity = GsonUtils.fromJson(
                        deviceCertificationInfoString,
                        UserInfoEntity::class.java
                    )
                    if (mUserInfoEntity == null && certificationOnlyInfoEntity != null) {
                        mUserInfoEntity = certificationOnlyInfoEntity
                    }
                }
                if (mUserInfoEntity != null) {
                    val idCard = mUserInfoEntity?.idCard
                    if (idCard != null && !TextUtils.isEmpty(idCard.name)) {
                        val sb = StringBuilder(idCard.name!!.substring(0, 1))
                        var i = 0
                        while (i < idCard.name!!.length - 1) {
                            sb.append("*")
                            i++
                        }
                        mBinding.userinfoIdCardNameEt.setText(sb.toString())
                        mBinding.userinfoIdCardEt.setText(
                            idCard.id!!.replace(
                                "(\\d)\\d{16}([0-9,x-y])".toRegex(),
                                "$1****************$2"
                            )
                        )
                        mBinding.userinfoIdCardNameEt.isEnabled = false
                        mBinding.userinfoIdCardEt.isEnabled = false
                        mBinding.userinfoCommit.visibility = View.GONE
                        mBinding.userinfoVerifiedSuccess.visibility = View.VISIBLE
                        mBinding.userinfoInformationTv.visibility = View.GONE
                    } else {
                        NewLogUtils.logCertificationTriggerType(mIsForcedToCertificate)
                    }
                } else {
                    NewLogUtils.logCertificationTriggerType(mIsForcedToCertificate)
                }
                mBinding.userinfoIdCardNameEt.filters = arrayOf(TextHelper.getFilter(20, "最多20个字"))
                mBinding.userinfoIdCardEt.filters = arrayOf(TextHelper.getFilter(18, "最多18个字"))
            }
            UserViewModel.TYPE_INTRODUCE -> {
                mBinding.introduceItem.root.visibility = View.VISIBLE
                mSaveMenuItem?.isVisible = true
                title = getString(R.string.userinfo_introduce)
                val introduce = mUserInfoEntity?.introduce
                mBinding.introduceItem.run {
                    countTv.visibility = View.VISIBLE
                    inputEt.addTextChangedListener(UserInfoEditTextWatcher(inputEt))
                    inputEt.filters = arrayOf(TextHelper.getFilter(30, "最多30个字"))
                    if (!TextUtils.isEmpty(introduce)) {
                        inputEt.setText(introduce)
                        inputEt.setSelection(inputEt.text.toString().trim { it <= ' ' }.length)
                    }
                }
            }
            else -> title = ""
        }
        setNavigationTitle(title)
    }

    override fun onMenuItemClick(menuItem: MenuItem) {
        super.onMenuItemClick(menuItem)
        when (menuItem.itemId) {
            R.id.menu_button -> saveData()
        }
    }

    private fun saveData() {
        if (UserViewModel.TYPE_NAME == mEditType) {
            var value: String = mBinding.nicknameItem.inputEt.text.toString().trim { it <= ' ' }
            if (!TextUtils.isEmpty(value)) {
                value = value.replace(" ", "")
                if (value == mUserInfoEntity?.name) {
                    requireActivity().finish()
                } else {
                    change(value)
                }
            } else {
                toast(R.string.nickname_empty_hint)
            }
        } else if (UserViewModel.TYPE_QQ == mEditType) {
            val qq: String = mBinding.qqItem.inputEt.text.toString()
            change(qq)
        } else if (UserViewModel.TYPE_MOBILE == mEditType) {
            val mobile: String = mBinding.mobileItem.inputEt.text.toString()
            if (mobile.isNotEmpty()) {
                if (mobile.length < 11 || !mobile.startsWith("1")) {
                    toast("手机号格式错误，请检查并重新输入")
                    return
                }
            }
            change(mobile)
        } else if (UserViewModel.TYPE_INTRODUCE == mEditType) {
            val value: String = mBinding.introduceItem.inputEt.text.toString().trim { it <= ' ' } // 去除前后空格
            change(value.replace("\\s+".toRegex(), " ")) // 多个空格合成一个
        } else if (UserViewModel.TYPE_ID_CARD == mEditType) {
            val name: String = mBinding.userinfoIdCardNameEt.text.toString()
            val idCard: String = mBinding.userinfoIdCardEt.text.toString()
            if (TextUtils.isEmpty(name)) {
                toast("请输入姓名")
                return
            }
            if (TextUtils.isEmpty(idCard)) {
                toast("请输入身份证号码")
                return
            }
            if (name.length < MIN_NAME_LENGHT) {
                toast("姓名至少2个汉字")
                return
            }
            val regName = "[\\u4e00-\\u9fa5]+".toRegex()
            if (!name.matches(regName)) {
                toast("姓名无效，请重新输入")
                return
            }
            if (idCard.length < 18) {
                toast("必须使用18位的身份证号码")
                return
            }
            val regIdCard = "^[1-9]\\d{5}([1-9]\\d{3})(0\\d|1[0-2])([0-2]\\d|3[0-1])\\d{3}[\\dXx]$".toRegex()
            if (!idCard.matches(regIdCard)) {
                toast("身份证无效，请重新输入")
                return
            }
            /*int year = Integer.parseInt(idCard.substring(6, 10));
            long curTime = Utils.getTime(getContext()) * 1000;
            int curYear = Integer.parseInt((new SimpleDateFormat("yyyy", Locale.CHINA)).format(new Date(curTime)));
            if (curYear - year < 18) {
                toast("身份证无效，请重新输入");
                return;
            }*/
            val dialog = VerifiedConfirmDialog(requireContext(), "我的光环_新", "实名认证")
            dialog.show()
            dialog.onConfirmClickListener = {
                try {
                    val jsonObject = JSONObject()
                    jsonObject.put("id", idCard)
                    jsonObject.put("name", name)
                    change(jsonObject.toString())
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
        }
    }

    private fun change(content: String) {
        mLoadingDialog = DialogUtils.showWaitDialog(activity, "正在修改信息...")
        mUserViewModel?.changeUserInfo(content, mEditType)
    }

    private inner class UserInfoEditTextWatcher(private val mEditText: EditText) : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            val tvCount = s.length
            if (mEditText === mBinding.nicknameItem.inputEt) {
                mBinding.nicknameItem.countTv.text = String.format(Locale.CHINA, "%d/12", tvCount)
            } else if (mEditText === mBinding.introduceItem.inputEt) {
                mBinding.introduceItem.countTv.text = String.format(Locale.CHINA, "%d/30", tvCount)
            }
        }

        override fun afterTextChanged(s: Editable) {}
    }

    /**
     * 身份证输入框说明文案
     */
    @SuppressLint("CheckResult")
    private fun getAuthText() {
        RetrofitManager.getInstance().api
            .authText
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : JSONObjectResponse() {
                override fun onResponse(response: JSONObject) {
                    super.onResponse(response)
                    try {
                        val text = response.getString("text")
                        mBinding.userinfoInformationTv.text = text.fromHtml()
                        mBinding.userinfoInformationTv.movementMethod =
                            UrlInterceptedLinkMovementMethod()
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }
            })
    }

    companion object {
        private const val MIN_NAME_LENGHT = 2
        const val AUTH_SUCCESS = "auth_success" //认证通过
    }
}