package com.gh.gamecenter.setting.compose.activity

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.activity.viewModels
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Icon
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.paint
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalTextInputService
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Popup
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.gamecenter.common.BuildConfig
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.provider.IDialogUtilsProvider
import com.gh.gamecenter.core.utils.PatternUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.setting.compose.R
import com.gh.gamecenter.setting.compose.base.ComposeBaseActivity
import com.gh.gamecenter.setting.compose.clickableWithoutRipple
import com.gh.gamecenter.setting.compose.empty
import com.gh.gamecenter.setting.compose.entity.ConflictUserEntity
import com.gh.gamecenter.setting.compose.ui.component.*
import com.gh.gamecenter.setting.compose.ui.theme.HaloTheme
import com.gh.gamecenter.setting.compose.viewmodel.ComposeBindPhoneViewModel
import com.lightgame.utils.Utils
import kotlinx.coroutines.delay

class ComposeBindPhoneActivity : ComposeBaseActivity() {

    private var mIsConflict by mutableStateOf(false)
    private var mFromLogin by mutableStateOf(false)
    private var mChangePhone by mutableStateOf(false)
    private var mShowPhoneNumberError by mutableStateOf(false)
    private var mShowCaptchaError by mutableStateOf(false)
    private var mShowCaptcha by mutableStateOf(false)
    private var mShowInviteCode by mutableStateOf(false)
    private var mBindPhoneNumber by mutableStateOf(TextFieldValue(""))
    private var mCaptcha by mutableStateOf("")
    private var mInviteCode by mutableStateOf("")
    private var mBindPhoneBtnText by mutableStateOf("下一步")
    private var mBindPhoneBtnEnable by mutableStateOf(false)
    private var mCaptchaCountDown by mutableStateOf(false)
    private var mGetCaptchaBtnText by mutableStateOf("")
    private var mShowBindPhoneKeyboard by mutableStateOf(false)

    private var mConflictPhone by mutableStateOf("")
    private var mConflictUser by mutableStateOf(ConflictUserEntity())
    private var mPopup by mutableStateOf(false)

    private var mDialog: Dialog? = null
    private val mViewModel: ComposeBindPhoneViewModel by viewModels()

