package com.ccwangluo.accelerator.ui.home

import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.support.v4.media.session.PlaybackStateCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import androidx.lifecycle.ViewModelProvider
import com.ccwangluo.accelerator.R
import com.ccwangluo.accelerator.databinding.FragmentQuickBinding
import com.ccwangluo.accelerator.ui.dialog.CommonDialog
import com.ccwangluo.accelerator.ui.dialog.MemberDialog
import com.ccwangluo.accelerator.ui.web.CommonWebViewFragment
import com.ccwangluo.accelerator.utils.AcceleratorUtils
import com.ccwangluo.accelerator.utils.LoginUtils
import com.ccwangluo.accelerator.utils.SysUtils
import com.ccwangluo.cc_quickly.utils.SettingSPUtils
import com.github.shadowsocks.http.HttpConfig
import com.github.shadowsocks.bg.BaseService
import com.hjq.toast.ToastUtils
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xpage.utils.TitleBar
import com.xuexiang.xui.utils.ViewUtils
import com.xuexiang.xui.widget.progress.CircleProgressView
import com.xuexiang.xutil.app.AppUtils

class AccelertorFragment : XPageFragment() {
    private lateinit var binding: FragmentQuickBinding
    private lateinit var accelertorViewModel: AccelertorViewModel
    private var acc_timer = 0L

    override fun initTitleBar(): TitleBar? {
        //不使用@Page标注的一定要注意覆盖这个方法
        return null
    }

    var state: BaseService.State? = null

    override fun inflateView(inflater: LayoutInflater?, container: ViewGroup?): View {
        binding = FragmentQuickBinding.inflate(inflater!!, container, false)
        accelertorViewModel =
            ViewModelProvider(requireActivity()).get(AccelertorViewModel::class.java)
        return binding.root
    }


    override fun initViews() {
        accelertorViewModel.netState.observe(this, {
            if (it.preNetDelay != -1) { //有网络

                binding.preDelay1.setText(it.preNetDelay.toString())
                binding.preDelay2.setText(it.preNetDelay.toString())
                binding.preDelay1Unit.visibility = View.VISIBLE
                binding.preDelay2Unit.visibility = View.VISIBLE

            } else { //无网络
                binding.preDelay1.setText("--")
                binding.preDelay2.setText("--")
                binding.preDelay1Unit.visibility = View.GONE
                binding.preDelay2Unit.visibility = View.GONE
            }

            if (it.accNetDelay != -1) {
                binding.netDelay1.setText(it.accNetDelay.toString())
                binding.netDelay2.setText(it.accNetDelay.toString())
                binding.netDelay1Unit.visibility = View.VISIBLE
                binding.netDelay2Unit.visibility = View.VISIBLE
            } else {
                binding.netDelay1.setText("__")
                binding.netDelay2.setText("__")
                binding.netDelay1Unit.visibility = View.GONE
                binding.netDelay2Unit.visibility = View.GONE
            }

            if (!it.lossRate.isEmpty()) {
                binding.netLost1.setText(it.lossRate)
                binding.netLost2.setText(it.lossRate)
                binding.netLost1Unit.visibility = View.VISIBLE
                binding.netLost2Unit.visibility = View.VISIBLE
            } else {
                binding.netLost1.setText("__")
                binding.netLost2.setText("__")
                binding.netLost1Unit.visibility = View.GONE
                binding.netLost2Unit.visibility = View.GONE
            }

            if (state == BaseService.State.Connected) {
                binding.netQuality.setText(SysUtils.getnetQuality(it.accNetDelay))
            } else {
                binding.netQuality.setText(SysUtils.getnetQuality(it.preNetDelay))
            }
            binding.activeNetwork.setText(SysUtils.getActiveNet())
        })

        accelertorViewModel.accState.observe(this, {
            binding.accStateTx.setText(SysUtils.getAccTimeString(acc_timer))
            state = it
            freshData(it)
            if (SettingSPUtils.isSmartAccOpen) {
                binding.smartAccOpen.setText("已开启")
                binding.smartAccOpen.setTextColor(resources.getColor(R.color.open_acc_enable))
                binding.smartAccOpenArea.visibility = View.GONE
            } else {
                binding.smartAccOpen.setText("未开启 >")
                binding.smartAccOpen.setTextColor(resources.getColor(R.color.white))
                binding.smartAccOpenArea.visibility = View.VISIBLE
            }
        })

        accelertorViewModel.userProfile.observe(this, {
            if (it.hasUnreadNotice) {
                binding.iconNoticeBadge.visibility = View.VISIBLE
            } else {
                binding.iconNoticeBadge.visibility = View.GONE
            }
        })

        binding.progressViewCircleSmall.setProgressViewUpdateListener(object :
            CircleProgressView.CircleProgressUpdateListener {
            override fun onCircleProgressStart(view: View?) {
                binding.progressArea.visibility = View.VISIBLE
            }

            override fun onCircleProgressUpdate(view: View?, progress: Float) {
                binding.progress.setText(progress.toInt().toString())
            }

            override fun onCircleProgressFinished(view: View?) {
                binding.progressArea.visibility = View.GONE
                binding.btnQuick.isEnabled = true
                binding.progressViewCircleSmall.progress = 0F
                binding.progressViewCircleSmall.postDelayed({
                    if (state != BaseService.State.Connected) {
                        ToastUtils.show("加速失败")
                    }
                }, 3000)
                AcceleratorUtils.startAccelerator(this@AccelertorFragment)
            }
        })

        if (binding.gamePicOut.background is AnimationDrawable) {
            (binding.gamePicOut.background as AnimationDrawable).start()
            binding.gamePicOut.startAnimation(getDefaultAnim())
        }

    }

