package com.rdiot.yx485.ui.mine

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.ContextCompat
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
import com.drake.net.component.Progress
import com.drake.net.interfaces.ProgressListener
import com.drake.net.utils.scopeDialog
import com.github.gzuliyujiang.imagepicker.ActivityBuilder
import com.github.gzuliyujiang.imagepicker.CropImageView
import com.github.gzuliyujiang.imagepicker.ImagePicker
import com.github.gzuliyujiang.imagepicker.PickCallback
import com.google.android.material.snackbar.Snackbar
import com.gyf.immersionbar.ktx.immersionBar
import com.gyf.immersionbar.ktx.setFitsSystemWindows
import com.king.zxing.util.LogUtils
import com.lindroy.iosdialog.IAlertDialog
import com.lindroy.iosdialog.IBottomListDialog
import com.rdiot.yx485.BuildConfig
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseActivity
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.bean.UserData
import com.rdiot.yx485.databinding.ActUserInfoBinding
import com.rdiot.yx485.net.*
import com.rdiot.yx485.ui.login.LoginActivity
import com.rdiot.yx485.ui.login.SetPwdActivity
import com.rdiot.yx485.ui.main.MainActivity
import com.rdiot.yx485.util.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


/**
 * 用户信息管理页面
 * @author mR2hao
 * @date 2022/12/7
 */
