package com.mints.goodmoney.ui.activitys

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import com.mints.goodmoney.R
import com.mints.goodmoney.common.Constant
import com.mints.goodmoney.login.LoginApi
import com.mints.goodmoney.login.OnLoginListener
import com.mints.goodmoney.manager.UserManager
import com.mints.goodmoney.mvp.model.DrawcashBean
import com.mints.goodmoney.mvp.model.WXInfo
import com.mints.goodmoney.mvp.presenters.SettingsPresenter
import com.mints.goodmoney.mvp.views.SettingsView
import com.mints.goodmoney.ui.activitys.base.BaseActivity
import com.mints.goodmoney.ui.widgets.CustomDialogAsApple
import com.mints.goodmoney.ui.widgets.DialogListener
import com.mints.goodmoney.utils.CacheUtil
import com.mints.library.utils.json.JsonUtil
import kotlinx.android.synthetic.main.activity_settings.*
import kotlinx.android.synthetic.main.header_layout.*
import java.util.*

class SettingsActivity : BaseActivity(), View.OnClickListener, OnLoginListener, SettingsView {

    private lateinit var cdaa: CustomDialogAsApple
    private val userManager by lazy { UserManager.getInstance() }
    private val settingsPresenter by lazy { SettingsPresenter() }
    private val loginApi by lazy { LoginApi() }
    private var wxInfo: WXInfo? = null

    override fun initViewsAndEvents() {
        settingsPresenter.attachView(this)

        initLayout()
    }

    override fun onResume() {
        super.onResume()

        if (userManager.mobile.isNotEmpty()) {
            item_phone.findViewById<TextView>(R.id.tv_right).text = userManager.mobile
        } else {
            item_phone.findViewById<TextView>(R.id.tv_right).text = "未绑定"
        }

//        if (userManager.wxOpenid.isNotEmpty()) {
//            item_wechat.findViewById<TextView>(R.id.tv_right).text = userManager.wxName
//        } else {
//            item_wechat.findViewById<TextView>(R.id.tv_right).text = "未授权"
//        }
    }

