package com.sipai.jspatrol.background.locationservice;

import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.sipai.jspatrol.Application.App;
import com.sipai.jspatrol.Bean.PatrolLocation;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.OKHttpUtils;

import org.litepal.LitePal;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class LocationService extends NotificationService {

    private double la = 0;
    private double lo = 0;
    private String IMEI;
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid;
    private SimpleDateFormat simpleDF;
    private Date dtnow;
    private LocationClient mLocationClient;
    private MyLocationListener myListener = new MyLocationListener();
//    private List<PatrolLocation> locations = new ArrayList<>();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        return START_STICKY;
    }

    public void init() {
        SharedPreferences sharedPre = getSharedPreferences("config", MODE_PRIVATE);
        IMEI = sharedPre.getString("imei","");
        mServer = sharedPre.getString("server", "");
        mUsername = sharedPre.getString("username", "");
        mPassword = sharedPre.getString("password", "");
        mUserid = sharedPre.getString("userid", "");
        mCaption = sharedPre.getString("caption", "");
        mBizid = sharedPre.getString("bizid", "");
        simpleDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
        applyNotiKeepMech(); //开启利用notification提高进程优先级的机制
        ontimelocation();
        mLocationClient.start();
    }

    @Override
    public void onDestroy() {
        unApplyNotiKeepMech();
        stopLocation();
        super.onDestroy();
    }

    public void ontimelocation() {
        //百度
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数

        LocationClientOption option = new LocationClientOption();

//		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认GCJ02
        //GCJ02：国测局坐标；
        //BD09ll：百度经纬度坐标；
        //BD09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(2500);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(false);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，V7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
    }

    void stopLocation() {
        if (mLocationClient.isStarted()) {
            // 关闭前台定位服务
            mLocationClient.disableLocInForeground(true);
            mLocationClient.unRegisterLocationListener(myListener);
            mLocationClient.stop();
        }
    }

    /**
     * 实现实时位置回调监听
     */
    public class MyLocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            try {
                //保存全局变量
                App app = (App) getApplication();
                app.setLatitude(location.getLatitude());
                app.setLongitude(location.getLongitude());
                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();
                Log.i("LocationNow", "Sa" +":"+ "latitude:" + latitude + ",longitude" + longitude);
                if ((Math.abs(latitude - la) > 0.000001&&Math.abs(latitude - la)<0.0003)|| (Math.abs(longitude - lo) > 0.000001&&Math.abs(longitude - lo)<0.0003)) {
                    double aaa = GetDistance(longitude, latitude, lo, la);
                    String longs = String.valueOf(aaa);
                    String caca = longs.substring(0, longs.indexOf("."));
                    final int caz = Integer.parseInt(caca);
                    Log.i("LocationNow", "SaveSuccess" +":"+caz+ ",latitude:" + latitude + ",longitude" + longitude);
                    if (caz > 0 && caz < 15) {
                        PatrolLocation pos = new PatrolLocation();
                        pos.setLatitude(String.valueOf(latitude));
                        pos.setLongitude(String.valueOf(longitude));
                        pos.setUserid(mUserid);
                        dtnow = new Date(System.currentTimeMillis());
                        pos.setInsdt(simpleDF.format(dtnow));
                        pos.save();
//                        postlocation(String.valueOf(latitude), String.valueOf(longitude));
                    }
                }
                la = latitude;
                lo = longitude;
            } catch (Exception e) {
                Log.i("PatrolActivity", "exception:" + e.toString());
            }
//            List<PatrolLocation> locations = LitePal.findAll(PatrolLocation.class);
//            Gson gson = new Gson();
//            String loc_json = "{\"re1\":" + gson.toJson(locations) + "}";
//            String res = loc_json;
        }
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 计算距离
     *
     * @param longitude1
     * @param latitude1
     * @param longitude2
     * @param latitude2
     * @return
     */
    public static double GetDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        double Lat1 = rad(latitude1); // 纬度

        double Lat2 = rad(latitude2);

        double a = Lat1 - Lat2;//两点纬度之差

        double b = rad(longitude1) - rad(longitude2); //经度之差

        double s = 2 * Math.asin(Math

                .sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)));//计算两点距离的公式

        s = s * 6378137.0;//弧长乘地球半径（半径为米）

        s = Math.round(s * 10000d) / 10000d;//精确距离的数值

        return s;

    }

    //完成当前位置信息
//    private void postlocation(final String latitude, final String longitude) throws Exception {
//        PatrolLocation pl = new PatrolLocation();
//        pl.setUserid(mUserid);
//        pl.setLatitude(latitude);
//        pl.setLongitude(longitude);
//        Gson gson = new Gson();
//        String loc_json = "";
//        loc_json = gson.toJson(pl);
//        HashMap<String, String> map = new HashMap<>();
//        map.put("jsonMap",loc_json);
//        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.SubPatrolLocation_Method)).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.i("LocationNow", "onFailure: " + e.toString());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                final String res = response.body().string();
////                if (res.contains("pass")) {
////                    Log.i("LocationNow", "onSuccess: " + res + ",latitude:" + latitude + ",longitude" + longitude);
////                } else{
////                    Log.i("LocationNow", "onFailure: " + res + ",latitude:" + latitude + ",longitude" + longitude);
////                }
//            }
//        });
//
//    }


}
