package com.jld.vod.service

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.view.WindowManager
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.room.Room
import com.google.android.gms.maps.model.LatLng
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.jld.vod.R
import com.jld.vod.config.Config
import com.jld.vod.db.CarSiteAllDatabase
import com.jld.vod.model.bean.*
import com.jld.vod.model.event.MapsEvent
import com.jld.vod.model.event.SiteEvent
import com.jld.vod.utils.LatLongUtils
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.http.OkHttpUtils
import com.jld.vod.utils.SharedPrefUtils
import com.jld.vod.view.widget.CustomGEOAdDialog
import com.jld.vod.viewmodel.MainViewModel
import okhttp3.Call
import okhttp3.Response
import org.greenrobot.eventbus.EventBus
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL


/**
 * @author ZhaoFuXin
 * @Email：18276061387@163.com
 * @description:
 * @date :2020/9/18 14:03
 */
class LatLongService :Service() {
    private var gson:Gson?= null
    private  var carsitealldb:CarSiteAllDatabase? =null
    private var siteId:Long?= 0
    private var sitearr = arrayOfNulls<Long>(2)

    private var indexsite:Int = 0
    private var carinfo:CarSiteAllBean?=null

    private lateinit var mCustom : CustomGEOAdDialog
    private var mContext: Context ?= null