    private val mCaptchaHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 0) { // 验证码倒计时
                var arg1 = msg.arg1
                arg1--
                if (arg1 >= 0) {
                    val message = Message()
                    message.what = 0
                    message.arg1 = arg1
                    sendMessageDelayed(message, 1000)
                    mGetCaptchaBtnText = arg1.toString() + "s"
                } else {
                    mCaptchaCountDown = false
                    mGetCaptchaBtnText = "重新获取"
                }
            }
        }
    }

    private val mBindPhoneBtnClick: () -> Unit = bindPhoneBtnClick@{
        val oldPhoneNum = UserManager.getInstance().userInfoEntity?.loginMobile ?: ""
        val phoneNum: String = mBindPhoneNumber.text.trim { it <= ' ' }.replace(" ".toRegex(), "")
        // 更换手机号，当输入手机号和当前手机号相同则弹出提示
        if (mChangePhone && phoneNum == oldPhoneNum) {
            val dialogUtils =
                ARouter.getInstance().build(RouteConsts.provider.dialogUtils).navigation() as? IDialogUtilsProvider
            dialogUtils?.showNoticeDialog(this@ComposeBindPhoneActivity, "", getString(R.string.change_phone_same)) {
                mBindPhoneNumber = mBindPhoneNumber.empty()
            }
            return@bindPhoneBtnClick
        }

        if (mBindPhoneBtnText == "下一步") {
            if (PatternUtils.isPhoneNum(phoneNum) && phoneNum.length == 11) {
                mShowPhoneNumberError = false

                if (mChangePhone) {
                    mViewModel.reBindPhoneOne(oldPhoneNum, phoneNum, this@ComposeBindPhoneActivity)
                } else {
                    mViewModel.bindPhoneOne(phoneNum, this@ComposeBindPhoneActivity)
                }
            } else {
                mShowPhoneNumberError = true
                return@bindPhoneBtnClick
            }
        } else {
            if (mChangePhone) {
                mViewModel.reBindPhoneTwo(
                    oldPhoneNum,
                    phoneNum,
                    mCaptcha.trim(),
                    mInviteCode.trim(),
                    this@ComposeBindPhoneActivity
                )
            } else {
                mViewModel.bindPhoneTwo(
                    phoneNum,
                    mCaptcha.trim(),
                    mInviteCode.trim(),
                    this@ComposeBindPhoneActivity
                )
            }
        }
    }

    private val mGetCaptchaBtnClick: () -> Unit = {
        if (!mCaptchaCountDown) {
            val phoneNum: String = mBindPhoneNumber.text.trim { it <= ' ' }.replace(" ".toRegex(), "")
            if (mChangePhone) {
                val oldPhoneNum = UserManager.getInstance().userInfoEntity?.loginMobile ?: ""
                mViewModel.reBindPhoneOne(oldPhoneNum, phoneNum, this)
            } else {
                mViewModel.bindPhoneOne(phoneNum, this)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mIsConflict = intent.getBooleanExtra(KEY_IS_CONFLICT, false)
        if (mIsConflict) {
            mConflictPhone = intent.getStringExtra(EntranceConsts.KEY_CONFLICT_PHONE) ?: ""
            mConflictUser = intent.getParcelableExtra(EntranceConsts.KEY_CONFLICT_USER) ?: ConflictUserEntity()
        } else {
            mFromLogin = intent.getBooleanExtra(EntranceConsts.KEY_FROM_LOGIN, false)
            mChangePhone = intent.getBooleanExtra(EntranceConsts.KEY_CHANGE_PHONE, false)
            mGetCaptchaBtnText = getString(R.string.login_get_captcha)
            initObserver()
            mShowBindPhoneKeyboard = true
        }
        super.onCreate(savedInstanceState)
    }

    @SuppressLint("UnusedMaterialScaffoldPaddingParameter")
    @Composable
    override fun Content() {
        Scaffold(
            topBar = {
                if (!mFromLogin) {
                    SettingTopAppBar("") {
                        onBackPressed()
                    }
                }
            }, modifier = Modifier.fillMaxSize(),
            backgroundColor = HaloTheme.colors.backgroundWhite
        ) {
            if (mIsConflict) {
                BindPhoneConflictPage()
            } else {
                BindPhonePage()
            }
        }
    }

    private fun initObserver() {
        mViewModel.nextLiveData.observe(this) {
            mShowCaptcha = true
            if ((BuildConfig.DEBUG || BuildConfig.BUILD_TIME != 0L) && !SPUtils.getBoolean(Constants.SP_HAS_COMPLETE_INVITE_CODE)) {
                mShowInviteCode = true
            }
            mBindPhoneBtnEnable = false
            mBindPhoneBtnText = "完成"

            Utils.toast(this, "验证码短信已发送，请注意查收")
            // 启动验证码倒计时
            val message = Message()
            message.what = 0
            message.arg1 = 60 // 倒数时间

            mCaptchaHandler.sendMessage(message)
            mCaptchaCountDown = true
        }

        // 手机号冲突
        mViewModel.phoneBoundLiveData.observe(this) { user ->
            val phoneNum = mBindPhoneNumber.text.trim { it <= ' ' }.replace(" ".toRegex(), "")
            var hidePhoneNum = phoneNum
            if (phoneNum.length >= 11) {
                hidePhoneNum = phoneNum.substring(0, 3) + "****" + phoneNum.substring(7, 11)
            }
            startActivityForResult(getBindPhoneConflictIntent(this, hidePhoneNum, user), 0)
        }

        mViewModel.finishLiveData.observe(this) { isSuccess ->
            if (isSuccess) {

                // 已完成填写邀请码
                val inviteCode = mInviteCode.trim()
                if (inviteCode.isNotBlank()) {
                    SPUtils.setBoolean(Constants.SP_HAS_COMPLETE_INVITE_CODE, true)
                }

                // 更新本地用户已绑定手机的信息
                val phoneNum: String = mBindPhoneNumber.text.trim { it <= ' ' }.replace(" ".toRegex(), "")
                UserManager.getInstance().userInfoEntity = UserManager.getInstance().userInfoEntity?.apply {
                    loginMobile = phoneNum
                }

                // 如果当前登录方式是手机号登录，也要更新loginType
                UserManager.getInstance().loginTokenEntity?.apply {
                    if (loginType?.length == 11) loginType = phoneNum
                }

                finish()
            } else {
                mShowCaptchaError = true
            }
        }

    }

    private fun showBindPhoneDialog() {
        val dialogUtils =
            ARouter.getInstance().build(RouteConsts.provider.dialogUtils).navigation() as? IDialogUtilsProvider
        mDialog = dialogUtils?.showBindPhoneDialog(this) {
            finish()
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_FINISH_CODE) {
            // 回到"账户与安全"界面
            finish()
        } else {
            // 从手机号冲突界面回到本界面，再次弹出软键盘
            mShowBindPhoneKeyboard = true
        }
    }

    override fun onStop() {
        super.onStop()
        mDialog = null
        mShowBindPhoneKeyboard = false
    }

    @Composable
    fun BindPhonePage() {
        val input = LocalTextInputService.current
        val phoneFocusRequester = remember {
            FocusRequester()
        }
        val captchaFocusRequester = remember {
            FocusRequester()
        }
        if (mShowBindPhoneKeyboard) {
            LaunchedEffect(Unit) {
                phoneFocusRequester.requestFocus()
                delay(100)
                input?.showSoftwareKeyboard()
            }
        }
        ConstraintLayout(modifier = Modifier.fillMaxSize()) {
            val (bindPhoneTitle, bindPhoneDesc, bindPhoneContainer, bindPhoneBtn, skipBtn) = createRefs()

            Text(
                text = if (mChangePhone) getString(R.string.bind_phone_title2) else getString(R.string.bind_phone_title1),
                fontSize = 22.sp,
                fontWeight = FontWeight.Bold,
                color = if (mIsDarkModeOn) Color.White else Color.Black,
                modifier = Modifier.constrainAs(bindPhoneTitle) {
                    top.linkTo(parent.top, if (mFromLogin) 100.dp else 48.dp)
                    start.linkTo(parent.start, 20.dp)
                    end.linkTo(parent.end, 20.dp)
                    width = Dimension.fillToConstraints
                })

            val currentPhoneNum = UserManager.getInstance().userInfoEntity?.loginMobile ?: ""
            Text(
                text = if (mChangePhone) "当前手机号：" + currentPhoneNum.substring(
                    0,
                    3
                ) + "******" + currentPhoneNum.substring(9, 11) else getString(R.string.bind_phone_desc),
                fontSize = 14.sp,
                lineHeight = 22.sp,
                color = HaloTheme.colors.textSubtitle,
                modifier = Modifier.constrainAs(bindPhoneDesc) {
                    top.linkTo(bindPhoneTitle.bottom, 16.dp)
                    start.linkTo(parent.start, 20.dp)
                    end.linkTo(parent.end, 20.dp)
                    width = Dimension.fillToConstraints
                })

            Column(modifier = Modifier.constrainAs(bindPhoneContainer) {
                top.linkTo(bindPhoneDesc.bottom, 40.dp)
                start.linkTo(parent.start, 20.dp)
                end.linkTo(parent.end, 20.dp)
                width = Dimension.matchParent
            }) {
                BasicTextField(
                    value = mBindPhoneNumber,
                    onValueChange = {
                        val numberFilter = it.text.filter { c -> c.isDigit() }

                        // 输入手机号码加空格
                        val stringBuilder = StringBuilder()
                        for (i in numberFilter.indices) {
                            if (i != 3 && i != 8 && numberFilter[i] == ' ') {
                                continue
                            } else {
                                stringBuilder.append(numberFilter[i])
                                if ((stringBuilder.length == 4 || stringBuilder.length == 9)
                                    && stringBuilder[stringBuilder.length - 1] != ' '
                                ) {
                                    stringBuilder.insert(stringBuilder.length - 1, ' ')
                                }
                            }
                        }

                        val phoneNumber = if (stringBuilder.toString().length > 13) stringBuilder.toString()
                            .substring(0, 13) else stringBuilder.toString()
                        mBindPhoneNumber =
                            mBindPhoneNumber.copy(text = phoneNumber, selection = TextRange(phoneNumber.length))
                        mBindPhoneBtnEnable = mBindPhoneNumber.text.isNotEmpty()
                    },
                    singleLine = true,
                    textStyle = TextStyle(fontSize = 16.sp, color = HaloTheme.colors.textTitle),
                    cursorBrush = SolidColor(HaloTheme.colors.theme),
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
                    modifier = Modifier
                        .focusRequester(focusRequester = phoneFocusRequester)
                        .fillMaxWidth()
                        .height(48.dp),
                    decorationBox = { innerTextField ->
                        Column(modifier = Modifier.fillMaxSize()) {
                            ConstraintLayout(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(47.dp)
                            ) {
                                val (prefix, textField, closeIcon) = createRefs()
                                Box(modifier = Modifier.constrainAs(textField) {
                                    top.linkTo(parent.top)
                                    start.linkTo(parent.start, 44.dp)
                                    bottom.linkTo(parent.bottom)
                                    end.linkTo(parent.end)
                                    width = Dimension.matchParent
                                    height = Dimension.matchParent
                                }, contentAlignment = Alignment.CenterStart) {
                                    innerTextField()
                                    if (mBindPhoneNumber.text.isEmpty()) Text(
                                        text = getString(R.string.input_phone_hint),
                                        fontSize = 16.sp,
                                        color = HaloTheme.colors.textBody
                                    )
                                }
                                Text(
                                    text = getString(R.string.login_phone_prefix),
                                    fontSize = 16.sp,
                                    color = HaloTheme.colors.textTitle,
                                    modifier = Modifier.constrainAs(prefix) {
                                        start.linkTo(parent.start)
                                        top.linkTo(parent.top)
                                        bottom.linkTo(parent.bottom)
                                    })
                                if (mBindPhoneNumber.text.isNotEmpty()) {
                                    Icon(
                                        painter = painterResource(id = R.drawable.icon_input_close),
                                        null,
                                        tint = Color.Unspecified,
                                        modifier = Modifier
                                            .size(16.dp)
                                            .constrainAs(closeIcon) {
                                                end.linkTo(parent.end, 16.dp)
                                                top.linkTo(parent.top)
                                                bottom.linkTo(parent.bottom)
                                            }
                                            .clickableWithoutRipple {
                                                mBindPhoneNumber = mBindPhoneNumber.empty()
                                            }
                                    )
                                }
                            }

                            Spacer(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(1.dp)
                                    .background(HaloTheme.colors.background)
                            )
                        }
                    }
                )

                if (mShowPhoneNumberError) {
                    Space(12.dp)
                    Text(
                        text = "请输入11位手机号",
                        fontSize = 11.sp,
                        color = Color(0XFFF10000)
                    )
                }

                if (mShowCaptcha) {
                    LaunchedEffect(Unit) {
                        captchaFocusRequester.requestFocus()
                        delay(100)
                        input?.showSoftwareKeyboard()
                    }

                    Space(12.dp)
                    BasicTextField(
                        value = mCaptcha,
                        onValueChange = {
                            val numberFilter = it.filter { c -> c.isDigit() }
                            mCaptcha = if (numberFilter.length > 8) numberFilter.substring(0, 8) else numberFilter
                            mBindPhoneBtnEnable = mCaptcha.length > 5
                        },
                        singleLine = true,
                        textStyle = TextStyle(fontSize = 16.sp, color = HaloTheme.colors.textTitle),
                        cursorBrush = SolidColor(HaloTheme.colors.theme),
                        keyboardOptions = KeyboardOptions(
                            keyboardType = KeyboardType.Number,
                            imeAction = ImeAction.Done
                        ),
                        modifier = Modifier
                            .focusRequester(captchaFocusRequester)
                            .fillMaxWidth()
                            .height(48.dp),
                        decorationBox = { innerTextField ->
                            Column(modifier = Modifier.fillMaxSize()) {
                                ConstraintLayout(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(47.dp)
                                ) {
                                    val (textField, getCaptcha) = createRefs()
                                    Box(modifier = Modifier.constrainAs(textField) {
                                        top.linkTo(parent.top)
                                        start.linkTo(parent.start)
                                        bottom.linkTo(parent.bottom)
                                        end.linkTo(parent.end)
                                        width = Dimension.matchParent
                                        height = Dimension.matchParent
                                    }, contentAlignment = Alignment.CenterStart) {
                                        innerTextField()
                                        if (mCaptcha.isEmpty()) Text(
                                            text = getString(R.string.input_captcha_hint),
                                            fontSize = 16.sp,
                                            color = HaloTheme.colors.textBody
                                        )
                                    }
                                    Text(text = mGetCaptchaBtnText,
                                        color = if (mCaptchaCountDown) Color(0XFFB3B3B3) else HaloTheme.colors.themeFont,
                                        fontSize = 14.sp,
                                        modifier = Modifier
                                            .constrainAs(getCaptcha) {
                                                top.linkTo(parent.top)
                                                bottom.linkTo(parent.bottom)
                                                end.linkTo(parent.end, 16.dp)
                                            }
                                            .clickableWithoutRipple(mGetCaptchaBtnClick)
                                    )
                                }

                                Spacer(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(1.dp)
                                        .background(HaloTheme.colors.background)
                                )
                            }
                        }
                    )
                }

                if (mShowCaptchaError) {
                    Space(12.dp)
                    Text(
                        text = "验证码错误",
                        fontSize = 11.sp,
                        color = Color(0XFFF10000)
                    )
                }

                if (mShowInviteCode) {
                    Space(12.dp)
                    BasicTextField(
                        value = mInviteCode,
                        onValueChange = {
                            mInviteCode = it
                        },
                        singleLine = true,
                        textStyle = TextStyle(fontSize = 16.sp, color = HaloTheme.colors.textTitle),
                        cursorBrush = SolidColor(HaloTheme.colors.theme),
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(48.dp),
                        decorationBox = { innerTextField ->
                            Column(modifier = Modifier.fillMaxSize()) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(47.dp), contentAlignment = Alignment.CenterStart
                                ) {
                                    innerTextField()
                                    if (mInviteCode.isEmpty()) Text(
                                        text = getString(R.string.input_invite_code_hint),
                                        fontSize = 16.sp,
                                        color = HaloTheme.colors.textBody
                                    )
                                }

                                Spacer(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(1.dp)
                                        .background(HaloTheme.colors.background)
                                )
                            }
                        }
                    )
                }
            }

            Box(
                modifier = Modifier
                    .height(44.dp)
                    .alpha(if (mBindPhoneBtnEnable) 1F else 0.4F)
                    .background(
                        Brush.horizontalGradient(listOf(Color(0XFF4BC7FF), HaloTheme.colors.theme)),
                        CircleShape
                    )
                    .constrainAs(bindPhoneBtn) {
                        top.linkTo(bindPhoneContainer.bottom, 40.dp)
                        start.linkTo(parent.start, 40.dp)
                        end.linkTo(parent.end, 40.dp)
                        width = Dimension.matchParent
                    }
                    .clickableWithoutRipple(mBindPhoneBtnClick), contentAlignment = Alignment.Center
            ) {
                Text(text = mBindPhoneBtnText, color = Color.White, fontSize = 16.sp)
            }

            if (mFromLogin) {
                Text(
                    text = getString(R.string.bind_phone_skip),
                    color = HaloTheme.colors.textSubtitle,
                    fontSize = 14.sp,
                    modifier = Modifier
                        .padding(horizontal = 20.dp, vertical = 17.dp)
                        .constrainAs(skipBtn) {
                            top.linkTo(parent.top)
                            end.linkTo(parent.end)
                        }
                        .clickableWithoutRipple {
                            showBindPhoneDialog()
                        }
                )
            }

        }
    }

    @Composable
    fun BindPhoneConflictPage() {
        ConstraintLayout(modifier = Modifier.fillMaxSize()) {
            val (bindPhoneConflictTitle, bindPhoneConflictDesc, bindPhoneConflictContainer, changePhoneBtn, cancelBtn) = createRefs()

            Text(
                text = getString(R.string.bind_phone_conflict_text),
                fontSize = 22.sp,
                fontWeight = FontWeight.Bold,
                color = if (mIsDarkModeOn) Color.White else Color.Black,
                modifier = Modifier.constrainAs(bindPhoneConflictTitle) {
                    top.linkTo(parent.top, 48.dp)
                    start.linkTo(parent.start, 20.dp)
                    end.linkTo(parent.end, 20.dp)
                    width = Dimension.fillToConstraints
                })

            Text(
                text = "手机号${mConflictPhone}已经绑定在另一个冲突号上，\n冲突号可能是你之前登录的",
                fontSize = 14.sp,
                color = HaloTheme.colors.textSubtitle,
                lineHeight = 22.sp,
                modifier = Modifier.constrainAs(bindPhoneConflictDesc) {
                    top.linkTo(bindPhoneConflictTitle.bottom, 16.dp)
                    start.linkTo(parent.start, 20.dp)
                    end.linkTo(parent.end, 20.dp)
                    width = Dimension.fillToConstraints
                })

            Column(modifier = Modifier.constrainAs(bindPhoneConflictContainer) {
                top.linkTo(bindPhoneConflictDesc.bottom, 32.dp)
                start.linkTo(parent.start, 24.dp)
                end.linkTo(parent.end, 24.dp)
                width = Dimension.matchParent
            }) {
                UserManager.getInstance().userInfoEntity?.run {
                    var userName = name ?: ""
                    if (userName.length == 2) userName = "${userName[0]}*"
                    if (userName.length > 2) userName = "${userName[0]}**${userName[userName.length - 1]}"
                    ConflictCardItem(
                        title = "当前号",
                        userIcon = icon ?: "",
                        userName = userName,
                        desc = "注册方式：${getRegisterType(registerType)}"
                    )
                }
                Space(16.dp)
                mConflictUser.run {
                    ConflictCardItem(
                        title = "冲突号",
                        userIcon = user?.icon ?: "",
                        userName = user?.name ?: "",
                        desc = "注册方式：${getRegisterType(registerType)}"
                    )
                }
                Space(24.dp)
                Column {
                    Row(modifier = Modifier.clickableWithoutRipple {
                        mPopup = true
                    }, verticalAlignment = Alignment.CenterVertically) {
                        Text(
                            text = getString(R.string.bind_phone_conflict_guide),
                            fontSize = 12.sp,
                            color = HaloTheme.colors.themeFont,
                            modifier = Modifier.padding(start = 4.dp, end = 2.dp)
                        )
                        Icon(
                            bitmap = ImageBitmap.imageResource(R.drawable.icon_doubt),
                            contentDescription = null,
                            tint = Color.Unspecified,
                            modifier = Modifier.size(12.dp)
                        )
                    }
                    GuidePopup()
                }
            }

            Box(
                modifier = Modifier
                    .height(44.dp)
                    .background(
                        Brush.horizontalGradient(listOf(Color(0XFF4BC7FF), HaloTheme.colors.theme)),
                        CircleShape
                    )
                    .constrainAs(changePhoneBtn) {
                        top.linkTo(bindPhoneConflictContainer.bottom, 80.dp)
                        start.linkTo(parent.start, 40.dp)
                        end.linkTo(parent.end, 40.dp)
                        width = Dimension.matchParent
                    }
                    .clickableWithoutRipple {
                        finish()
                    }, contentAlignment = Alignment.Center
            ) {
                Text(text = getString(R.string.bind_phone_conflict_change), color = Color.White, fontSize = 16.sp)
            }

            Text(
                text = getString(R.string.bind_phone_conflict_cancel),
                fontSize = 14.sp,
                color = HaloTheme.colors.textSubtitle,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .padding(horizontal = 20.dp)
                    .height(44.dp)
                    .wrapContentHeight(Alignment.CenterVertically)
                    .constrainAs(cancelBtn) {
                        top.linkTo(changePhoneBtn.bottom)
                        start.linkTo(parent.start, 40.dp)
                        end.linkTo(parent.end, 40.dp)
                        width = Dimension.matchParent
                    }
                    .clickableWithoutRipple {
                        setResult(RESULT_FINISH_CODE)
                        finish()
                    })
        }
    }

    @Composable
    fun ConflictCardItem(title: String, userIcon: String, userName: String, desc: String) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .height(100.dp),
            shape = RoundedCornerShape(4.dp),
            elevation = 4.dp,
            color = HaloTheme.colors.backgroundWhite
        ) {
            Column(modifier = Modifier.padding(start = 24.dp, top = 16.dp)) {
                Text(text = title, fontSize = 14.sp, color = HaloTheme.colors.textTitle, fontWeight = FontWeight.Bold)
                Space(8.dp)
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(40.dp)
                ) {
                    AndroidView(factory = {
                        SimpleDraweeView(it).apply {
                            val builder = GenericDraweeHierarchyBuilder(it.resources)
                            hierarchy = builder.setFadeDuration(500)
                                .setPlaceholderImage(R.drawable.occupy)
                                .setPlaceholderImageScaleType(ScalingUtils.ScaleType.FIT_XY)
                                .setRoundingParams(RoundingParams.asCircle().apply {
                                    borderColor = R.color.divider.toColor(it)
                                    borderWidth = 1F.dip2px().toFloat()
                                })
                                .build()
                            ImageUtils.display(this, userIcon)
                        }
                    }, modifier = Modifier.size(40.dp))
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(start = 8.dp)
                    ) {
                        Text(text = userName, fontSize = 13.sp, color = HaloTheme.colors.textTitle)
                        Space(8.dp)
                        Text(text = desc, fontSize = 11.sp, color = HaloTheme.colors.textSubtitleDesc)
                    }
                }
            }
        }
    }

    @Composable
    fun GuidePopup() {
        if (mPopup) {
            Popup(offset = IntOffset((-9F).dip2px(), 10F.dip2px()), onDismissRequest = {
                mPopup = false
            }) {
                Column(
                    modifier = Modifier
                        .width(330.dp)
                        .paint(painterResource(id = R.drawable.bg_doubt), contentScale = ContentScale.FillBounds),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Space(35.dp)
                    Text(
                        text = getString(R.string.bind_phone_conflict_guide_content1),
                        fontSize = 12.sp,
                        lineHeight = 18.sp,
                        color = HaloTheme.colors.textTitle
                    )
                    Space(16.dp)
                    Text(
                        text = getString(R.string.bind_phone_conflict_guide_content2),
                        fontSize = 12.sp,
                        lineHeight = 18.sp,
                        color = HaloTheme.colors.textTitle
                    )
                    Space(16.dp)
                    Text(
                        text = getString(R.string.bind_phone_conflict_guide_content3),
                        fontSize = 12.sp,
                        lineHeight = 18.sp,
                        color = HaloTheme.colors.textTitle
                    )
                    Space(35.dp)
                }
            }
        }
    }

    private fun getRegisterType(type: String?): String {
        return when (type) {
            "qq" -> "QQ"
            "wechat" -> "微信"
            "weibo" -> "微博"
            "douyin" -> "抖音"
//                    "mobile" -> "手机"
            else -> "手机"
        }
    }

    companion object {
        const val RESULT_FINISH_CODE = 411
        private const val KEY_IS_CONFLICT = "is_conflict"

        @JvmStatic
        fun getNormalIntent(context: Context, isChangePhone: Boolean): Intent {
            return getIntent(context, isFromLogin = false, isChangePhone = isChangePhone)
        }

        // 第三方登录成功跳转绑定手机专用
        @JvmStatic
        fun getLoginSuccessIntent(context: Context): Intent {
            return getIntent(context, isFromLogin = true, isChangePhone = false)
        }

        @JvmStatic
        fun getIntent(context: Context, isFromLogin: Boolean, isChangePhone: Boolean): Intent {
            return Intent(context, ComposeBindPhoneActivity::class.java).apply {
                putExtra(KEY_IS_CONFLICT, false)
                putExtra(EntranceConsts.KEY_FROM_LOGIN, isFromLogin)
                putExtra(EntranceConsts.KEY_CHANGE_PHONE, isChangePhone)
            }
        }

        @JvmStatic
        fun getBindPhoneConflictIntent(context: Context, phoneNum: String, conflictUser: ConflictUserEntity): Intent {
            return Intent(context, ComposeBindPhoneActivity::class.java).apply {
                putExtra(KEY_IS_CONFLICT, true)
                putExtra(EntranceConsts.KEY_CONFLICT_PHONE, phoneNum)
                putExtra(EntranceConsts.KEY_CONFLICT_USER, conflictUser)
            }
        }
    }
}