package com.jld.vod.view

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import com.google.gson.Gson
import com.jld.vod.R
import com.jld.vod.base.BaseActivity
import com.jld.vod.config.Config
import com.jld.vod.model.bean.ResultBean
import com.jld.vod.utils.http.OkHttpUtils
import okhttp3.Response

class SettingActivity : BaseActivity() ,View.OnClickListener{

    private var settingStart: LinearLayout? = null
    private var settingEnd: LinearLayout? = null
    private var settingDel: LinearLayout? = null
    private var ivBackPages: ImageView? = null
    private var settingSingle: LinearLayout? = null
    private var ivWIFIPages: ImageView? = null
    private var gson: Gson?= null
    private var flagNet = false//wifi状态
    private val mHandler =
        Handler(Handler.Callback { message ->
            val result: String = message.obj.toString()
            val resultData = gson!!.fromJson(result, ResultBean::class.java)
            when (message.what) {
                1->{
                    //处理开启逻辑
                    if (resultData.flag){
                        val intent = Intent(this,SplashActivity::class.java)
                        startActivity(intent)
                        finish()
                    }else{
                        //吐司
                        toast(this.getString(R.string.tips_seat_err))
//                        toast("开启失败！设备正处于调试状态!")
                    }
                }
                2->{
                    //处理关闭逻辑
                    if (resultData.flag){
                        toast(this.getString(R.string.tips_success))
                    }else{
                        //吐司
                        toast(this.getString(R.string.tips_clear_failed))
                    }
                }
                3->{
                    //处理清除逻辑
                    if (resultData.flag){
                        toast(this.getString(R.string.tips_clear_success))
                    }else{
                        toast(this.getString(R.string.tips_clear_failed))
                    }
                }
                4->{
                    //处理连接成功逻辑
                    if (resultData.flag){
                       //在线状态
                        ivWIFIPages?.setImageResource(R.drawable.wifi)
                    }
                }
                5->{
                    //处理状态
                    if (resultData.flag){
                        ivWIFIPages?.setImageResource(R.drawable.wifi_no)
                    }else{
                        ivWIFIPages?.setImageResource(R.drawable.wifi_no_net)
                    }
                }
                6->{
                    if (resultData.flag){
                        toast(resultData.message)
                    }
                }
            }
            false
        })

    override fun getLayoutId(): Int {
       return R.layout.activity_setting
    }

    override fun initView() {
        settingStart =findViewById(R.id.ll_setting_start)//开始联动
        settingEnd =findViewById(R.id.ll_setting_end)//结束联动
        settingDel =findViewById(R.id.ll_setting_del)//清除座位信息
        ivBackPages = findViewById(R.id.iv_back_pages)//返回按键
        settingSingle =findViewById(R.id.ll_setting_single)//修改座位信息
        ivWIFIPages = findViewById(R.id.iv_back_wifi)//WIFI状态
        //绑定点击事件
        settingStart?.setOnClickListener(this)
        settingEnd?.setOnClickListener(this)
        settingDel?.setOnClickListener(this)
        settingSingle?.setOnClickListener(this)
        ivBackPages?.setOnClickListener(this)
    }

    override fun initData() {
        //初始化数
        gson = Gson()
        //WIFI循环检测
        requestWifiState()
    }

    /**
     * 心跳请求wifi状态
     */
    private fun requestWifiState() {
        mHandler.postDelayed(Runnable {
            //WIFI检测状态
            if (isWifiConnect()){
                //网络检测
                Thread(Runnable {
                    //心跳上传
                    try {
                        val response: Response = OkHttpUtils.getInstance()
                            .getData(Config.ApiBaseUrl + "/sys/HQ")
                        val res = response.body!!.string()
                        val msg = Message()
                        msg.what = 4
                        msg.obj = res
                        mHandler.sendMessage(msg)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        //网络链接异常处理
                        val msg = Message()
                        msg.what = 5
                        msg.obj = "{\"flag\":false,\"code\":20000,\"message\":\"null！\",\"data\":null}"
                        mHandler.sendMessage(msg)
                    }
                }).start()
            }else{
                //WIFI链接异常处理
                val msg = Message()
                msg.what = 5
                msg.obj = "{\"flag\":true,\"code\":20000,\"message\":\"null！\",\"data\":null}"
                mHandler.sendMessage(msg)
            }
            requestWifiState()
        }, 3000)
    }

    /**
     * 检查wifi是否处开连接状态
     *
     * @return
     */
    fun isWifiConnect(): Boolean {
        if (Config.Breed){
            //有线VOD不检测WIFI
            return true
        }
        val connManager: ConnectivityManager? =
            getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
        val mWifiInfo: NetworkInfo = connManager!!.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
        return mWifiInfo.isConnected()
    }

    //监听按钮信息
    override fun onClick(v: View?) {
        when(v?.id) {
            R.id.ll_setting_start->{
                //开始按钮
                showAlertDialog(this.getString(R.string.tips),this.getString(R.string.tips_seat_linkage),"/sys/runDeBUg",1)
            }
            R.id.ll_setting_end->{
                showAlertDialog(this.getString(R.string.tips),this.getString(R.string.tips_end_linkage),"/sys/offDebug",2)
//                //结束按钮
            }
            R.id.ll_setting_del->{
//                //清除按钮
                showAlertDialog(this.getString(R.string.tips),this.getString(R.string.tips_clear_info),"/sys/resetTerminalAll",3)
            }
            R.id.ll_setting_single->{
                val intent = Intent(this,SeatSettingsActivity::class.java)
                startActivity(intent)
                finish()
            }
            R.id.iv_back_pages->{
                Log.i("iv_back_pages", "onClick:点击返回 返回设置界面 ")
                val intent = Intent(this,SettingsActivity::class.java)
                startActivity(intent)
                finish()
            }
        }
    }

    //页面关闭执行此方法--关闭循环检测
    override fun finish() {
        super.finish()
        mHandler.removeCallbacksAndMessages(null)
    }

    private fun toastString(message: String){
        //WIFI链接异常处理
        val msg = Message()
        msg.what = 6
        msg.obj = "{\"flag\":true,\"code\":20000,\"message\":\"$message！\",\"data\":null}"
        mHandler.sendMessage(msg)
    }

    //窗体提示并执行
    private  fun showAlertDialog(title:String, message: String, url:String,handlerWhat:Int){
        //清除按钮
        val builder = AlertDialog.Builder(this)
        builder.setTitle(title)
        builder.setMessage("$message？")
        builder.setPositiveButton(R.string.cancel) {_, _ ->
        }
        builder.setNegativeButton(R.string.define) { _, _ -> run {
            Thread(Runnable {
                try {
                    val response: Response = OkHttpUtils.getInstance()
                        .getData(Config.ApiBaseUrl + url)
                    val res = response.body!!.string()
                    val msg = Message()
                    msg.what = handlerWhat
                    msg.obj = res
                    mHandler.sendMessage(msg)
                } catch (e: Exception) {
                    toastString("操作失败!，请检测网络")
                    e.printStackTrace()
                }
            }).start()
        }
      }
        val alert = builder.create()
        alert.show()
    }




}