    override fun initListeners() {
        binding.iconNotice.setOnClickListener {
            openToWebview(HttpConfig.UI_MESSAGE_URL)
        }

        binding.gamePage.setOnClickListener {
            openToWebview(HttpConfig.UI_GAME_URL + "?gameId=${AcceleratorUtils.game?.id}")
        }

        binding.smartAccOpen.setOnClickListener {
            if (!SettingSPUtils.isSmartAccOpen) {
                openToWebview(HttpConfig.UI_SETTING_URL)
            }
        }

        binding.smartAccOpenBtn.setOnClickListener {
            if (!SettingSPUtils.isSmartAccOpen) {
                openToWebview(HttpConfig.UI_SETTING_URL)
            }
        }

        binding.preventAccLost.setOnClickListener {
            openToWebview(HttpConfig.UI_SPEED_URL + "?id=1")
        }
        binding.preventAccInvalid.setOnClickListener {
            openToWebview(HttpConfig.UI_SPEED_URL + "?id=2")
        }

        binding.btnExpend.setOnClickListener {
            if (binding.expandableLayout1.isExpanded) {
                binding.expandableLayout1.toggle()
                binding.expandableLayout2.expand()
                binding.btnExpendBg.setBackgroundResource(R.mipmap.quick_arrow_up)
            } else {
                binding.expandableLayout1.expand()
                binding.expandableLayout2.toggle()
                binding.btnExpendBg.setBackgroundResource(R.mipmap.quick_arrow_down)
            }
        }
        binding.btnQuick.setOnClickListener {
            accelertorViewModel.accState.value?.let {
                if (it.canStop) {
                    context?.let {
                        CommonDialog(it).setTitle("加速停止确认")
                            .setContent("停止加速可能会导致游戏断线，是否确认停止？")
                            .setBtnLeft("取消", {}).setBtnRight("停止加速", {
                                AcceleratorUtils.stopAccelerator()
                            }).show<CommonDialog>()
                    }
                    return@setOnClickListener
                }
            }
            if (!LoginUtils.hasToken()) {
                LoginUtils.login(this, {

                })
                return@setOnClickListener
            }

            if (!SysUtils.getConnectivityStatus()) {
                binding.quickTopToast.visibility = View.VISIBLE
                binding.quickTopToastTx.setText("网络异常,请检查网络后重试")
                binding.quickTopToastTx.postDelayed({
                    binding.quickTopToast.visibility = View.GONE
                }, 2000)
                return@setOnClickListener
            }
            AcceleratorUtils.getGameList(this) {
                if (it) {
                    //
                    AcceleratorUtils.game?.let {
                        if (!SysUtils.isPackageInstall(requireContext(), it.packageName)) {
                            binding.quickTopToast.visibility = View.VISIBLE
                            binding.quickTopToastTx.setText("请先安装游戏后加速")
                            binding.quickTopToastTx.postDelayed({
                                binding.quickTopToast.visibility = View.GONE
                            }, 2000)
                            return@getGameList
                        }
                    }
                    //用户是否有使用时长
                    LoginUtils.getUserHasTimer(this@AccelertorFragment) {
                        if (it) {
                            binding.btnQuick.isEnabled = false
                            startAnim()
                        } else {
                            MemberDialog(this@AccelertorFragment).show<MemberDialog>()
                        }
                    }
                } else {
                    ToastUtils.show("获取游戏配置异常")
                }
            }


        }

        binding.gameStart.setOnClickListener {
            AcceleratorUtils.game?.let {
                AppUtils.launchApp(it.packageName)
                if (state == BaseService.State.Connected) {
                    binding.gameStart.postDelayed({
                        ToastUtils.show("TT正在为游戏加速")
                    }, 1000)
                }
            }
        }
    }

