package com.jld.vod.view

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Message
import android.view.MotionEvent
import android.view.View
import android.widget.Button
import android.widget.TextView
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.AppUtil
import com.jld.vod.utils.http.OkHttpUtils
import com.jld.vod.utils.SharedPrefUtils
import okhttp3.Response

/**
 * 座位号联动设置
 */
class LinkageSeatSettingsActivity : BaseActivity() {
    private val TAG:String = "LinkageSeatSettingsActivity"
    private var gson: Gson?= null
    private var mContent: TextView? = null
    private var content :String ?= null
    private  val deviceSN: String = AppUtil.getDeviceSN()
    private var confirm : Boolean  = false
    private var offDebug: Button ?= null
    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(content=="0"){
                        mContent?.setBackgroundResource(R.drawable.tv_splash_num)
                    }else if (content!=resultData.data) {
                        confirm = false
                        mContent?.setBackgroundResource(R.drawable.tv_splash_num)
                    }
                    mContent!!.text = resultData.data//设置座位号显示
                    content = resultData.data//保存临时座位号
                    if (!resultData.flag){
                        SharedPrefUtils.putString(this,"seatid",content)//存入座位号
                        val intent = Intent(this,SplashActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
                }
                2->{
                    if(resultData.flag){
                        //确认座位号
                        mContent?.setBackgroundResource(R.drawable.tv_splash_num_confirm)
                        toast( this.getString(R.string.confirm_success)+"！")
                    }
                }
                3->{
                    if (resultData.flag){
                        //取消座位号确认
                        mContent?.setBackgroundResource(R.drawable.tv_splash_num)
                        toast(this.getString(R.string.cancel_confirmation_successful)+"！")
                    }
                }
                4->{
                    if (resultData.flag) {
                        toast(this.getString(R.string.tips_success))
                    }
                }
                5->{
                    if (resultData.flag) {
                        toast(resultData.message)
                    }
                }
            }
            false
        })

    override fun getLayoutId(): Int {
        return R.layout.activity_seat_linkage_settings
    }
    @SuppressLint("LongLogTag", "ClickableViewAccessibility")
    override fun initView() {
        super.initView()
        mContent = findViewById(R.id.tv_setting_content)
        offDebug = findViewById(R.id.r_button_offDebug)
        offDebug?.text = getString(R.string.setting_name_end)
        content = mContent!!.text.toString()//显示座位号
        mContent!!.setOnClickListener(View.OnClickListener{
            if (!confirm){//未确认状态
                confirm =true //转为已确认
                //设置点击监听
                Thread(Runnable {
                    try {
                        val response: Response = OkHttpUtils.getInstance()
                            .getData(Config.ApiBaseUrl + "/sys/bindSeat?id=$deviceSN")
                        val res = response.body!!.string()
                        val msg = Message()
                        msg.what = 2
                        msg.obj = res
                        mHandler.sendMessage(msg)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        toastString( this.getString(R.string.confirmation_failed)+"！")
                    }
                }).start()
            }else{
                confirm =false //转为未确认
                //清除掉当前位置以及之后的座位号
                Thread(Runnable {
                    try {
                        val response: Response = OkHttpUtils.getInstance()
                            .getData(Config.ApiBaseUrl + "/sys/cancelConfirm?id=$deviceSN")
                        val res = response.body!!.string()
                        val msg = Message()
                        msg.what = 3
                        msg.obj = res
                        mHandler.sendMessage(msg)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        toastString( this.getString(R.string.cancel_failed)+"！")
                    }
                }).start()
            }
        })
        offDebug!!.setOnClickListener (View.OnClickListener {
            //清除按钮
            val builder = AlertDialog.Builder(this)
            builder.setTitle(title)
            builder.setMessage( this.getString(R.string.tips_end_linkage)+"？")
            builder.setPositiveButton(R.string.cancel) {_, _ ->
            }
            builder.setNegativeButton(R.string.define) { _, _ -> run {
                Thread(Runnable {
                    try {
                        val response: Response = OkHttpUtils.getInstance()
                            .getData(Config.ApiBaseUrl + "/sys/offDebug")
                        val res = response.body!!.string()
                        val msg = Message()
                        msg.what = 4
                        msg.obj = res
                        mHandler.sendMessage(msg)
                    } catch (e: Exception) {
                        toastString(this.getString(R.string.please_network))
                        e.printStackTrace()
                    }
                }).start()
            }
            }
            val alert = builder.create()
            alert.show()

        })
        offDebug!!.setOnTouchListener(View.OnTouchListener { v, event ->
                //抬起
                if(event.action == MotionEvent.ACTION_UP){
                    v.setBackgroundColor(Color.rgb(255,255,255))
                    offDebug?.animate()?.scaleX(1f)?.scaleY(1f)?.setDuration(200)?.start()
                }
                //按下
                if(event.action == MotionEvent.ACTION_DOWN){
                    v.setBackgroundColor(Color.rgb(44,173,108))
                    offDebug?.animate()?.scaleX(1.05f)?.scaleY(1.05f)?.setDuration(200)?.start()
                }
            return@OnTouchListener false
        })
    }

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

    override fun initData() {
        //初始化数
        gson = Gson()
        getDebugStatus(deviceSN)
    }
    private fun getDebugStatus(id:String){
        mHandler.postDelayed(Runnable {
            //判断是否确认了
            Thread(Runnable {
                try {
                    val response: Response = OkHttpUtils.getInstance()
                        .getData(Config.ApiBaseUrl + "/sys/getDebugStatus?id=$id")
                    val res = response.body!!.string()
                    val msg = Message()
                    msg.what = 1
                    msg.obj = res
                    mHandler.sendMessage(msg)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }).start()

            getDebugStatus(id)
        }, 1000)
    }
    //页面关闭执行此方法
    override fun finish() {
        super.finish()
        mHandler.removeCallbacksAndMessages(null)
    }
}