package com.dahe.pass.ui.account

import android.Manifest
import android.os.Bundle
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import com.dahe.mylibrary.base.BaseActivity
import com.dahe.mylibrary.net.CommonResponseBean
import com.dahe.mylibrary.net.JsonUtils
import com.dahe.mylibrary.utils.ActivityUtils
import com.dahe.pass.R
import com.dahe.pass.bean.UserBean
import com.dahe.pass.net.BaseObserver
import com.dahe.pass.net.DataManager
import com.dahe.pass.net.RxHttpCallBack
import com.dahe.pass.ui.HomeActivity
import com.dahe.pass.ui.account.activity.RegisterActivity
import com.dahe.pass.utils.AppActivityUtils
import com.dahe.pass.utils.SPUtils
import kotlinx.android.synthetic.main.activity_login.*
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import java.util.*

class LoginActivity : BaseActivity(), EasyPermissions.PermissionCallbacks, View.OnClickListener {


    var perms = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.CALL_PHONE,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    override fun getLayout(): Int = R.layout.activity_login

    override fun initView(savedInstanceState: Bundle?) {
//        setStatusBarCancelLightColor()
        setStatusBarColor(R.color.white)
        if (!EasyPermissions.hasPermissions(this, *perms)) {
            EasyPermissions.requestPermissions(this@LoginActivity, "您尚有权限未开放，是否获取权限", 2, *perms)
        }


        btn_log.setOnClickListener(this)
        tvForget.setOnClickListener(this)
        tv_yhxy.setOnClickListener(this)
        tv_yszc.setOnClickListener(this)
        tvXyh.setOnClickListener(this)
        tvZc.setOnClickListener(this)
        cb.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                et_pass.setTransformationMethod(PasswordTransformationMethod.getInstance())
            } else {
                et_pass.setTransformationMethod(HideReturnsTransformationMethod.getInstance())
            }
            et_pass.setSelection(et_pass.getText().toString().length)
        }
    }

    override fun initDate() {
//        getCode()
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.btn_log -> {
                if (!EasyPermissions.hasPermissions(this, *perms)) {
                    EasyPermissions.requestPermissions(
                        this@LoginActivity,
                        "您尚有权限未开放，是否获取权限",
                        2,
                        *perms
                    )
                } else {
                    logByPass()
                }

            }
//            R.id.tv_forget -> ActivityUtils.startActivity(mContext, ForgetPwdActivity::class.java)
            R.id.tv_yhxy -> AppActivityUtils.openWebViewActivity(this,
                "用户服务协议",
                "https://downtest.dahehuodongbao.com/passcheck/user-agreement.html");
            R.id.tv_yszc -> AppActivityUtils.openWebViewActivity(this, "隐私政策",
                "https://downtest.dahehuodongbao.com/passcheck/user-privacy.html")

            R.id.tvZc, R.id.tvXyh -> ActivityUtils.startActivity(this, RegisterActivity::class.java)

        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    /**
     * 密码登录
     */
    private fun logByPass() {
        val s: String = et_phone.getText().toString().trim()
        val s1: String = et_pass.getText().toString().trim()
        if (TextUtils.isEmpty(s) || TextUtils.isEmpty(s1)) {
            showToast("请输入账号密码")
            return
        }
//        if (!PatternUtils.isPassword(s1)){
//            showToast("密码格式错误")
//            return
//        }
//        if (et_yzm.text.toString().isEmpty()) {
//            showToast("请输入验证码")
//            return
//        }
//        if (!cb_read.isChecked()) {
//            showToast("请勾选用户协议")
//            return
//        }

        DataManager.getInstance()
            .log(et_phone.getText().toString().trim(), et_pass.getText().toString().trim())
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<UserBean>() {
                override fun onSuccess(t: CommonResponseBean<UserBean>) {
                    super.onSuccess(t)

                    //                            val toJson = JsonUtils.getInstance().getGson().toJson(t.getData())
                    SPUtils.setUserInfo(
                        this@LoginActivity,
                        JsonUtils.getInstance().getGson().toJson(t.getData())
                    )

//                            val freighter = SPUtils.getUserInfo(this@LoginActivity).freighter

                    ActivityUtils.startActivity(this@LoginActivity,
                        HomeActivity::class.java)
                    finish()
                }

            }))

//        DataManager.getInstance().log(et_pass.getText().toString().trim(), et_phone.getText().toString().trim())
//            .subscribeOn(Schedulers.io())
//            .observeOn(AndroidSchedulers.mainThread())
//            .subscribe(
//                BaseObserver<UserBean>(mContext,
//                    object : RxHttpCallBack<UserBean?>(this@LoginActivity) {
//                        override fun onSuccess(t: CommonResponseBean<UserBean?>) {
//                            super.onSuccess(t)
////                            val toJson = JsonUtils.getInstance().getGson().toJson(t.getData())
//                            SPUtils.setUserInfo(
//                                this@LoginActivity,
//                                JsonUtils.getInstance().getGson().toJson(t.getData())
//                            )
//
////                            val freighter = SPUtils.getUserInfo(this@LoginActivity).freighter
//
//                            ActivityUtils.startActivity(this@LoginActivity,
//                                HomeActivity::class.java)
//                            finish()
//                        }
//
//                        override fun onCodeError(mContext: Context?, t: CommonResponseBean<UserBean?>) {
//                            super.onCodeError(mContext, t)
////                            if (t.getCode() != -1) {
////                                getCode()
////                            }
//                        }
//                    })
//            )
    }


    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            AppSettingsDialog.Builder(this).setTitle("获取权限")
                .setRationale("如果没有请求的权限，此应用可能无法正常工作。 打开应用程序设置屏幕以修改应用程序权限").build().show()
        }
    }
}