    private val mHandler: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1->{
                    val result: String = msg.obj.toString()
                    // 把定位信息广播发送出去
                    EventBus.getDefault().post(MapsEvent(result))

                    try {
                        val latlng = gson!!.fromJson(result, LatLongBean::class.java)
                        var min :Double = 1000.0
                        Thread(Runnable {
                            var mCarSiteAll: List<CarSiteAllBean> =  carsitealldb!!.carSiteAllDao().getAll()
                            //查询数据库的站点信息，根据当前定位报站
                            if (latlng!=null && mCarSiteAll.isNotEmpty() && latlng.flag) {
                                LogUtils.logD("进入报站：$latlng")
                                //获取本地经纬度
                                val Latitude = latlng.data.Latitude
                                val Longitude = latlng.data.Longitude

                                val location = LatLng(Latitude, Longitude)

                                //判断不超出经纬度范围
                                if (Longitude <= 180 && Longitude >= -180 && Latitude <= 90 && Latitude >= -90) {

                                    for ((index, data) in mCarSiteAll.withIndex()) {
                                       //LogUtils.logD("距离=test"+data.name)
                                        //站台的位置
                                        val lat: Double = data.latitude.toDouble()
                                        val lng: Double = data.longitude.toDouble()
                                        val plalocation = LatLng(lat, lng)//定位值

                                        //根据经纬度测算距离(米)
                                        val Distance: Double = LatLongUtils.getDistance(location, plalocation)
                                        //LogUtils.logD("距离all="+data.name+Distance)
                                        //设置距离站点，然后报站
                                        if (Distance <= 1000) {
                                            //LogUtils.logD("距离<1000="+Distance)
                                            //判断最短距离报站
                                            if(min > Distance) {
                                                min = Distance
                                                indexsite = index
                                                carinfo = data
                                            }
                                        }
                                    }
                                    //LogUtils.logD("距离min="+min+"indexsite$indexsite"+"carinfo$carinfo")
                                    // 把到站的站点广播发送出去
                                    EventBus.getDefault().post(SiteEvent(indexsite+1))
                                    SharedPrefUtils.putInt(applicationContext,"SiteEvent",indexsite+1)//把到站点缓存
                                    //通过id报站判断是否相同重复报站
                                    if(carinfo!=null){
                                        val siteIds = carinfo!!.siteId //记录当前站点id
                                       // LogUtils.logD("siteIds="+siteIds+"====siteId"+data.siteId)
                                        if (siteIds != siteId) {//判断不是同一个站点
                                            //报站通知
//                                            addNotification(carinfo!!.name,carinfo!!.sInfo)
                                            //预加载通知
//                                            returnBitMap(carinfo!!.sImg,carinfo!!.name,carinfo!!.sInfo)
                                            siteId = siteIds
                                            initAdVert(siteId)
//                                            //取消报站
//                                            Thread.sleep(15000)
//                                            cleanNotification()
                                        }
                                    }
                                }
                            }else{
                                LogUtils.logD("没有报站信息")
                            }
                        }).start()
                    }catch (e:Exception) {
                        e.printStackTrace()
                    }
                }
                2->{
                    //开启通知
                    val result = msg.obj as GEOAdvertBean
                    LogUtils.logD("result"+result)
                    if (result.data != null)
                    {
                        mCustom = CustomGEOAdDialog(mContext)
                        mCustom.getWindow()!!.setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
                        mCustom.setDataList(result.data)
                        mCustom.show()
                    }

                 //   addNotification(result.pat,result.info,result.bitmap)
                }
            }
        }
    }
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        mContext = this

        //初始化db
        carsitealldb = Room.databaseBuilder(this, CarSiteAllDatabase::class.java, "carsiteall").build()

        //初始化gson
        gson = Gson()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        //获取经纬度
        requestLocalLatLng()
        return super.onStartCommand(intent, flags, startId)
    }

    /**
     * 初始化广告模块
     */
    private fun initAdVert(sid : Long?) {

        LogUtils.logD("sid"+sid)
        OkHttpUtils.getInstance().getDataAsyn(Config.ApiBaseUrl+"/advert/findGEOAdvert?sid="+sid,object :OkHttpUtils.MyNetCall{
            override fun failed(call: Call?, e: IOException?) {
                LogUtils.logE(e.toString())
            }
            override fun success(call: Call?, response: Response?) {
                val json = response!!.body!!.string()
                LogUtils.logD("initGEOAdVert"+json)

                val mGEOAdvertBean= gson!!.fromJson(json, GEOAdvertBean::class.java)
                val msg = Message()
                msg.what = 2
                msg.obj = mGEOAdvertBean
                mHandler.sendMessage(msg)

            }
        })
    }
    /**
     * 心跳回调
     */
    private fun requestLocalLatLng() {
        mHandler.postDelayed(Runnable {
            requestLatLng()

            //getDebugStatus(AppUtil.getDeviceSN())
            //重新调用
            requestLocalLatLng()
        }, 3000)
    }

    /**
     * 获取经纬度
     */
    private fun requestLatLng() {
        Thread(Runnable {
            try {
                val response: Response = OkHttpUtils.getInstance()
                    .getData(Config.ApiBaseUrl + "/synchronization/findGPS")
                    val res = response.body!!.string()
                    val msg = Message()
                    msg.what = 1
                    msg.obj = res
                    mHandler.sendMessage(msg)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    /**
     * 弹出到站通知
     * @param pat
     */
    private fun addNotification(pat: String,info: String,bitmap: Bitmap) {
        val intent = Intent(this, LatLongService::class.java) //点击了之后进入的一个Actity
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
        val noti =
            Notification.Builder(this) // .setTicker("你懂的！")
                .setContentTitle(pat)
                .setContentText(info)
//                .setLargeIcon(
//                    BitmapFactory.decodeResource(
//                        resources, R.mipmap.maps_dialog))
                .setLargeIcon(bitmap)//设置图片
//                .setSmallIcon(Icon.createWithContentUri(Config.ApiBaseUrl+"/synchronization/previewImg?imgUrl=$imgUrl"))
                .setSmallIcon(R.mipmap.maps_dialog) //设置图标
                .setDefaults(Notification.DEFAULT_SOUND) //设置声音
                .setContentIntent(pendingIntent) //点击之后的页面
                .setFullScreenIntent(pendingIntent, true)
                .build()
        val manager =
            this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.notify(666, noti)
    }

    /**
     * 取消到站通知
     */
    private fun cleanNotification() {
        val manager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.cancel(R.mipmap.ic_launcher)
        manager.cancel(666)
    }


    /**
     * 加载动态图片
     */
    fun returnBitMap(url: String?,pat: String,info: String) {
        Thread(Runnable {
            try {
                LogUtils.logD("imageurl:$url")
                var imageUrl  =URL(Config.ApiBaseUrl+"/synchronization/previewImg?imgUrl=$url")
                LogUtils.logD("imageurl:$imageUrl")
                val conn: HttpURLConnection = imageUrl.openConnection() as HttpURLConnection
                conn.doInput = true
                conn.connect()
                val inputStream: InputStream = conn.inputStream
                val bitmap = BitmapFactory.decodeStream(inputStream)
                inputStream.close()
                var notificationInfoBean=NotificationInfoBean(pat,info,bitmap)
                val msg = Message()
                msg.what = 2
                msg.obj = notificationInfoBean
                mHandler.sendMessage(msg)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }).start()
    }
}