package com.rehome.bhdxj.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import com.azhon.appupdate.listener.OnButtonClickListener
import com.azhon.appupdate.listener.OnDownloadListener
import com.azhon.appupdate.manager.DownloadManager
import com.rehome.bhdxj.R
import com.rehome.bhdxj.base.BaseActivityAutoToolbarViewBinding
import com.rehome.bhdxj.bean.ApkUpdateBean
import com.rehome.bhdxj.bean.PhoneInfo
import com.rehome.bhdxj.bean.UserInfo
import com.rehome.bhdxj.contans.Contans
import com.rehome.bhdxj.databinding.ActivityLoginBinding
import com.rehome.bhdxj.utils.ControllerActivity
import com.rehome.bhdxj.utils.GsonUtils
import com.rehome.bhdxj.utils.HttpListener
import com.rehome.bhdxj.utils.NetworkUtil
import com.rehome.bhdxj.utils.NohttpUtils
import com.rehome.bhdxj.utils.RSAUtils
import com.rehome.bhdxj.utils.SPUtils
import com.rehome.bhdxj.utils.StatusBarUtil
import com.rehome.bhdxj.utils.UiUtlis
import com.tencent.bugly.crashreport.CrashReport
import com.yolanda.nohttp.NoHttp
import com.yolanda.nohttp.RequestMethod
import com.yolanda.nohttp.rest.Response
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import kotlin.system.exitProcess

/**
 *   Create By HuangWenFei
 *   创建日期：2023-02-06 11:30
 *   描述：登录页面
 */
class LoginActivity : BaseActivityAutoToolbarViewBinding<ActivityLoginBinding>() {

    private lateinit var UserID: String
    private lateinit var UserPwd: String
    private var exitTime: Long = 0

    private var manager: DownloadManager? = null

    override fun getViewBinding() = ActivityLoginBinding.inflate(layoutInflater)

    override fun getToolbar() = binding.toolbarView.toolbar

    @SuppressLint("SetTextI18n")
    override fun initView() {
        binding.tvVersion.text = "版本V" + getVersionName()
        StatusBarUtil.transparencyBar(this) //设置透明状态栏



        val UserIDTemp = SPUtils.get(this, Contans.USERID, "") as String
        val UserPwdTemp = SPUtils.get(this, Contans.USERPWD, "") as String

        val save = SPUtils.get(this, "save", true) as Boolean
        binding.savePwUser.isChecked = save

        if (!TextUtils.isEmpty(UserIDTemp)) {
            UserID = RSAUtils.decryptBASE64StrLocal(UserIDTemp);
            binding.etUse.setText(UserID)
        }else{
            UserID = ""
            UserPwd = ""
            binding.etUse.setText(UserID)
            binding.etPwd.setText(UserPwd);
        }

        //binding.etUse.setText(UserID)
        if (save) {
            //binding.etPwd.setText(UserPwd)
            if (!TextUtils.isEmpty(UserPwdTemp)) {
                UserPwd = RSAUtils.decryptBASE64StrLocal(UserPwdTemp);
                binding.etPwd.setText(UserPwd);
            }
        }

        binding.etUse.setText("870064")
        binding.etPwd.setText("Xdj@2025")

    }

    override fun initData() {
        checkUpdateApk()
        CrashReport.putUserData(context, "UserName", UserID)
        onclick()
    }


    private fun onclick() {
        binding.btnLogin.setOnClickListener(View.OnClickListener {
            if (isCanLogin()) {
                if (NetworkUtil.canNetWorkConnect(context)) {
                    Log.i("app", "有网络")
                    onlineLogin()
                } else {
                    Log.i("app", "无网络")
                    offlineLogin()
                }
            }
        })
    }

    private fun isCanLogin(): Boolean {
        return if (TextUtils.isEmpty(
                binding.etUse.text.toString()
            ) && TextUtils.isEmpty(binding.etPwd.text.toString())
        ) {
            showToast("用户名和密码不能为空")
            false
        } else if (TextUtils.isEmpty(binding.etUse.text.toString())) {
            showToast("用户名不能为空")
            false
        } else if (TextUtils.isEmpty(binding.etPwd.text.toString())) {
            showToast("密码不能为空")
            false
        } else {
            true
        }
    }


