package com.yidianling.user.mine

import android.annotation.SuppressLint
import android.text.Editable
import android.text.Spannable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.util.TypedValue.COMPLEX_UNIT_SP
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import com.alibaba.android.arouter.launcher.ARouter
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.data.http.BaseAPIResponse
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.utils.extend.visible
import com.ydl.ydlcommon.view.DeleteEditTextView
import com.ydl.ydlcommon.view.TitleBar
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.api.service.IImService
import com.yidianling.user.R
import com.yidianling.user.api.bean.UserResponseBean
import com.yidianling.user.api.service.IUserService
import com.yidianling.user.http.UserHttpImpl.Companion.getInstance
import com.yidianling.user.http.request.BaseInfo
import com.yidianling.user.http.request.ModifyBaseInfo
import com.yidianling.user.http.request.UserModifyAuditRespDto
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * 昵称修改
 * 简介修改
 */
const val NICKNAME = 1
const val INTRODUCTION = 2

class ModifyInfoActivity : BaseActivity() {

    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(isAddStatusView = true, statusBarDarkMode = true)
    }

    private val mShake: Animation by lazy {
        AnimationUtils.loadAnimation(this, R.anim.user_mine_shake)
    }

    private lateinit var det_set_info: DeleteEditTextView
    private lateinit var tv_tip1: TextView
    private lateinit var tv_tip2: TextView
    private lateinit var tb_title_bar: TitleBar
    private lateinit var iv_warn: ImageView

    override fun layoutResId(): Int = R.layout.activity_modify_info

    private fun findView() {
        det_set_info = findViewById(R.id.det_set_info)
        tv_tip1 = findViewById(R.id.tv_tip1)
        tv_tip2 = findViewById(R.id.tv_tip2)
        tb_title_bar = findViewById(R.id.tb_title_bar)
        iv_warn = findViewById(R.id.iv_warn)
    }

    @SuppressLint("SetTextI18n")
    override fun initDataAndEvent() {
        findView()
        val from = intent.getIntExtra("from", 0)
        val userInfo = findRouteService(IUserService::class.java).getUserInfo()
        userInfo ?: return
        if (INTRODUCTION == from) {
            tb_title_bar.title = "简介"
            det_set_info.layoutParams.height = RxImageTool.dp2px(180f)
            det_set_info.hint = "一句话介绍下自己"
            det_set_info.setShowDelete(false)
            det_set_info.setTextSize(COMPLEX_UNIT_SP, 14f)
            det_set_info.gravity = Gravity.START
        }
        tb_title_bar.setOnLeftTextClick { _, _ ->
            setResult(RESULT_OK) // 刷新个人资料页
            finish()
        }
        mDisposables.add(
            getInstance().getUserAuditInfo(BaseInfo(if (NICKNAME == from) 101 else 103))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { response: BaseAPIResponse<UserModifyAuditRespDto> ->
                    if (response.code != "200") return@subscribe
                    val (auditReason, auditStatus, _, _, _, _, _, last7Day, modifyAfter) = response.data
                    if (NICKNAME == from) {
                        when (auditStatus) {
                            1 -> { // 审核中
                                tv_tip1.visible()
                                tv_tip1.text = "抱歉，七天内只能修改一次昵称"
                                setCanNotSave()
                                setEditText(modifyAfter, "昵称审核中，预计24小时内审核完成")
                                tv_tip2.visible()
                                tv_tip2.text = "昵称审核中，预计24小时内审核完成，暂无法修改。"
                            }
                            2 -> { // 审核失败
                                tv_tip1.visible()
                                tv_tip1.text = "七天内可修改一次昵称"
                                checkNickSaveButton(userInfo)
                                det_set_info.setText(userInfo.nick_name)
                                iv_warn.visible()
                                customerService("审核失败 ，$auditReason。如有疑问联系客服小壹")
                            }
                            3 -> { // 审核成功 || 提交审核
                                modifyAfter?.let { nick ->
                                    userInfo.nick_name = nick
                                    findRouteService(IImService::class.java).updateUserName(nick) // 更新用户昵称到云信
                                }
                                if (last7Day) {
                                    tv_tip1.visible()
                                    tv_tip1.text = "抱歉，七天内只能修改一次昵称"
                                    setCanNotSave()
                                    setEditText(modifyAfter, "抱歉，七天内只能修改一次")
                                } else {
                                    tv_tip1.visible()
                                    tv_tip1.text = "七天内可修改一次昵称"
                                    checkNickSaveButton(userInfo)
                                    det_set_info.setText(modifyAfter)
                                }
                            }
                        }
                    } else if (INTRODUCTION == from) {
                        when (auditStatus) {
                            1 -> { // 审核中
                                setCanNotSave()
                                setEditText(modifyAfter, "简介审核中，预计24小时内审核完成")
                                tv_tip2.visible()
                                tv_tip2.text = "审核中，预计24小时内审核完成，暂无法修改"
                            }
                            2 -> { // 审核失败
                                setCanSave()
                                det_set_info.setText(userInfo.description)
                                iv_warn.visible()
                                customerService("审核失败，$auditReason。如有疑问联系客服小壹")
                            }
                            3 -> { // 审核成功 || 提交审核
                                modifyAfter?.let {
                                    det_set_info.setText(it)
                                    userInfo.description = it
                                }
                                setCanSave()
                            }
                        }
                    }
                })
    }

    /**
     * 客服提示
     */
    private fun customerService(tip: String) {
        tv_tip2.visible()
        tv_tip2.text = SpannableString(tip).also {
            it.setSpan(
                ForegroundColorSpan(resources.getColor(R.color.color_1DA1F2)),
                it.lastIndexOf("客服"),
                it.length,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        tv_tip2.setOnClickListener { // 客服
            ARouter.getInstance().navigation(
                IImService::class.java
            ).startKefuChat(this, "", 0, 0)
        }
    }

    private fun setCanSave() {
        tb_title_bar.setRightTextColor(resources.getColor(R.color.color_1DA1F2))
        tb_title_bar.setOnRightTextClick { _, _ ->
            modifyUserBaseInfo(103) {
                ToastUtil.toastShort("提交成功，简介审核中，预计24小时内审核完成")
                finish()
            }
        }
    }

    private fun setCanNotSave() {
        tb_title_bar.setRightTextEnable(false)
        tb_title_bar.setRightTextColor(resources.getColor(R.color.color_9d9ea7))
    }

    private fun setEditText(text: String?, tip: String) {
        det_set_info.setText(text)
        det_set_info.keyListener = null
        det_set_info.isFocusableInTouchMode = false
        det_set_info.setTextColor(resources.getColor(R.color.color_9d9ea7))
        det_set_info.setOnClickListener {
            ToastUtil.toastShort(tip)
        }
    }

    private fun checkNickSaveButton(userInfo: UserResponseBean.UserInfo) {
        tb_title_bar.setOnRightTextClick { _: View?, _: Boolean ->
            modifyUserBaseInfo(101) {
                ToastUtil.toastShort("提交成功，昵称审核中，预计24小时内审核完成")
                finish()
            }
        }
        det_set_info.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s?.isEmpty() == true || s?.toString() == userInfo.nick_name) {
                    tb_title_bar.setRightTextEnable(false)
                    tb_title_bar.setRightTextColor(resources.getColor(R.color.color_9d9ea7))
                } else {
                    tb_title_bar.setRightTextEnable(true)
                    tb_title_bar.setRightTextColor(resources.getColor(R.color.color_1DA1F2))
                }
            }

            override fun afterTextChanged(s: Editable?) {}

        })
    }

    private fun modifyUserBaseInfo(type: Int, block: () -> Unit) {
        mDisposables.add(
            getInstance().modifyUserBaseInfo(
                ModifyBaseInfo(
                    det_set_info.text.toString(),
                    type
                )
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (it.code == "200") block.invoke()
                    else ToastUtil.toastShort(it.msg)
                }
        )
    }
}