package com.yzx.ebrand.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.core.widget.ContentLoadingProgressBar
import androidx.recyclerview.widget.GridLayoutManager
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.UIData
import com.allenliu.versionchecklib.v2.callback.CustomDownloadingDialogListener
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.yzx.ebrand.MainActivity
import com.yzx.ebrand.R
import com.yzx.ebrand.activity.base.BaseActivity
import com.yzx.ebrand.adapter.HomeAdapter
import com.yzx.ebrand.config.Config
import com.yzx.ebrand.model.BaseBean
import com.yzx.ebrand.model.HomeItem
import com.yzx.ebrand.model.User
import com.yzx.ebrand.model.Version
import com.yzx.ebrand.widget.BaseDialog
import com.yzx.ebrand.presenter.base.BasePresenter
import kotlinx.android.synthetic.main.activity_home.*
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.util.*

class HomeActivity : BaseActivity<BasePresenter<*>>(), NetworkUtils.OnNetworkStatusChangedListener {

    private val mAdapter: HomeAdapter by lazy {
        val list = mutableListOf<HomeItem>()
        list.add(HomeItem("家庭作业", R.mipmap.ic_home_work, "/homework/ebook_list"))
        list.add(HomeItem("笔记本", R.mipmap.ic_home_notebook, "/notebook/list"))
        list.add(HomeItem("背诵默写", R.mipmap.ic_home_write, "/write/index"))
        list.add(HomeItem("阅读", R.mipmap.ic_home_rack,"/read/index"))
        list.add(HomeItem("错题本", R.mipmap.ic_home_errorbook, "/errorbook/ebookindex"))
        list.add(HomeItem("随堂检测", R.mipmap.ic_home_classwork))
        list.add(HomeItem("我的", R.mipmap.ic_home_my, "/mine/ebook"))
        HomeAdapter(list)
    }

    private var count = 0
    private val run = Runnable {
        count = 0
    }

    private var netDialog:AlertDialog ?= null

    override val inflateId: Int
        get() = R.layout.activity_home



    override fun initView() {

        NetworkUtils.registerNetworkStatusChangedListener(this)


        val layoutManager = GridLayoutManager(this, 3)
        homeGridView.layoutManager = layoutManager
        homeGridView.adapter = mAdapter

        switchBtn.setOnClickListener {
            val url = "${Config.M_URL}/choiceunit.html?from=ehome"
            WebActivity.active(this, url)
        }

        loginBtn.setOnClickListener {
            val url = "${Config.M_URL}/login.html?from=ehome"
            WebActivity.active(this, url)
        }

        testBtn.setOnClickListener {
            count++
            testBtn.removeCallbacks(run)
            testBtn.postDelayed(run, 1000)
            if (count >= 5) {
                startActivity<MainActivity>()
            }
        }
    }

    override fun initData() {
        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (User.getUser().user_id == 0) {
                val url = "${Config.M_URL}/login.html?from=ehome"
                WebActivity.active(this, url)
            } else {
                val list = mAdapter.data
                val item = list[position]
                if (StringUtils.isTrimEmpty(item.url)) {
                    toast("功能设计中，敬请期待")
                } else {
                    val url = Config.M_URL + item.url
                    WebActivity.active(this, url)
                }
            }
        }


        //请求权限
//        ActivityCompat.requestPermissions(
//            this,
//            PERMISSIONS,
//            PERMISSIONS_REQUEST_STORAGE
//        )

