package com.jld.vod.view

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.drawable.Drawable
import android.os.Handler
import android.text.InputType
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.observe
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.jld.vod.R
import com.jld.vod.base.BaseActivity
import com.jld.vod.config.Config
import com.jld.vod.model.bean.*
import com.jld.vod.service.MyAccessibilityService
import com.jld.vod.utils.DateUtils
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.PopupUtils
import com.jld.vod.utils.SharedPrefUtils
import com.jld.vod.view.fragment.*
import com.jld.vod.view.widget.CustomGEOAdDialog
import com.jld.vod.view.widget.UpCircleMenuLayout
import com.jld.vod.viewmodel.MainViewModel
import com.xuexiang.xpage.enums.CoreAnim
import com.xuexiang.xui.adapter.simple.XUISimpleAdapter
import com.xuexiang.xui.utils.DensityUtils
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import com.xuexiang.xui.widget.popupwindow.popup.XUIListPopup
import com.xuexiang.xui.widget.popupwindow.popup.XUIPopup
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import java.util.*


/**
 * @author ZhaoFuXin
 * @Email：18276061387@163.com
 * @description:
 * @date :2020/6/28 11:38
 */
class MainActivity : BaseActivity() {
    private val TAG ="MainActivity"
    private var mUpCircleMenuLayout: UpCircleMenuLayout? = null
    private var receiver: broadCastRecever = broadCastRecever()//更新时间广播
    private lateinit var viewModel: MainViewModel
    private val languageList: MutableList<LanguageBean> = ArrayList<LanguageBean>()
    private var language: Array<String?> ?=null
    private var mAllModularRotateImgBean:List<AllModularRotateImgBean> ?=null
    private val password : String = "123456"
    private var pos = 0
    private val mHandler = Handler()

    private val mItemTexts = arrayOf(
        "电影", "音乐", "游戏",
        "浏览器", "地图", "关于",
        "电影", "音乐", "游戏",
        "浏览器"
    )
    private val mItemImgs = intArrayOf(
        R.mipmap.movie, R.mipmap.music,
        R.mipmap.game, R.mipmap.browser,
        R.mipmap.maps, R.mipmap.about_us,
        R.mipmap.movie, R.mipmap.music,
        R.mipmap.game, R.mipmap.browser)

    override fun initView() {
        super.initView()
        //点击图标位置
        val intent = intent
        val bundle = intent.extras
        pos = bundle!!.getInt("pos")

        mUpCircleMenuLayout = findViewById(R.id.id_mymenulayout) as UpCircleMenuLayout
        viewModel = ViewModelProvider.
         AndroidViewModelFactory(application).create(MainViewModel::class.java)


        //初始化车牌号
        var carNum = SharedPrefUtils.getString(this,"carNum")
        if (carNum != "")
        {
            tv_plate.setText(carNum)
        }

        //动态背景图片
        val main_bg_img = SharedPrefUtils.getString(this,"main_bg_img")
        try {
            if (!main_bg_img.isEmpty())
            {
                val simpleTarget: SimpleTarget<Drawable?> = object : SimpleTarget<Drawable?>() {
                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable?>?) {
                        rl_main.setBackground(resource)
                    }
                }
                Glide.with(this).load(com.jld.vod.config.Config.ApiBaseUrl+"/synchronization/previewImg?imgUrl="
                        +main_bg_img).into(simpleTarget)
            }
        }catch (e: Exception)
        {
            e.printStackTrace()
        }