    private fun initLayout() {
        if (!userManager.userIsLogin()) {
            btn_switch.visibility = View.GONE
        }

        tv_title.text = "设置"
        iv_left_icon.visibility = View.VISIBLE
        iv_left_icon.setImageResource(R.mipmap.ic_arrow_back)
        iv_left_icon.setOnClickListener(this)

        item_phone.setOnClickListener(this)
        item_wechat.setOnClickListener(this)
        item_invitedCode.setOnClickListener(this)
        item_cleanCache.setOnClickListener(this)
        item_userAgree.setOnClickListener(this)
        item_privacyAgree.setOnClickListener(this)
        item_aboutUs.setOnClickListener(this)
        btn_switch.setOnClickListener(this)

        item_phone.findViewById<TextView>(R.id.tv_title).text = "手机号"
        val phone = resources.getDrawable(R.mipmap.icon_settings_tel)
        phone.setBounds(0, 0, 56, 56)
        item_phone.findViewById<TextView>(R.id.tv_title).setCompoundDrawables(phone, null, null, null)
        item_phone.findViewById<TextView>(R.id.tv_right).visibility = View.VISIBLE
        item_phone.findViewById<ImageView>(R.id.iv_right).visibility = View.GONE
        if (userManager.mobile.isNotEmpty()) {
            item_phone.findViewById<TextView>(R.id.tv_right).text = userManager.mobile
        } else {
            item_phone.findViewById<TextView>(R.id.tv_right).text = "未绑定"
        }

        item_wechat.findViewById<TextView>(R.id.tv_title).text = "微信昵称"
        val wechat = resources.getDrawable(R.mipmap.icon_settings_wechat)
        wechat.setBounds(0, 0, 56, 56)
        item_wechat.findViewById<TextView>(R.id.tv_title).setCompoundDrawables(wechat, null, null, null)
        item_wechat.findViewById<TextView>(R.id.tv_right).visibility = View.VISIBLE
        item_wechat.findViewById<ImageView>(R.id.iv_right).visibility = View.GONE
        if (userManager.wxOpenid.isNotEmpty()) {
            item_wechat.findViewById<TextView>(R.id.tv_right).text = userManager.wxName
        } else {
            item_wechat.findViewById<TextView>(R.id.tv_right).text = "未授权"
        }

//        item_invitedCode.findViewById<TextView>(R.id.tv_title).text = "邀请码"
//        val invitedCode = resources.getDrawable(R.mipmap.icon_settings_invite)
//        invitedCode.setBounds(0, 0, 56, 56)
//        item_invitedCode.findViewById<TextView>(R.id.tv_title).setCompoundDrawables(invitedCode, null, null, null)
//        item_invitedCode.findViewById<TextView>(R.id.tv_right).visibility = View.VISIBLE
//        item_invitedCode.findViewById<ImageView>(R.id.iv_right).visibility = View.GONE
//        item_invitedCode.findViewById<TextView>(R.id.tv_right).text = "填写邀请码 海量金币等你拿"

        item_cleanCache.findViewById<TextView>(R.id.tv_title).text = "清理缓存"
        val cleanCache = resources.getDrawable(R.mipmap.icon_settings_clean)
        cleanCache.setBounds(0, 0, 56, 56)
        item_cleanCache.findViewById<TextView>(R.id.tv_title).setCompoundDrawables(cleanCache, null, null, null)
        item_cleanCache.findViewById<TextView>(R.id.tv_right).visibility = View.VISIBLE
        item_cleanCache.findViewById<ImageView>(R.id.iv_right).visibility = View.GONE
        item_cleanCache.findViewById<TextView>(R.id.tv_right).text = CacheUtil.getTotalCacheSize(this)

        item_userAgree.findViewById<TextView>(R.id.tv_title).text = "服务协议"
        val userAgree = resources.getDrawable(R.mipmap.icon_settings_user)
        userAgree.setBounds(0, 0, 56, 56)
        item_userAgree.findViewById<TextView>(R.id.tv_title).setCompoundDrawables(userAgree, null, null, null)
        item_userAgree.findViewById<TextView>(R.id.tv_right).visibility = View.GONE
        item_userAgree.findViewById<ImageView>(R.id.iv_right).visibility = View.VISIBLE

        item_privacyAgree.findViewById<TextView>(R.id.tv_title).text = "隐私协议"
        val privacyAgree = resources.getDrawable(R.mipmap.icon_settings_privacy)
        privacyAgree.setBounds(0, 0, 56, 56)
        item_privacyAgree.findViewById<TextView>(R.id.tv_title).setCompoundDrawables(privacyAgree, null, null, null)
        item_privacyAgree.findViewById<TextView>(R.id.tv_right).visibility = View.GONE
        item_privacyAgree.findViewById<ImageView>(R.id.iv_right).visibility = View.VISIBLE

        item_aboutUs.findViewById<TextView>(R.id.tv_title).text = "关于我们"
        val aboutUs = resources.getDrawable(R.mipmap.icon_settings_about)
        aboutUs.setBounds(0, 0, 56, 56)
        item_aboutUs.findViewById<TextView>(R.id.tv_title).setCompoundDrawables(aboutUs, null, null, null)
        item_aboutUs.findViewById<TextView>(R.id.tv_right).visibility = View.GONE
        item_aboutUs.findViewById<ImageView>(R.id.iv_right).visibility = View.VISIBLE
    }

    override fun getContentViewLayoutID() = R.layout.activity_settings