        PermissionUtils.permissionGroup(PermissionConstants.STORAGE)
            .rationale { activity, shouldRequest ->

            }.callback(object :PermissionUtils.FullCallback{
                override fun onGranted(granted: MutableList<String>) {
                    LogUtils.d("权限通过",granted)
                }

                override fun onDenied(
                    deniedForever: MutableList<String>,
                    denied: MutableList<String>
                ) {
                    LogUtils.d("权限拒绝",denied)
                }

            }).theme { activity -> ScreenUtils.setFullScreen(activity) }
            .request()


    }

    private val PERMISSIONS_REQUEST_STORAGE = 1

    val PERMISSIONS = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    override fun initPresenter(): BasePresenter<*>? {
        return null
    }

    @SuppressLint("SetTextI18n")
    override fun onResume() {
        super.onResume()
        val user = User.getUser()
        if (user.user_id != 0) {
            userNameTv.text = "你好，${user.user_name}"
//            userInfoTv.text = "${user.school_name} | ${user.grade_name}${user.class_name}"
            userInfoTv.visibility = View.VISIBLE
            loginBtn.visibility = View.GONE
            switchBtn.visibility = if (User.getUnitCount() > 1) {
                View.VISIBLE
            } else {
                View.GONE
            }
        } else {
            userNameTv.text = "未登录"
            userInfoTv.text = ""
            userInfoTv.visibility = View.GONE
            loginBtn.visibility = View.VISIBLE
            switchBtn.visibility = View.GONE
        }
        titleTv.text = Config.APP_NAME
        if (NetworkUtils.isConnected()) {
            checkVersion(false)
        }else{
            checkNetwork()
        }
    }

    private fun checkNetwork() {
        if(netDialog==null){
            val builder = AlertDialog.Builder(this)
            builder.setTitle("温馨提示")
            builder.setMessage("你还没有连接网络，请先连接网络！")
            builder.setPositiveButton("去设置") { _, _ ->
                NetworkUtils.openWirelessSettings()
            }
            builder.setCancelable(false)
            netDialog = builder.create()
            netDialog?.setCanceledOnTouchOutside(false)
            netDialog?.getButton(DialogInterface.BUTTON_NEGATIVE)?.visibility = View.GONE
        }
        netDialog?.show()
    }

    private fun checkVersion(userCheck: Boolean = false): Unit {
        val BASE_URL = Config.BASE_URL
        OkGo.post<String>("$BASE_URL/parent/common/getInkBottleMaxVersion")
            .tag(this)
            .execute(object : StringCallback() {

                override fun onSuccess(response: Response<String>) {
                    val json = response.body()
                    Log.d("checkVersion", "onSuccess: ${json}")
                    val resultType = object : TypeToken<BaseBean<Version>>() {}.type
                    val gson = Gson()
                    val res = gson.fromJson<BaseBean<Version>>(json, resultType)
                    if (res.code == 0) {
                        val appVersion = AppUtils.getAppVersionName()
                        val appVersionCode = AppUtils.getAppVersionCode()
                        val versionCode = res?.data?.version_code ?: 0
                        val curr = Date().time
                        val lastTipTime = SPUtils.getInstance()
                            .getLong("last_tip_time${res.data.version_code}", 0)
                        if (versionCode > appVersionCode) {     //有新版本
                            when {
                                res.data.type == 1 -> {   //强制升级
                                    updateApp(res.data)
                                }
                                curr - lastTipTime > 24 * 60 * 60 * 1000 -> {     //非强制一天以内提示一次
                                    updateApp(res.data)
                                }
                                userCheck -> {      //
                                    updateApp(res.data)
                                }
                            }

                        } else {
                            if (userCheck) {
                                toast("已经是最新版本了！")
                            }
                        }
                    }
                }

            })


    }


    private fun updateApp(version: Version) {
        AllenVersionChecker
            .getInstance()
            .downloadOnly(
                UIData.create()
                    .setTitle("检测到新版本")
                    .setContent(version.explain)
                    .setDownloadUrl(version.app_src)
            )
            .setCustomVersionDialogListener { context, versionBundle ->
                val dialog = BaseDialog(context, R.style.BaseDialog, R.layout.version_dialog)
                val title = dialog.find<TextView>(R.id.tv_title)
                title.text = "检测到新版本"
                val content = dialog.find<TextView>(R.id.tv_msg)
                content.text = version.explain
                dialog.window?.setDimAmount(0.5f)
                val cancelBtn = dialog.find<View>(R.id.cancel_btn)
                if (version.type == 1) {
                    cancelBtn.visibility = View.GONE
                }

                return@setCustomVersionDialogListener dialog
            }
            .setOnCancelListener {
                SPUtils.getInstance().put("last_tip_time${version.version_code}", Date().time)
            }
            .setCustomDownloadingDialogListener(object : CustomDownloadingDialogListener {
                @SuppressLint("SetTextI18n")
                override fun updateUI(dialog: Dialog?, progress: Int, versionBundle: UIData?) {
                    val tvProgress: TextView = dialog!!.findViewById(R.id.tv_progress)
                    val progressBar: ContentLoadingProgressBar = dialog.findViewById(R.id.pb)
                    progressBar.progress = progress
                    tvProgress.text = "$progress%"

                    Log.d("checkVersion", "onSuccess: ${progress}")
                }

                override fun getCustomDownloadingDialog(
                    context: Context?,
                    progress: Int,
                    versionBundle: UIData?
                ): Dialog {
                    return BaseDialog(
                        context!!,
                        R.style.BaseDialog,
                        R.layout.download_dialog
                    )
                }

            })
            .executeMission(this)
    }

    override fun onConnected(networkType: NetworkUtils.NetworkType?) {
        netDialog?.dismiss()
    }

    override fun onDisconnected() {
        checkNetwork()
    }
}