package com.ccwangluo.accelerator.ui.home

import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
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.model.NetState
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.ShareUtils
import com.ccwangluo.accelerator.utils.SysUtils
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
import com.ccwangluo.cc_quickly.utils.SettingSPUtils
import com.github.shadowsocks.bg.AuthManager
import com.github.shadowsocks.bg.BaseService
import com.github.shadowsocks.http.HttpConfig
import com.hjq.toast.ToastUtils
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xpage.core.PageOption
import com.xuexiang.xpage.utils.TitleBar
import com.xuexiang.xui.widget.progress.CircleProgressView
import com.xuexiang.xutil.app.AppUtils

class AcceleratorFragment : XPageFragment() {
    private lateinit var binding: FragmentQuickBinding
    private lateinit var acceleratorViewModel: AccelertorViewModel
    private var accTimer = 0L

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

    var state: BaseService.State? = null

    fun updateNetState(netState: NetState) {
        acceleratorViewModel.netState.postValue(netState)
        accTimer = AcceleratorUtils.getAccTime()
    }

    fun changeState(state: BaseService.State) {
        acceleratorViewModel.accState.postValue(state)
    }

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


    override fun initViews() {
        acceleratorViewModel.netState.observe(this, {
            if (it.preNetDelay != -1 && state == BaseService.State.Connected) { //有网络

                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 && state == BaseService.State.Connected) {
                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() && state == BaseService.State.Connected) {
                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())
        })

        acceleratorViewModel.accState.observe(this) {
            binding.accStateTx.setText(SysUtils.getAccTimeString(accTimer))
            state = it
            freshData(it)
            if (AuthManager.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
            }
        }

        acceleratorViewModel.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
                AcceleratorUtils.startAccelerator(this@AcceleratorFragment)
            }
        })

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

    }

    override fun initListeners() {
        binding.iconNotice.setOnClickListener {
            DataRePortUtils.report("st_speed_sysmsg_clk")
            openToWebview(HttpConfig.UI_MESSAGE_URL)
        }
        binding.accShare.setOnClickListener {
            DataRePortUtils.report("st_share_clk", mapOf("scene" to "3"))
            activity?.let { it1 -> ShareUtils().share(it1) }
        }

        binding.gamePage.setOnClickListener {
            DataRePortUtils.report("st_game_sysmsg_clk")
            openWebviewForResult(HttpConfig.UI_GAME_URL + "?gameId=${AcceleratorUtils.game?.id}")
        }

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

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

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

        binding.btnExpend.setOnClickListener {
            DataRePortUtils.report("st_speed_msg_clk")
            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 {
            acceleratorViewModel.accState.value?.let {
                if (it.canStop) {
                    context?.let {
                        CommonDialog(it).setTitle("加速停止确认")
                            .setContent("停止加速可能会导致游戏断线，是否确认停止？")
                            .setBtnLeft("取消", {
                                DataRePortUtils.report("st_speed_stop_pop_cancel_clk")
                            }).setBtnRight("停止加速", {
                                DataRePortUtils.report("st_speed_stop_pop_ok_clk")
                                AcceleratorUtils.stopAccelerator()
                            }).show<CommonDialog>()
                        DataRePortUtils.report("st_speed_stop_pop_show")
                    }
                    DataRePortUtils.report("st_speed_stop_clk")
                    return@setOnClickListener
                } else {
                    DataRePortUtils.report("st_speed_start_clk")
                }
            }
            if (!LoginUtils.hasToken()) {
                context?.let { it1 ->
                    LoginUtils.login(it1, {

                    })
                }
                DataRePortUtils.report("st_speed_result", mapOf("result" to 0, "cause" to "3"))
                return@setOnClickListener
            }

            if (!SysUtils.getConnectivityStatus()) {
                binding.quickTopToast.visibility = View.VISIBLE
                binding.quickTopToastTx.setText("网络异常,请检查网络后重试")
                binding.quickTopToastTx.postDelayed({
                    binding.quickTopToast.visibility = View.GONE
                }, 2000)
                DataRePortUtils.report("st_speed_result", mapOf("result" to 0, "cause" to "3"))
                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)
                            DataRePortUtils.report(
                                "st_speed_result",
                                mapOf("result" to 0, "cause" to "1")
                            )
                            return@getGameList
                        }
                    }
                    //用户是否有使用时长
                    LoginUtils.getUserHasTimer(this@AcceleratorFragment) {
                        if (it) {
                            binding.btnQuick.isEnabled = false
                            startAnim()
                        } else {
                            DataRePortUtils.report(
                                "st_speed_result",
                                mapOf("result" to 0, "cause" to 3)
                            )
                            MemberDialog(this@AcceleratorFragment).show<MemberDialog>()
                        }
                    }
                } else {
                    DataRePortUtils.report("st_speed_result", mapOf("result" to 0, "cause" to "3"))
                    ToastUtils.show("获取游戏配置异常")
                }
            }


        }

        binding.gameStart.setOnClickListener {
            if (!binding.expandableLayout1.isExpanded) {
                AcceleratorUtils.game?.let {
                    DataRePortUtils.report("st_speed_game_start_clk")
                    try {
                        AppUtils.launchApp(it.packageName)
                    } catch (e: Exception) {

                    }
                    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 {
            context?.let { it1 ->
                LoginUtils.login(it1, {
                    if (true) {
                        openPage(CommonWebViewFragment::class.java, params)
                    }
                })
            }
        }
    }

    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onFragmentResult(requestCode, resultCode, data)
        if (requestCode == CLICK_START_ACC_REQUEST_CODE) {
            binding.btnQuick.performClick()
        }
    }

    private val CLICK_START_ACC_REQUEST_CODE: Int = 100;
    private fun openWebviewForResult(url: String) {
        LoginUtils.token?.let {
            PageOption.to(CommonWebViewFragment::class.java)
                .putString(CommonWebViewFragment.WEBVIEW_URL_KEY, HttpConfig.UI_MAIN_URL + url)
                .setRequestCode(CLICK_START_ACC_REQUEST_CODE)
                .open(this)
        } ?: let {
            context?.let { it1 ->
                LoginUtils.login(it1) {
                    if (it) {
                        PageOption.to(CommonWebViewFragment::class.java)
                            .putString(
                                CommonWebViewFragment.WEBVIEW_URL_KEY,
                                HttpConfig.UI_MAIN_URL + url
                            )
                            .setRequestCode(CLICK_START_ACC_REQUEST_CODE)
                            .open(this)
                    }
                }
            }
        }
    }


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

            }
        } 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 {
                    acceleratorViewModel.userProfile.postValue(it)
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AcceleratorUtils.registerVipExpireListener {
            MemberDialog(this@AcceleratorFragment).show<MemberDialog>()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        AcceleratorUtils.unRegisterVipExpireListener()
    }

    override fun onStart() {
        super.onStart()
        AcceleratorUtils.registerStateListener { state, l, net ->
            net?.let {
                acceleratorViewModel.netState.postValue(net)
            }
            accTimer = l
            acceleratorViewModel.accState.postValue(state)
        }
    }

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

    override fun onResume() {
        super.onResume()

    }

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

    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(): AcceleratorFragment {
            return AcceleratorFragment()
        }
    }

}