    fun openToWebview(url: String) {
        val params = Bundle()
        params.putString(CommonWebViewFragment.WEBVIEW_URL_KEY, HttpConfig.UI_MAIN_URL + url)
        LoginUtils.token?.let {
            openPage(CommonWebViewFragment::class.java, params)
        } ?: let {
            LoginUtils.login(this, {
                if (true) {
                    openPage(CommonWebViewFragment::class.java, params)
                }
            })
        }
    }

    override fun onResume() {
        super.onResume()
        AcceleratorUtils.registerStateListener { state, l, net ->
            net?.let {
                accelertorViewModel.netState.postValue(net)
            }
            acc_timer = l
            accelertorViewModel.accState.postValue(state)
        }
    }

    fun freshData(state: BaseService.State) {
        if (state == BaseService.State.Connected) {
            startAccSuccess()
            if (SettingSPUtils.isFirstAccSuccess) {
                context?.let {
                    CommonDialog(it).setTitle("防止加速掉线")
                        .setContent("为了防止加速进程被手机系统中断，影响游戏加速，请确保完成相关设置")
                        .setBtnLeft("取消", {}).setBtnRight("去设置", {
                            openToWebview(HttpConfig.UI_SPEED_URL + "?id=1")
                        }).show<CommonDialog>()
                    SettingSPUtils.isFirstAccSuccess = false
                }

            }
        } else {
            binding.gamePicIn1.clearAnimation()
            if (binding.gamePicOut.background is AnimationDrawable) {
                (binding.gamePicOut.background as AnimationDrawable).start()
            }
            binding.accStateTx.visibility = View.GONE
            binding.btnQuick.setBackgroundResource(R.mipmap.quick_start)
            binding.gameStart.visibility = View.GONE
        }
    }

    fun getUserProfile() {
        LoginUtils.token?.let {
            LoginUtils.getUserProfile(this) {
                it?.let {
                    accelertorViewModel.userProfile.postValue(it)
                }
            }
        }
    }

    override fun onPause() {
        super.onPause()
        AcceleratorUtils.unRegisterStateListener()
    }

    fun startAnim() {
        binding.progressViewCircleSmall.startProgressAnimation()
    }

    fun startAccSuccess(){
        if (binding.gameStart.visibility == View.GONE) {
            binding.gamePicIn1.startAnimation(getDefaultAnim())
            binding.accStateTx.visibility = View.VISIBLE
            binding.btnQuick.setBackgroundResource(R.mipmap.quick_stop)
            if (binding.gamePicOut.background is AnimationDrawable) {
                (binding.gamePicOut.background as AnimationDrawable).stop()
            }
            binding.gameStart.visibility = View.VISIBLE
        }
    }

    fun getDefaultAnim(): RotateAnimation {
        val multiple = 1000
        val rotate = RotateAnimation(
            0f,
            360f * multiple,
            Animation.RELATIVE_TO_SELF,
            0.5f,
            Animation.RELATIVE_TO_SELF,
            0.5f
        )
        val lin = LinearInterpolator()
        rotate.interpolator = lin
        rotate.duration = 2000L * multiple //设置动画持续周期

        rotate.repeatCount = -1 //设置重复次数

        return rotate
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            getUserProfile()
        }
    }

    companion object {
        fun newInstance(): AccelertorFragment {
            val fragment = AccelertorFragment()
            return fragment
        }
    }

}