    override fun isApplyKitKatTranslucency() = false

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.item_phone -> {
                if (userManager.mobile.isEmpty()) {
                    val bundle = Bundle()
                    bundle.putBoolean(Constant.LOGIN_FLAG, true)
                    readyGo(LoginActivity::class.java, bundle)
                }
            }
            R.id.item_wechat -> {
                if (userManager.wxOpenid.isEmpty()) {

                    val wechat = ShareSDK.getPlatform(Wechat.NAME)
                    if (!wechat.isClientValid) {
                        showToast("请先安装微信")
                        return
                    }

                    loginApi.setOnLoginListener(this)
                    loginApi.setPlatform(Wechat.NAME)
                    loginApi.login(this)
                }
            }
            R.id.item_invitedCode -> {
                submitInvitedCode()
            }
            R.id.item_cleanCache -> {
                clearDialog()
            }
            R.id.item_userAgree -> {
                val bundle = Bundle()
                bundle.putString(WebActivity.WEB_TITLE, getString(R.string.register_name))
                bundle.putString(WebActivity.WEB_URL, Constant.REGISTER_URL)
                readyGo(WebActivity::class.java, bundle)
            }
            R.id.item_privacyAgree -> {
                val bundle = Bundle()
                bundle.putString(WebActivity.WEB_TITLE, getString(R.string.privacy_name))
                bundle.putString(WebActivity.WEB_URL, Constant.PRIVACY_URL)
                readyGo(WebActivity::class.java, bundle)
            }
            R.id.item_aboutUs -> {
                readyGo(AboutusActivity::class.java)
            }
            R.id.btn_switch -> {
//                readyGo(LoginActivity::class.java)
                backDialog()
            }
            R.id.iv_left_icon -> {
                onBackPressed()
            }
        }
    }

    private fun backDialog() {
        cdaa = CustomDialogAsApple(context, object : DialogListener() {
           override fun onClick(v: View) {
                if (cdaa != null && cdaa.isShowing()) {
                    cdaa.dismiss()
                }
                when (v.id) {
                    R.id.dialog_btn_left -> {
                        UserManager.getInstance().userLogout()
                        readyGoThenKill(MainActivity::class.java)
                    }
                }
            }
        })
        cdaa.setContent("确定要退出登录吗？")
        cdaa.setLeft("确定")
        cdaa.setRight("取消")
        cdaa.show()
    }

    private fun submitInvitedCode() {
        val view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_invite, null)
        val etInput = view.findViewById<EditText>(R.id.et_input)

        val dialog = AlertDialog.Builder(this)
                .setTitle("请输入邀请码")
                .setPositiveButton("确定") { dialog, which ->
                    if (etInput.text.isEmpty()) {
                        showToast("请输入邀请码")
                    } else {
                        dialog.dismiss()
                    }

                }
                .setNegativeButton("取消") { dialog, which ->
                    dialog.dismiss()
                }
                .create()
        dialog.setOnShowListener {
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(etInput, InputMethodManager.SHOW_IMPLICIT)
        }

        dialog.setView(view)

//        val window = dialog.window
//        window?.setGravity(Gravity.CENTER)
//        window?.setWindowAnimations(R.style.DialogAnimBottom)
        dialog.show()
    }

    private fun clearDialog() {
        val dialog = AlertDialog.Builder(this)
                .setTitle("确定清除缓存吗?")
                .setPositiveButton("确定") { dialog, _ ->
                    try {
                        CacheUtil.clearAllCache(context)
                        item_cleanCache.findViewById<TextView>(R.id.tv_right).text = "0KB"
                    } catch (e: Exception) {
                        e.printStackTrace()
                    } finally {
                        dialog.dismiss()
                    }

                }
                .setNegativeButton("取消") { dialog, _ ->
                    dialog.dismiss()
                }
                .create()

        val window = dialog.window
        window?.setGravity(Gravity.CENTER)
        window?.setWindowAnimations(R.style.DialogAnimBottom)

        dialog.show()
    }

    override fun onLogin(platform: String?, res: HashMap<String, Any>): Boolean {
        try {
            wxInfo = WXInfo()
            wxInfo?.let {
                it.setUnionid(res["unionid"].toString() + "")
                it.setOpenid(res["openid"].toString() + "")
                it.setProvince(res["province"].toString() + "")
                it.setCity(res["city"].toString() + "")
                it.setCountry(res["country"].toString() + "")
                it.setHeadimgurl(res["headimgurl"].toString() + "")
                it.setNickname(res["nickname"].toString() + "")
                it.setSex((res["sex"].toString() + "").toInt())
            }

            if (!isFinishing) {
                settingsPresenter.editUserMsg(JsonUtil.toJson(wxInfo))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    override fun editUserMsgSuc() {
        showToast("微信授权成功")

        settingsPresenter.getUserTaskMsg()
    }

    override fun getUserTaskMsgSuc(data: DrawcashBean) {
        item_wechat.findViewById<TextView>(R.id.tv_right).text = data.nickName
    }
}