        //获取车辆信息
        viewModel.getCarInfo()
        //获取语言
        viewModel.getLanguage()
        //获取全部模块
        viewModel.getAllModular()
        //获取固定广告
        viewModel.findPositionAdvert()
    }

    override fun initData() {
        super.initData()

        //初始全部模块
        initModular()
        //初始化车辆信息
        initCarInfo()
        //初始化全部语言
        initLanguage()
        //初始化图标资源
        initIconRes()
        //初始化模块id
        initMid()
        //初始化广告模块
        initAdVert()
    }

    /**
     * 初始化广告模块
     */
    private fun initAdVert() {
        viewModel.findPositionAdvertLiveData.observe(this) {res->
            LogUtils.logD("findPositionAdvertLiveData"+res.data)
            when (res?.code) {
                BaseBean.SUCCESS -> {
                    if (res.data!!.size != 0)
                    {
                        val isFirstShowAds = SharedPrefUtils.getBoolean(this,"isFirstShowAds",true)
                        if (isFirstShowAds)
                        {
                            mHandler.postDelayed(Runnable {
                                EventBus.getDefault().post(res.data)
                                SharedPrefUtils.putBoolean(this,"isFirstShowAds",false)
                            },5000)
                        }
                    }

                    finishLoading()
                }
                BaseBean.ERROR -> {
                    finishLoading()
                    Toast.makeText(this, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }
    }

    override fun initEvent() {
        super.initEvent()

        mUpCircleMenuLayout!!.setOnMenuItemClickListener(object :UpCircleMenuLayout.OnMenuItemClickListener{
            override fun itemClick(pos: Int) {
                //根据网络判断数据选择功能
                if (mAllModularRotateImgBean!!.size != 0)
                {
                    var modelType = mAllModularRotateImgBean!![pos].mid
                    var gardenType = mAllModularRotateImgBean!![pos].garden

                    LogUtils.logD("gardenType"+modelType)
                    //加载半圆图标
                    Glide.with(applicationContext)
                        .load(Config.ApiBaseUrl + "/synchronization/previewImg?imgUrl=" + gardenType)
                        .into(iv_mymenu_center)
                    if (modelType.equals("RES_MOVIE")) {
//                        openPage(MovieFragment::class.java)
                        openPage("MovieFragment", null, CoreAnim.none,false)
                        //changePage("MovieFragment", null, CoreAnim.none)
                        //    changePage(MovieFragment::class.java)
                    }else if (modelType.equals("RES_MUSIC")) {
                        //  openPage(MusicFragment::class.java)
                        openPage("MusicFragment",null, CoreAnim.none,false)
                        //changePage("MusicFragment", null, CoreAnim.none)
//                        changePage(MusicFragment::class.java)
                    }else if (modelType.equals("RES_GAME")) {
                        //  openPage(GameFragment::class.java)
                        openPage("GameFragment", null, CoreAnim.none,false)
                        //changePage("GameFragment", null, CoreAnim.none)
                    }else if (modelType.equals("RES_NETWORK")) {
                        //  openPage(BrowserFragment::class.java)
                        openPage("BrowserFragment", null, CoreAnim.none,false)
                        //changePage("BrowserFragment", null, CoreAnim.none)
                    }else if (modelType.equals("RES_MAP")) {
                        //  openPage(MapsFragment::class.java)
                        openPage("MapsFragment", null, CoreAnim.none,false)
                        //changePage("MapsFragment", null, CoreAnim.none)
                    }else if (modelType.equals("RES_ABOUT")) {
                        //openPage(AboutFragment::class.java)
                        openPage("AboutFragment", null, CoreAnim.none,false)
                        //changePage("AboutFragment", null, CoreAnim.none)
                    }else if(modelType.equals("RES_ORDER")){
                        openPage("OrderFragment", null, CoreAnim.none,false)
                    }
                }else{
                    if (mItemTexts[pos].equals("电影")) {
                        // openPage(MovieFragment::class.java)
                        openPage("MovieFragment", null, CoreAnim.none,false)
                        //changePage("MovieFragment", null, CoreAnim.none)
                        iv_mymenu_center.setImageResource(R.mipmap.round_moive)
                    }else if (mItemTexts[pos].equals("音乐")) {
                        // openPage(MusicFragment::class.java)
                        openPage("MusicFragment",null, CoreAnim.none,false)
                        //changePage("MusicFragment", null, CoreAnim.none)
                        iv_mymenu_center.setImageResource(R.mipmap.round_music)
                    }else if (mItemTexts[pos].equals("游戏")) {
                        //  openPage(GameFragment::class.java)
                        openPage("GameFragment",null, CoreAnim.none,false)
                        //changePage("GameFragment", null, CoreAnim.none)
                        iv_mymenu_center.setImageResource(R.mipmap.round_game)
                    }else if (mItemTexts[pos].equals("浏览器")) {
                        //openPage(BrowserFragment::class.java)
                        openPage("BrowserFragment",null, CoreAnim.none,false)
                        //changePage("BrowserFragment", null, CoreAnim.none)
                        iv_mymenu_center.setImageResource(R.mipmap.round_network)
                    }else if (mItemTexts[pos].equals("地图")) {
                        //openPage(MapsFragment::class.java)
                        openPage("MapsFragment",null, CoreAnim.none,false)
                        //changePage("MapsFragment", null, CoreAnim.none)
                        iv_mymenu_center.setImageResource(R.mipmap.round_maps)
                    }else if (mItemTexts[pos].equals("关于")) {
                        // openPage(AboutFragment::class.java)
                        openPage("AboutFragment",null, CoreAnim.none,false)
                        //changePage("AboutFragment", null, CoreAnim.none)
                        iv_mymenu_center.setImageResource(R.mipmap.round_settings)
                    }
                }
            }
            override fun itemCenterClick(view: View?) {
                LogUtils.logD("click")
            }
        })

        //返回
        iv_back_page.setOnClickListener {
            this.onBackPressed()
        }

        //回到主界面
        iv_home.setOnClickListener {
            go<HomeActivity>()
            finish()
        }

        //音量调节
        iv_volume.setOnClickListener {
            PopupUtils.popupUtilsVolume(this,iv_volume)
        }

        //语言选择
        iv_language.setOnClickListener{

            val locale = resources.configuration.locale
            val languages = locale.language
            LogUtils.logD("language_lid 当前语言 $languages")

            val adapter = XUISimpleAdapter.create(this, language)
            val mListPopup = XUIListPopup<XUIListPopup<XUIListPopup<*>>>(this, adapter)
            mListPopup.create(
                DensityUtils.dp2px(150f),
                DensityUtils.dp2px(350f)) { adapterView, view, i, l -> // ToastUtils.toast("Item " + languageList.get(i).getCountryLanguage());
                //缓存存入
                SharedPrefUtils.putString(this, "language_lid", languageList[i].lid.toString() + "")
                mListPopup.dismiss()
                LogUtils.logD("language_lid "+languageList[i].name)
                val language_lid = languageList[i].name
                if (language_lid != "") {
                    try {
                        val country = language_lid!!.split("_")

                        val locale = Locale(country[0],country[1])
                        LogUtils.logD("language_lid"+country[0]+"=="+country[1] +"合成数据$locale" )
                        //设置系统语言
                        updateLocale(locale)
                    }catch (e:Exception) {
                        e.printStackTrace()
                    }
                }

                //重新加载activity
                recreateActivity()
            }

            mListPopup.setAnimStyle(XUIPopup.ANIM_GROW_FROM_CENTER)
            mListPopup.setPreferredDirection(XUIPopup.DIRECTION_TOP)
            mListPopup.show(iv_language)
        }

        //待机
        iv_power.setOnClickListener {
            fl_bg.visibility = View.VISIBLE
        }
        iv_fl_power.setOnClickListener {
            fl_bg.visibility = View.INVISIBLE
        }

        //背光设置
        iv_brightness.setOnClickListener {
            PopupUtils.popupUtilsbrightness(this,iv_brightness)
        }

        //解决穿透问题
        fl_bg.setOnTouchListener(object :View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                return true
            }
        });

        //点击logo5次跳转设置
        ll_main_date.setOnClickListener {
            HomeActivity.HideClick().start()
            if (HomeActivity.HideClick.sIsAlive >= 5) {
                bulletFrameSetting()
            }
        }
    }
    /**
     * 初始化图标资源
     */
    private fun initIconRes() {
        viewModel.findAllModularRotateImgBeanLiveData.observe(this){it->
            //LogUtils.logD("initIconRes"+it)
            if(it.data!!.size != 0) {
                mUpCircleMenuLayout!!.setMenuItemIconsAndTexts(it.data)
                mAllModularRotateImgBean = it.data
                //LogUtils.logD("AllModularRotateImgBean"+it.data+"==" + it.data.get(pos).mid+"=="+pos)
                //加载半圆图标
                Glide.with(this)
                    .load(Config.ApiBaseUrl + "/synchronization/previewImg?imgUrl=" + it.data.get(9).garden)
                    .into(iv_mymenu_center)
                when (it.data.get(pos).mid) {
                    "RES_MOVIE" -> {
                        openPage(MovieFragment::class.java)
                    }
                    "RES_MUSIC" -> {
                        openPage(MusicFragment::class.java)
                    }
                    "RES_GAME" -> {
                        openPage(GameFragment::class.java)
                    }
                    "RES_BROWSER" -> {
                        openPage(BrowserFragment::class.java)
                    }
                    "RES_MAP" -> {
                        openPage(MapsFragment::class.java)
                    }
                    "RES_ABOUT" -> {
                        openPage(AboutFragment::class.java)
                    }
                    "RES_ORDER" -> {
                        openPage(OrderFragment::class.java)
                    }
                }
            }
        }
    }

    /**
     * 初始化全部语言
     */
    private fun initLanguage() {
        viewModel.LanguageLiveData.observe(this){it->
            LogUtils.logD("main"+it)
            if(it != null)
            {
                language = arrayOfNulls<String>(it.size)

                for((index,e) in it.withIndex())
                {
                    language!![index] = it[index].countryLanguage!!
                    languageList.add(it[index])
                }
            }
        }
    }

    /**
     * 初始化车辆信息
     */
    private fun initCarInfo() {
        viewModel.carinfoLiveData.observe(this){it->
            LogUtils.logD("main"+it)
            if(it != null)
            {
                viewModel.findModularAll(it[0].userId)//获取全部模块
                // viewModel.findAllModularImg(it[0].userId.toString())//获取全部模块静态资源
                viewModel.findAllModularRotateImg(it[0].userId.toString(),pos)
            }
        }
    }

    /**
     * 初始化全部模块
     */
    private fun initModular() {
        viewModel.modelAllLiveData.observe(this) {res->
            LogUtils.logD("main"+res)
            when (res?.code) {
                BaseBean.SUCCESS -> {
                    finishLoading()
                }
                BaseBean.ERROR -> {
                    finishLoading()
                    Toast.makeText(this, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }
    }

    /**
     * 初始模块id
     */
    private fun initMid() {
        viewModel.ByrtNamesLiveData.observe(this){res->
            if (res.size != 0 )
            {
                SharedPrefUtils.putString(this,"RES_MOVIE",res[0].mid.toString())
                SharedPrefUtils.putString(this,"RES_MUSIC",res[1].mid.toString())
                SharedPrefUtils.putString(this,"RES_GAME",res[2].mid.toString())
                SharedPrefUtils.putString(this,"RES_NETWORK",res[3].mid.toString())
                SharedPrefUtils.putString(this,"RES_MAP",res[4].mid.toString())
                SharedPrefUtils.putString(this,"RES_ABOUT",res[5].mid.toString())
            }
        }
    }


    /**
     * 弹框方法
     */
    private fun bulletFrameSetting(){
        MaterialDialog.Builder(this)
            .title("Password")
            .inputType(
                InputType.TYPE_CLASS_TEXT
                        or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                        or InputType.TYPE_TEXT_FLAG_CAP_WORDS
            )
            .input("Please enter your password", "", false,
                MaterialDialog.InputCallback { dialog: MaterialDialog?, input: CharSequence ->
                    if (input.toString() == Config.pwd) {
                        val mIntent = Intent(applicationContext, SettingsActivity::class.java)
                        mIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        startActivity(mIntent)
                    }else{
                        bulletFrameSetting()
                        Toast.makeText(this,"PassWord Error",Toast.LENGTH_LONG).show()
                    }
                }
            )
            .inputRange(5, 10)
            .positiveText("Confirm")
            .negativeText("Cancel")
            .cancelable(false)
            .show()
    }


    /**
     * 更新语言
     */
    protected fun updateLocale(locale: Locale?) {
        try {
            val config = this.resources.configuration
            val dm = resources.displayMetrics
            config.locale = locale
            resources.updateConfiguration(config, dm)
          //  recreate()
        } catch (e: Exception) {
            // Intentionally left blank
        }
    }
    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }
    private fun recreateActivity() {
        finish()
        startActivity(intent)
        //清除Activity退出和进入的动画
        overridePendingTransition(0, 0)
    }
    /**
     * onStart
     * 广播更新时间
     */
    override fun onStart() {
        super.onStart()
        //初始化当前时间
        LogUtils.logD("初始化当前时间")
        var dateString =  SharedPrefUtils.getString(this,"newDate")
        Log.d("onStart", "onStart: $dateString")
        Log.d("onStart——系统时间", "onStart:"+System.currentTimeMillis())
//        var date: Date = Date(System.currentTimeMillis())
        var dateLong =0L
        try {
             dateLong = dateString.toLong()
        } catch ( e : NumberFormatException){
            Log.e(TAG, "onStart: ", e)
        }
        var date: Date = Date(dateLong)
        val time = DateUtils.getTime(date)
        val dates = DateUtils.getDate(date)
        val week = DateUtils.getWeekOfDate(date)
        Log.d(TAG, "onStart: $date $dates $time $week")
        tv_main_time.text = time
        tv_main_week.text = "$dates  $week"
        //动态注册广播
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_TIME_TICK)
        registerReceiver(receiver, filter)

    }
    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
    }
    /**
     * 时间广播更新
     */
    inner class broadCastRecever : BroadcastReceiver() {
        //广播接收器
        override fun onReceive(context: Context?, intent: Intent?) {//接收广播后执行的操作
            var action: String? = intent!!.action
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                //获取当前时间
                var date: Date = Date(System.currentTimeMillis())
                var time = DateUtils.getTime(date)
                var dates = DateUtils.getDate(date)
                var week = DateUtils.getWeekOfDate(date)
                tv_main_time.text = time
                tv_main_week.text = "$dates $week"
            }
        }
    }
}