class UserInfoActivity : BaseActivity<ActUserInfoBinding>() {
    override fun getLayoutId() = R.layout.act_user_info
    private lateinit var userData: UserData
    private var dialog: IAlertDialog? = null

    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            statusBarView(binding.v)
            statusBarColor(R.color.white)
            navigationBarColor(R.color.main_bg_color)
            statusBarDarkFont(true)
        }
        LocalData.userData.observe(this) { data ->
            if (data == null) {
                finish()
                return@observe
            }
            userData = data
            binding.userData = data

            val imgUrl = "${LocalData.apiHost.avatarHost}${userData.photo}"
            binding.ivAvatar.circleImg(imgUrl)

        }


        binding.nb.setLeftClickListener { finish() }

        binding.llAvatar.setClickLimitListener(clickLimitListener)
        binding.llUserName.setClickLimitListener(clickLimitListener)
        binding.llPhone.setClickLimitListener(clickLimitListener)
        binding.llChangePwd.setClickLimitListener(clickLimitListener)
        binding.llLogOutAccount.setClickLimitListener(clickLimitListener)

        binding.btnSignOut.setClickLimitListener(clickLimitListener)
    }


    private val clickLimitListener = object : ClickLimitListener {
        override fun onClickLimit(view: View) {
            binding.apply {
                when (view) {
                    llAvatar -> {
                        showPicWayBottomListDialog()
                    }
                    llUserName -> {
                        showEditNameDialog()
                    }
                    llPhone -> {

                    }
                    llChangePwd -> {
                        LocalData.userData.value?.let { userData ->
                            if (userData.setPwd) {
                                clearGoTo(getClearTopIntent(LoginActivity::class.java).apply {
                                    putExtra(LoginActivity.RESET_PWD, true)
                                })
                                LogUtils.e("重置密码")
                            } else {
                                clearGoTo(SetPwdActivity::class.java)
                                LogUtils.e("设置密码")
                            }
                        }
                    }
                    llLogOutAccount -> {    //注销
                        showWarningDialog()
                    }
                    btnSignOut -> { //退出登录
                        scopeDialog(cancelable = BuildConfig.DEBUG) {
                            try {
                                signOut().await()
                            } catch (_: Exception) {

                            } finally {
                                delay(500)
                                finishGoTo(MainActivity::class.java)
                                LocalData.logout()
                            }
                        }
                    }
                }
            }

        }

    }

    private val cropCallback: PickCallback = object : PickCallback() {
        override fun onPermissionDenied(permissions: Array<String>, message: String) {
            LogUtils.e("权限不足 $message")
        }

        override fun cropConfig(builder: ActivityBuilder) {
            builder.setMultiTouchEnabled(true)
                .setGuidelines(CropImageView.Guidelines.ON_TOUCH)
                .setRequestedSize(400, 400)
                .setFixAspectRatio(true)
                .setAspectRatio(1, 1)
        }

        override fun onCropImage(imageUri: Uri?) {
            LogUtils.d("路径：${imageUri.toString()}")
            imageUri?.let { uri ->
                scopeDialog(cancelable = BuildConfig.DEBUG) {
                    try {
                        uploadAvatar(uri, object : ProgressListener() {
                            override fun onProgress(p: Progress) {
                                LogUtils.d("上传进度：${p.progress()}")
                            }
                        }).await().also {
                            userData.photo = it.url
                            updateUserData()
                        }
                    } catch (e: Exception) {
                        LogUtils.e("${e.message}")
                    }
                }
            }

        }
    }

    private fun showHint() {
        LocalData.firstCamera = true
        dialog?.dismiss()
        dialog = IAlertDialog.build(this)
            .setTitle("相机权限使用说明")
            .setMessage("用于拍照、录制视频、扫描二维码等场景")
            .setNegButtonText(R.string.cancel)
            .setCancelOutside(false)
            .setNegClickListener {
                return@setNegClickListener
            }
            .setAlpha(1.0F)
//            .setPosButtonText(R.string.go_setting)
            .setPosClickListener {
                askPermission()
            }
        dialog?.show()
    }

    private fun askPermission() {
        askPermission(false) { allGranted: Boolean?, _: MutableList<String>? ->
            if (allGranted == true) {
                ImagePicker.getInstance().startCamera(this, true, cropCallback)
            } else {
                showNeedPermissionDialog(allGranted)
            }
        }
    }

    /** 弹窗提示选择 0拍照 1相册 */
    private fun showPicWayBottomListDialog() {
        IBottomListDialog.build(this)
            .setTitle(R.string.set_avatar)
            .addItems(listOf(getString(R.string.take_photo), getString(R.string.photo_album)))
            .setOnItemClickListener { position, _, _, _ ->
                if (position == 0) {
                    if (LocalData.firstCamera){
                        showHint()
                    }else {
                        askPermission()
                    }
                } else if (position == 1) {
                    ImagePicker.getInstance().startGallery(this, true, cropCallback)
                }
            }
            .show()
    }

    private fun showNeedPermissionDialog(allGranted: Boolean?) {
        dialog?.dismiss()
        dialog = IAlertDialog.build(this)
            .setTitle(R.string.hint)
            .setMessage(R.string.need_allow_take_photo)
            .setNegButtonText(R.string.cancel)
            .setCancelOutside(false)
            .setNegClickListener {
            }
            .setAlpha(1.0F)
            .setPosButtonText(R.string.go_setting)
            .setPosClickListener {
                goToAppSetting(true)
            }
        dialog?.show()
    }

    private fun showWarningDialog() {
        dialog?.dismiss()
        dialog = IAlertDialog.build(this)
            .setTitle(R.string.hint)
            .setMessage(R.string.log_out_hint)
            .setNegButtonText(R.string.cancel)
            .setNegButtonTextColor(resources.getColor(R.color.main_text_color, null))
            .setAlpha(1.0F)
            .setPosButtonText(R.string.log_out_account)
            .setPosButtonTextColor(resources.getColor(R.color.warning, null))
            .setPosClickListener {
                scopeDialog(cancelable = BuildConfig.DEBUG) {
                    logOut().await()
                    delay(500)
                    finishGoTo(MainActivity::class.java)
                    LocalData.logout()
                }
            }
        dialog?.show()
    }

    private fun showEditNameDialog() {
        val title = getString(R.string.set_user_name)
        val text = userData.userName
        val hint = getString(R.string.user_name)
        var inputText = ""
        dialog?.dismiss()
        dialog = IAlertDialog
            .build(this)
            .setTitle(title)
            .setContentView(R.layout.dialog_simple_edit)
            .setCancelOutside(false)
            .setNegButtonText(R.string.cancel)
            .setNegButtonTextColor(resources.getColor(R.color.main_text_color, null))
            .setNegClickListener { dialogInterface ->
                dialogInterface.dismiss()
            }
            .setPosClickListener { dialogInterface ->
                dialogInterface.dismiss()
                userData.userName = inputText
                updateUserData()
//                LogUtils.e(inputText)
            }
            .setDismissible(false)
            .setAlpha(1.0F)
            .setPosButtonTextColor(resources.getColor(R.color.btn_blue, null))
            .setOnViewHandler { holder, _ ->
                lifecycleScope.launch {
                    (holder.getView(R.id.et) as AppCompatEditText).apply {
                        setText(text)
                        setHint(hint)

                        //延时弹出键盘
                        delay(300)
                        setSelection(text.length)
                        requestFocus()
                        val inputManager = this@UserInfoActivity.getSystemService(
                            Context.INPUT_METHOD_SERVICE
                        ) as InputMethodManager
                        inputManager.showSoftInput(this, 0)

                        doAfterTextChanged {
                            inputText = it.toString()
                        }
                    }

                }
            }
        dialog?.show()
    }

    private fun updateUserData() {
        scopeDialog(cancelable = BuildConfig.DEBUG) {
            updateUserData(userData).await()
            getCurrentUserData().await().also {
                LocalData.userData.postValue(it)
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        ImagePicker.getInstance().onActivityResult(this, requestCode, resultCode, data)
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        ImagePicker.getInstance()
            .onRequestPermissionsResult(this, requestCode, permissions, grantResults)
    }
}