    private fun getVersionName(): String? {
        val pm = packageManager
        try {
            val packageInfo = pm.getPackageInfoCompat(packageName)
            return packageInfo.versionName
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    private fun PackageManager.getPackageInfoCompat(
        packageName: String,
        flags: Int = 0
    ): PackageInfo =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flags.toLong()))
        } else {
            @Suppress("DEPRECATION") getPackageInfo(packageName, flags)
        }

    private fun checkUpdateApk() {
        val url = Contans.IP + Contans.CHECK_UPDATA_APK
        val request = NoHttp.createStringRequest(url, RequestMethod.GET)
        NohttpUtils.getInstance().addNoProgress(this,0, request, object : HttpListener<String?> {
            override fun onSucceed(what: Int, response: Response<String?>?) {
                val jsonResult = response?.get()
                showLog("-----checkUpdateApk------")
                //{"Rows":[{"versionname":"1.1.0","versioncode":"110","apkurl":"http://10.46.0.164:8002/Apps/DJ_APP.apk","bz":"","appdesc":"更新内容:Maximo接口地址 "}],"Total":"1"}
                showLog(jsonResult)
                val apkUpdateBean = GsonUtils.GsonToBean(
                    jsonResult,
                    ApkUpdateBean::class.java
                )
                if (apkUpdateBean!=null&&apkUpdateBean.total.equals("1")) {
                    val rowsBean: ApkUpdateBean.RowsBean = apkUpdateBean.rows[0]
                    val appURL: String = rowsBean.apkurl
                    val appVersionName: String = rowsBean.versionname
                    val versioncode: String = rowsBean.versioncode
                    val appDesc: String = rowsBean.appdesc
                    showLog(appURL)
                    showLog(appVersionName)
                    showLog(versioncode)
                    showLog(appDesc)
                    if (appVersionName != getVersionName()) {
                        downloadAndInstall(appURL, appVersionName, appDesc, versioncode)
                    }
                }
            }

            override fun onFailed(what: Int, response: Response<String?>?) {

            }
        })
    }

    private fun downloadAndInstall(
        downloadURL: String,
        versionName: String,
        description: String,
        versionCode: String
    ) {
        manager = DownloadManager.Builder(this).run {
            apkUrl(downloadURL)
            apkName("博贺电厂点巡检.apk")
            smallIcon(R.mipmap.logo1)
            showNewerToast(false)
            apkVersionCode(versionCode.toInt())
            apkVersionName(versionName)
            apkDescription(description)
            enableLog(true)
            jumpInstallPage(true)
            dialogButtonColor(Color.parseColor("#FF8247"))
            dialogProgressBarColor(Color.parseColor("#FF8247"))
            dialogButtonTextColor(Color.WHITE)
            showNotification(true)
            showBgdToast(true)
            forcedUpgrade(true)
                .onDownloadListener(object : OnDownloadListener {
                    override fun start() {}
                    override fun downloading(max: Int, progress: Int) {}
                    override fun done(apk: File) {}
                    override fun cancel() {}
                    override fun error(e: Throwable) {}
                }).onButtonClickListener(object : OnButtonClickListener {
                    override fun onButtonClick(id: Int) {}
                })
            build()
        }
        manager?.download()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                showToast("再按一次退出程序")
                exitTime = System.currentTimeMillis()
            } else {
                NohttpUtils.getInstance().cancelAll()
                ControllerActivity.getAppManager().finishAllActivity()
                finish()
                exitProcess(0)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    private fun getPhoneInfo(): String {
        val imei: String = Settings.System.getString(contentResolver, Settings.Secure.ANDROID_ID)
        val model = Build.MODEL //手机型号
        val sysVersion = Build.VERSION.RELEASE //系统版本
        val info = PhoneInfo()
        info.total = 1
        val list: MutableList<PhoneInfo.UserInfo> = ArrayList()
        val userInfo = PhoneInfo.UserInfo()
        userInfo.imeinum = imei
        userInfo.sysversion = sysVersion
        userInfo.phonemodel = model
        userInfo.phonenum = ""
        userInfo.username = UiUtlis.getText(binding.etUse)
        userInfo.password = UiUtlis.getText(binding.etPwd)
        list.add(userInfo)
        info.rows = list
        return GsonUtils.GsonString(info)
    }

    private fun checkLoginDateNoExpire(): Boolean {
        val lastLoginDate = SPUtils.get(context, Contans.LASTLOGINDATE, "") as String
        if (lastLoginDate != "") {
            try {
                //格式化日期的对象(转化成习惯的时间格式)
                val sdFormat = SimpleDateFormat("yyyy年MM月dd日")
                val date = sdFormat.parse(lastLoginDate)
                val calendarLastLogin = Calendar.getInstance()
                if(date!=null){
                    calendarLastLogin.setTime(date)
                    if (!Calendar.getInstance().after(calendarLastLogin)) {
                        return true
                    }
                }
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }
        return false
    }

    private fun  offlineLogin() {
        if (UserID == "") {
            showToast("首次登陆请连接厂内WIFI")
        } else {
            if (UserID != binding.etUse.text.toString()) {
                showToast("工号错误")
            } else {
                val canOfflineLogin = checkLoginDateNoExpire()
                if (canOfflineLogin) {
                    val intent = Intent(this, MainActivity::class.java)
                    startActivity(intent)
                    finish()
                }else{
                    showToast("离线登录有效期只有7天，离线自动登录已失效,请连接wifi后重新登录")
                }
            }
        }
    }

    private fun onlineLogin() {
        Log.i("app", Contans.IP + Contans.LOGIN);
        val json: String = getPhoneInfo()
        val request = NoHttp.createStringRequest(Contans.IP + Contans.LOGIN, RequestMethod.POST)
        request.setDefineRequestBodyForJson(json)
        NohttpUtils.getInstance().add(this, 0, request, callback, true, true, "登录中...")
    }

    private val callback: HttpListener<String?> = object : HttpListener<String?> {
        override fun onSucceed(what: Int, response: Response<String?>?) {
            val json = response?.get()
            showLog(json)
            val userInfo = GsonUtils.GsonToBean(json, UserInfo::class.java)
            if (userInfo != null) {
                val user = userInfo.rows[0]
                val status = user.status
                val username = user.usernames
                when (status) {
                    "0" -> showToast("用户名或密码错误")
                    "1" -> {
                        CrashReport.putUserData(context, "UserName", binding.etUse.text.toString())
                        SPUtils.put(context, "save", binding.savePwUser.isChecked)
                        SPUtils.put(
                            context,
                            Contans.USERID,
                            RSAUtils.encryptBASE64StrLocal(binding.etUse.getText().toString())
                        )
                        SPUtils.put(
                            context,
                            Contans.USERPWD,
                            RSAUtils.encryptBASE64StrLocal(binding.etPwd.getText().toString())
                        )
                        SPUtils.put(context, Contans.USERNAME, username)
                        SPUtils.put(
                            context,
                            Contans.BZBH,
                            if (user.bzbh == null) "" else user.bzbh
                        )
                        SPUtils.put(
                            context,
                            Contans.BZMC,
                            if (user.bzmc == null) "" else user.bzmc
                        )
                        SPUtils.put(
                            context,
                            Contans.PERMISSIONSRESULT,
                            if (user.permissionsResult == null) "" else user.permissionsResult
                        )

                        //格式化日期的对象(转化成习惯的时间格式)
                        val sdFormat = SimpleDateFormat("yyyy年MM月dd日")
                        //静态方法getInstance()使用默认时区和语言环境获得一个日历。
                        val calendar = Calendar.getInstance()
                        //增加7天，负数则为减少天数
                        //calendar.add(Calendar.DATE, 1)
                        calendar.add(Calendar.DATE, 7)
                        val nowStr = sdFormat.format(calendar.time)
                        SPUtils.put(
                            context,
                            Contans.LASTLOGINDATE,
                            nowStr
                        )

                        val intent = Intent(context, MainActivity::class.java)
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        startActivity(intent)
                        finish()
                    }

                    "2" -> showToast("登录异常...")
                    "3" -> showToast("未激活或未授权...")
                    "4" -> showToast("禁止登陆...")
                }
            } else {
                showToast(UiUtlis.getString(context, R.string.data_error))
            }
        }

        override fun onFailed(what: Int, response: Response<String?>?) {
            Log.i("app", "onFailed,请求超时");
            showToast("请求超时,进入离线登录状态")
            offlineLogin()
        }
    }
}