package com.tofly.ghrq_route.module.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.PowerManager;
import androidx.annotation.Nullable;
import android.util.Log;

import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.common.ui.activity.HomeActivity;
import com.tofly.ghrq_route.common.util.AlarmUtils.AlarmUtils;
import com.tofly.ghrq_route.module.gps.GpsTool;

/**
 * Created by zombiexq on 2016/7/20.
 */

public class UploadGPSService extends Service{


/*    private LocationService locationService;
    private LocationManager locationManager;
    private String padid,GPS_X,GPS_Y,address,speed,direction,radius,gpstime;
    private int locationtype;
    private GPSController gpsController;
    private DBDaoHelper dbDaoHelper;
    private List<GpsSatellite> gpsSatelliteList = new ArrayList<>();*/

    private PowerManager powerManager;
    private PowerManager.WakeLock wakeLock;

    private GpsTool gpsTool;

    private AlarmReceiver alarmReceiver;

    private boolean mbRegisterScreenOn = false;

/*    private final static int LOCATION_TYPE_GPS = 1;
    private final static int LOCATION_TYPE_CELL = 2;
    private final static int LOCATION_TYPE_WIFI = 3;

    private final static int UPLOAD_SAVED_LIMIT_COUNT = 100;*/

    public static final int REQCODE_LOCATION = 100;

    public static final String ACTION_LOCATION = "com.route.UploadGPSService.wakeup";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("UploadGPSService", "创建OnCreate");
/*        dbDaoHelper = DBDaoHelper.getInstance();*/
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

        powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, getClass().getName());
        wakeLock.acquire();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground();
/*        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        //设置每隔10分钟启动一次
        int Minutes = 10 * 60 * 1000;
        //SystemClock.elapsedRealtime()表示1970年1月1日0点至今所经历的时间
        long triggerAtTime = SystemClock.elapsedRealtime() + Minutes;
        //此处设置开启AlarmReceiver这个Service
        Intent i = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        //ELAPSED_REALTIME_WAKEUP表示让定时任务的出发时间从系统开机算起，并且会唤醒CPU。
        manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, Minutes, pi);*/

        initLocalLocationService();

        boolean isKeepScreenOn = BaseApp.getInstance().isbKeepScreenOn();
        if (isKeepScreenOn){
            alarmReceiver = new AlarmReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
            registerReceiver(alarmReceiver, intentFilter);
            mbRegisterScreenOn = true;
        }

        Log.d("UploadGPSService", "OnCommand");
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    private void startForeground(){
        //启用前台服务，主要是startForeground()
        Notification.Builder builder = new Notification.Builder(this);
        PendingIntent pendIntent = PendingIntent.getActivity(this, 0, new Intent(this, HomeActivity.class), 0);
        builder.setContentIntent(pendIntent);
        builder.setSmallIcon(R.mipmap.logo);
        builder.setContentTitle("正在上传地理位置信息");
        builder.setContentText("签到后，后台会持续上传当前的地理位置信息。");
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_SHOW_LIGHTS;
        startForeground(1, notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("UploadGPSService", "销毁OnDestroy");
/*        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务*//*
        if (locationListener != null) {
            locationManager.removeUpdates(locationListener);
        }*/
        if (wakeLock != null){
            wakeLock.release();
        }

/*        //在Service结束后关闭AlarmManager
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent i = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.cancel(pi);

        Intent intent = new Intent(this, AlarmReceiver.class);
        sendBroadcast(intent);*/

        stopForeground(true);

        gpsTool.stopLocating();
        AlarmUtils.getInstance().stopBroadcast(AlarmReceiver.class, ACTION_LOCATION, REQCODE_LOCATION);

        if (alarmReceiver != null && mbRegisterScreenOn){
            alarmReceiver.releaseWakeLock();

            unregisterReceiver(alarmReceiver);
        }

        BaseApp.cancelRequest(this.getClass().getName());
    }

    private void initLocalLocationService(){
        /*locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
        locationManager.addGpsStatusListener(this);*/
        gpsTool = GpsTool.getInstance();
        gpsTool.startLocating(this);
        int wakeTime = BaseApp.getInstance().getGpsWakeTime();
        AlarmUtils.getInstance().startBroadcast(wakeTime, AlarmReceiver.class, ACTION_LOCATION, REQCODE_LOCATION);
    }

    /*@Override
    public void onGpsStatusChanged(int event) {
        GpsStatus status = locationManager.getGpsStatus(null); // 取当前状态
        updateGpsStatus(event, status);
    }

    private void updateGpsStatus(int event, GpsStatus status) {
        if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
            int maxSatellites = status.getMaxSatellites();
            Iterator<GpsSatellite> it = status.getSatellites().iterator();
            gpsSatelliteList.clear();
            int count = 0;
            while (it.hasNext() && count <= maxSatellites) {
                GpsSatellite s = it.next();
                gpsSatelliteList.add(s);
                count++;
            }
        }
    }

    private final LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                String xx = Double.toString(location.getLongitude());
                String yy = Double.toString(location.getLatitude());
                String time = DateUtils.getDate(location.getTime());
                String speed = Float.toString(location.getSpeed());

                GPSDataBean gpsDataBean = new GPSDataBean();
                gpsDataBean.setLocation_longitude(xx);
                gpsDataBean.setLocation_latitude(yy);
                gpsDataBean.setNetwork(locationtype);
                gpsDataBean.setGpstime(time);

                Log.w("TAG",xx + " " + yy + " " + time + " " + locationtype + " " + speed);
                boolean isNetConnected = NetworkStatus.isNetworkConnected(BaseApp.getInstance());
                if (isNetConnected){
                    //上传GPS数据
                    uploadGPSInfo(gpsDataBean);
                    checkSavedGpsInfo();
                }else {
                    String gpsId = UUID.randomUUID().toString();
                    gpsDataBean.setGps_id(gpsId);
                    dbDaoHelper.insertOrUpdateGPSData(gpsDataBean);
                }
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    private void uploadGPSInfo(final GPSDataBean gpsData){
        UserBean user = BaseApp.getInstance().getLoginUser();
        if (gpsData != null){
            if (gpsController == null)
                gpsController = new GPSController(this);
            gpsController.uploadGpsInfo(user.getToken(), gpsData, new GPSCallBack(){
                @Override
                public void onUploadGpsInfo(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUploadGpsInfo(isSuccess, errorCode, errMsg);
                    if (isSuccess){

                    }else {
                        //保存在本地
                        String gpsId = UUID.randomUUID().toString();
                        gpsData.setGps_id(gpsId);
                        dbDaoHelper.insertOrUpdateGPSData(gpsData);
                    }
                }
            });
        }
    }

    private void checkSavedGpsInfo(){
        final List<GPSDataBean> savedGpsList = dbDaoHelper.getSavedGpsList(UPLOAD_SAVED_LIMIT_COUNT);
        UserBean user = BaseApp.getInstance().getLoginUser();
        if (savedGpsList.size() > 0){
            if (gpsController == null)
                gpsController = new GPSController(this);
            gpsController.uploadBatchGpsInfo(user.getToken(), savedGpsList, new GPSCallBack(){
                @Override
                public void onUploadBatchGpsInfo(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUploadBatchGpsInfo(isSuccess, errorCode, errMsg);
                    if (isSuccess){
                        dbDaoHelper.deleteSavedGps(savedGpsList);
                    }
                }
            });
        }
    }*/
}
