endian11
2021-02-09 3c918119be7003cab14019ace2ccdd183f95bb0a
上传移动地图包形式的fragment 和vtpk行驶的fragment
2个文件已添加
1190 ■■■■■ 已修改文件
app/src/main/java/safeluck/drive/evaluation/fragment/ArcGisMapFragmentMMPK.java 600 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/java/safeluck/drive/evaluation/fragment/ArcGisMapFragmentVTPK.java 590 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/src/main/java/safeluck/drive/evaluation/fragment/ArcGisMapFragmentMMPK.java
New file
@@ -0,0 +1,600 @@
package safeluck.drive.evaluation.fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.anyun.basecommonlib.MyLog;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.layers.ArcGISMapImageLayer;
import com.esri.arcgisruntime.layers.ArcGISVectorTiledLayer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.MobileMapPackage;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.google.gson.Gson;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import me.yokeyword.fragmentation.SupportFragment;
import safeluck.drive.evaluation.Constant;
import safeluck.drive.evaluation.DB.exam_status.ExamStatus;
import safeluck.drive.evaluation.R;
import safeluck.drive.evaluation.bean.ExamPlatformData;
import safeluck.drive.evaluation.bean.GisCarModel;
import safeluck.drive.evaluation.bean.RTKInfoBean;
import safeluck.drive.evaluation.cEventCenter.CEventCenter;
import safeluck.drive.evaluation.cEventCenter.ICEventListener;
import safeluck.drive.evaluation.util.CThreadPoolExecutor;
import safeluck.drive.evaluation.util.FileUtil;
import safeluck.drive.evaluation.util.Utils;
/**驾校信息UI
 * MyApplication2
 * Created by lzw on 2019/3/20. 11:22:39
 * 邮箱:632393724@qq.com
 * All Rights Saved! Chongqing AnYun Tech co. LTD
 */
public class ArcGisMapFragmentMMPK extends SupportFragment implements View.OnClickListener {
    private static final String TAG = ArcGisMapFragmentMMPK.class.getSimpleName();
    private static final int ENTER = 1;//进入 科二某个项目地图
    private LinkedBlockingQueue queue = new LinkedBlockingQueue(100);
    private ExecutorService consumer = Executors.newSingleThreadExecutor();
    private ExecutorService producer = Executors.newSingleThreadExecutor();
    SimpleLineSymbol lineSymbolGls = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 0.5f);
    PointCollection points = new PointCollection(SpatialReference.create(4544));
    private Gson gson = new Gson();
    private ICEventListener icEventListener = new ICEventListener() {
        @Override
        public void onCEvent(String topic, int msgCode, int resultCode, Object obj) {
                producer.execute(()->{
                    String json = (String)obj;
                    Log.i(TAG,String.format("当前线程号%d,json=%s",Thread.currentThread().getId(),json));
                    RTKInfoBean rtkInfoBean = gson.fromJson(json,RTKInfoBean.class);
                    queue.offer(rtkInfoBean);
                });
//                MyLog.i(TAG,"处理完11.时间="+Utils.formatTimeYYMMDDHHmmSSSSS(System.currentTimeMillis()));
        }
    };
    private ICEventListener icEventListener1 = new ICEventListener() {
        @Override
        public void onCEvent(String topic, int msgCode, int resultCode, Object obj) {
            if (msgCode==13){
                ExamStatus examStatus = (ExamStatus)obj;
                if (examStatus.getMap_id()>-1){
                    if (examStatus.getEnter()==ENTER){
                        MyLog.i(TAG,String.format("进入[%d] map",examStatus.getMap_id()));
                        double scale = mMapView.getMapScale();
                        mMapView.setViewpointScaleAsync(scale * 0.2*0.2);
                    }else{
                        MyLog.i(TAG,String.format("退出[%d] map",examStatus.getMap_id()));
                        double scale = mMapView.getMapScale();
                        mMapView.setViewpointScaleAsync(scale * 5*5);
                    }
                }
            }
        }
    };
    public static SupportFragment newInstance(String s){
        ArcGisMapFragmentMMPK jiaXiaoFragment = new ArcGisMapFragmentMMPK();
        Bundle bundle = new Bundle();
        bundle.putString("arcgis_url",s);
        jiaXiaoFragment.setArguments(bundle);
        return jiaXiaoFragment;
    }
    private MapView mMapView ;
    private static final int MSG_CAR = 100;
    double yaw = 0;
    GraphicsOverlay mGraphicsOverlay;
    GraphicsOverlay mGraphicsOverlay_body;
    private double startY = 428882,startX = 3291858;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_CAR:
                    List<safeluck.drive.evaluation.bean.Point> newCarPoints = (List<safeluck.drive.evaluation.bean.Point>) msg.obj;
                    Log.i(TAG,"handle message newcarPoints.size="+newCarPoints.size());
                    drawGlses(newCarPoints,gisCarModel);
                    break;
            }
        }
    };
    PointCollection mPointCollection = new PointCollection(SpatialReference.create(4544));
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_arc_gis,container,false);
        mMapView = view.findViewById(R.id.mapView);
        view.findViewById(R.id.btn_change_map).setOnClickListener(this);
        Log.i(TAG,String.format("当前线程号%d,json=%s",Thread.currentThread().getId(),"onCreateView"));
        url = getArguments().getString("arcgis_url");
        CThreadPoolExecutor.runInBackground(()->{
            readGisCar();
        });
        consumer.execute(new CalRunnable());
        setupMap();
//        addTrailheadsLayer();
        url = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+_mActivity.getPackageName()+"/lianfang.mmpk";
        Log.i(TAG,"url ========="+url);
        final MobileMapPackage mobileMapPackage = new MobileMapPackage(url);
        mobileMapPackage.loadAsync();
        mobileMapPackage.addDoneLoadingListener(()->{
            LoadStatus loadStatus = mobileMapPackage.getLoadStatus();
            if (loadStatus==LoadStatus.LOADED){
                List<ArcGISMap> mainArcGisMapL = mobileMapPackage.getMaps();
                ArcGISMap mainArcGismapMMPK = mainArcGisMapL.get(0);
                mMapView.setMap(mainArcGismapMMPK);
            }
        });
        return view;
    }
    RTKInfoBean rtkInfoBean;
    boolean flag = true;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_change_map:
                if (ExamPlatformData.getInstance().getExamType()>ExamPlatformData.EXAM_TYPE_ChangKAO){
                    RoadDriveMapFragmentab jiaXiaoFragment = findFragment(RoadDriveMapFragmentab.class);
                    if (jiaXiaoFragment == null) {
                        jiaXiaoFragment = (RoadDriveMapFragmentab) RoadDriveMapFragmentab.newInstance();
                    }
                    startWithPop(jiaXiaoFragment);
                }else{
                    MapFragment jiaXiaoFragment = findFragment(MapFragment.class);
                    if (jiaXiaoFragment == null) {
                        jiaXiaoFragment = (MapFragment) MapFragment.newInstance();
                    }
                    startWithPop(jiaXiaoFragment);
                }
                break;
        }
    }
    class CalRunnable implements Runnable{
        @Override
        public void run() {
            while (flag){
                rtkInfoBean = (RTKInfoBean)queue.poll();
                if (rtkInfoBean != null){
                    Log.i(TAG,String.format("取出一个,queue.size=%d,rtkinfo=%s,线程号=%d",queue.size(),rtkInfoBean.toString(),Thread.currentThread().getId()));
                    yaw = rtkInfoBean.getHeading();
                    startX = rtkInfoBean.getCoord_y();
                    startY = rtkInfoBean.getCoord_x();
                    if (mMapView != null){
                        mMapView.setViewpointRotationAsync(rtkInfoBean.getHeading());
                    }
                addGraphicLayer(yaw,startX,startY);
                }
            }
        }
    }
    private void setupMap() {
        if (mMapView != null) {
            mGraphicsOverlay = addGraphicsOverlay(mMapView);
        }
    }
String url ;
    private void addTrailheadsLayer() {
        if (!TextUtils.isEmpty(url)){
            Log.i(TAG,"map_url="+url);
            final ArcGISMapImageLayer mapImageLayer = new ArcGISMapImageLayer(url);
            // create an empty map instance
            ArcGISMap map = new ArcGISMap();
            Log.i(TAG,String.format("map.getMiniScale=%f",map.getMinScale()));
            map.setMinScale(1000.0);
            // add map image layer as operational layer
            map.getOperationalLayers().add(mapImageLayer);
            mMapView.setMap(map);
        }else{
            Toast.makeText(_mActivity, "url为空", Toast.LENGTH_SHORT).show();
        }
    }
    GisCarModel gisCarModel;
    boolean once =true;
    private void addGraphicLayer(double yaw,double x,double y){
        Log.i(TAG,"addgraphicLayer开始");
        long time = System.currentTimeMillis();
        if (gisCarModel != null){
            long  qudianTime = System.currentTimeMillis();
            List<safeluck.drive.evaluation.bean.Point> carNew =Utils.getCarPoint(0,yaw,new safeluck.drive.evaluation.bean.Point(x,y),gisCarModel);
            Log.i(TAG,String.format("取到点耗时=%d毫秒,线程号=%d",System.currentTimeMillis()-qudianTime,Thread.currentThread().getId()));
            if (carNew == null) return;
            if (once){
                Message message = Message.obtain();
                message.what = MSG_CAR;
                message.obj = carNew;
                mHandler.sendMessage(message);
            }
        }
        long period= System.currentTimeMillis()-time;
        Log.i(TAG,"执行addGraphicLayer方法,耗时="+period);
    }
    private GraphicsOverlay addGraphicsOverlay(MapView mapView){
        //create the graphics overlay
        GraphicsOverlay graphicsOverlay = new GraphicsOverlay();
        mGraphicsOverlay_body = new GraphicsOverlay();
        //add the overlay to the map view
        mapView.getGraphicsOverlays().add(mGraphicsOverlay_body);
        mapView.getGraphicsOverlays().add(graphicsOverlay);
        return graphicsOverlay;
    }
    private void readGisCar() {
        String carFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+_mActivity.getPackageName()+"/lianfang_giscar.json";
        if (TextUtils.isEmpty(carFilePath)){
            MyLog.i (TAG, "GISCar车辆模型文件不存在");
            return ;
        }
        byte[] fileContentBytes= FileUtil.readFile(carFilePath);
        if (fileContentBytes !=null&&fileContentBytes.length>0){
            String buffer= new String(fileContentBytes);
            gisCarModel = new Gson().fromJson(buffer, GisCarModel.class);
        }else{
            return;
        }
    }
    PointCollection points1 = new PointCollection(SpatialReference.create(4544));
    PointCollection points2 = new PointCollection(SpatialReference.create(4544));
    PointCollection points3 = new PointCollection(SpatialReference.create(4544));
    PointCollection points4 = new PointCollection(SpatialReference.create(4544));
    SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.rgb(232,0,0), 0.5f);
    SimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.argb(255,232,0,0), lineSymbol);
    SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.WHITE, 5);
    SimpleFillSymbol simpleFillSymbolGls = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.argb(255,0,0,0), lineSymbolGls);
    private void drawGlses(List<safeluck.drive.evaluation.bean.Point> carNew,  GisCarModel gisCarModel) {
        if(gisCarModel== null){
            return;
        }
        long beginTime = System.currentTimeMillis();
/**==============================car body=========================================*/
        List<Integer> bodys =gisCarModel.getBody();
        points.clear();
        for (int i = 0; i <bodys.size(); i++) {
            points.add(carNew.get(bodys.get(i)).getX(),carNew.get(bodys.get(i)).getY());
        }
        Polygon polygon = new Polygon(points);
        Graphic graphic = new Graphic(polygon,simpleFillSymbol);
        /**===============================car body end========================================*/
/**==============================画天线=========================================*/
//        Graphic graphicAnt = new Graphic(new Point(startX,startY), simpleMarkerSymbol);
        /**==============================画天线结束 END=========================================*/
        List<Integer> leftCenterGls = gisCarModel.getLeft_center_glass();
        points1.clear();
        for (int i = 0; i < leftCenterGls.size(); i++) {
            int pos = leftCenterGls.get(i);
            points1.add(carNew.get(pos).getX(), carNew.get(pos).getY());
        }
        List<Integer> rightCenterGls = gisCarModel.getRight_center_glass();
        points2.clear();
        for (int i = 0; i < rightCenterGls.size(); i++) {
            int pos = rightCenterGls.get(i);
            points2.add(carNew.get(pos).getX(), carNew.get(pos).getY());
        }
                List<Integer> frontCLs = new ArrayList<>();
        frontCLs.addAll(gisCarModel.getLeft_front_glass());
        frontCLs.addAll(gisCarModel.getRight_front_glass());
        points3.clear();
        for (int i = 0; i < frontCLs.size(); i++) {
            int pos = frontCLs.get(i);
            points3.add(carNew.get(pos).getX(), carNew.get(pos).getY());
        }
                frontCLs.clear();
        frontCLs.addAll(gisCarModel.getLeft_rear_glass());
        frontCLs.addAll(gisCarModel.getRight_rear_glass());
        points4.clear();
        for (int i = 0; i < frontCLs.size(); i++) {
            int pos = frontCLs.get(i);
            points4.add(carNew.get(pos).getX(), carNew.get(pos).getY());
        }
        Polygon polygon1 = new Polygon(points1);
        Polygon polygon2 = new Polygon(points2);
        Polygon polygon3 = new Polygon(points3);
        Polygon polygon4 = new Polygon(points4);
        //create graphics
        Graphic buoyGraphic1 = new Graphic(polygon1, simpleFillSymbolGls);
        Graphic buoyGraphic2 = new Graphic(polygon2, simpleFillSymbolGls);
        Graphic buoyGraphic3 = new Graphic(polygon3, simpleFillSymbolGls);
        Graphic buoyGraphic4 = new Graphic(polygon4, simpleFillSymbolGls);
        //add the graphics to the graphics overlay
        /**==============================清除GraphicsOverlay上所有graphic=========================================*/
        long clearTime = System.currentTimeMillis();
        mGraphicsOverlay.getGraphics().clear();
        Log.i(TAG,"clear方法时间+"+(System.currentTimeMillis()-clearTime));
        /**==============================清除GraphicsOverlay上所有graphic   END=========================================*/
        mGraphicsOverlay.getGraphics().add(buoyGraphic1);
        mGraphicsOverlay.getGraphics().add(buoyGraphic2);
        mGraphicsOverlay.getGraphics().add(buoyGraphic3);
        mGraphicsOverlay.getGraphics().add(buoyGraphic4);
        mGraphicsOverlay_body.getGraphics().clear();
        mGraphicsOverlay_body.getGraphics().add(graphic);
//        mGraphicsOverlay.getGraphics().add(graphicAnt);
        Log.i(TAG,"GraphicsOverLay add graphic完成"+(System.currentTimeMillis()-beginTime));
        if (mMapView != null){
            mMapView.setViewpointCenterAsync(new Point(startX,startY));
        }
    }
    /**
     * 绘制面
     */
    private void drawPolygon() {
//        List<Point> points = new ArrayList<>();
//        points.add(new Point(21.21,21.32, SpatialReference.create("4544")));
//        PointCollection pointCollection = new PointCollection(points);
        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(_mActivity, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                mGraphicsOverlay.getGraphics().clear();
                Point point = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
                mPointCollection.add(point);
                Polygon polygon = new Polygon(mPointCollection);
                if (mPointCollection.size() == 1) {
                    SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 10);
                    Graphic pointGraphic = new Graphic(point, simpleMarkerSymbol);
                    mGraphicsOverlay.getGraphics().add(pointGraphic);
                }
                SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.GREEN, 3.0f);
                SimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.parseColor("#33e97676"), lineSymbol);
                Graphic graphic = new Graphic(polygon, simpleFillSymbol);
                mGraphicsOverlay.getGraphics().add(graphic);
                return super.onSingleTapConfirmed(e);
            }
        });
    }
    /**
     * 绘制点
     */
    private void drawPoint() {
        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(_mActivity, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Point clickPoint = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
                SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 20);
                Graphic graphic = new Graphic(clickPoint, simpleMarkerSymbol);
                //清除上一个点
                mGraphicsOverlay.getGraphics().clear();
                mGraphicsOverlay.getGraphics().add(graphic);
                //使用渲染器
                //                Graphic graphic1 = new Graphic(clickPoint);
                //                SimpleRenderer simpleRenderer = new SimpleRenderer(simpleMarkerSymbol);
                //                mGraphicsOverlay.setRenderer(simpleRenderer);
                //                mGraphicsOverlay.getGraphics().clear();
                //                mGraphicsOverlay.getGraphics().add(graphic1);
                return super.onSingleTapConfirmed(e);
            }
        });
    }
    /**
     * 绘制线
     */
    private void drawPolyline() {
        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(_mActivity, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Point point = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
                mPointCollection.add(point);
                Polyline polyline = new Polyline(mPointCollection);
                //点
                SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 10);
                Graphic pointGraphic = new Graphic(point, simpleMarkerSymbol);
                mGraphicsOverlay.getGraphics().add(pointGraphic);
                //线
                SimpleLineSymbol simpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.parseColor("#FC8145"), 3);
                Graphic graphic = new Graphic(polyline, simpleLineSymbol);
                mGraphicsOverlay.getGraphics().add(graphic);
                return super.onSingleTapConfirmed(e);
            }
        });
    }
    @Override
    public void onPause() {
        if (mMapView != null) {
            mMapView.pause();
        }
        super.onPause();
    }
    @Override
    public void onResume() {
        super.onResume();
        if (mMapView != null) {
            mMapView.resume();
        }
    }
    @Override
    public void onDetach() {
        super.onDetach();
        if (mMapView != null) {
            mMapView.dispose();
        }
        Log.i(TAG,"清空队列");
        flag = false;
        producer.shutdown();
        consumer .shutdown();
        queue.clear();
        CEventCenter.onBindEvent(false,icEventListener, Constant.BIND_RTK_INFO_MAP);
        CEventCenter.onBindEvent(false,icEventListener1, Constant.BIND_EXAM_STATUS_TOPIC);
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        CEventCenter.onBindEvent(true,icEventListener,Constant.BIND_RTK_INFO_MAP);
        CEventCenter.onBindEvent(true,icEventListener1,Constant.BIND_EXAM_STATUS_TOPIC);
    }
}
app/src/main/java/safeluck/drive/evaluation/fragment/ArcGisMapFragmentVTPK.java
New file
@@ -0,0 +1,590 @@
package safeluck.drive.evaluation.fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.anyun.basecommonlib.MyLog;
import com.esri.arcgisruntime.data.TileCache;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.layers.ArcGISMapImageLayer;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.layers.ArcGISVectorTiledLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import me.yokeyword.fragmentation.SupportFragment;
import safeluck.drive.evaluation.Constant;
import safeluck.drive.evaluation.DB.exam_status.ExamStatus;
import safeluck.drive.evaluation.R;
import safeluck.drive.evaluation.bean.ExamPlatformData;
import safeluck.drive.evaluation.bean.GisCarModel;
import safeluck.drive.evaluation.bean.RTKInfoBean;
import safeluck.drive.evaluation.cEventCenter.CEventCenter;
import safeluck.drive.evaluation.cEventCenter.ICEventListener;
import safeluck.drive.evaluation.util.CThreadPoolExecutor;
import safeluck.drive.evaluation.util.FileUtil;
import safeluck.drive.evaluation.util.Utils;
/**驾校信息UI
 * MyApplication2
 * Created by lzw on 2019/3/20. 11:22:39
 * 邮箱:632393724@qq.com
 * All Rights Saved! Chongqing AnYun Tech co. LTD
 */
public class ArcGisMapFragmentVTPK extends SupportFragment implements View.OnClickListener {
    private static final String TAG = ArcGisMapFragmentVTPK.class.getSimpleName();
    private static final int ENTER = 1;//进入 科二某个项目地图
    private LinkedBlockingQueue queue = new LinkedBlockingQueue(100);
    private ExecutorService consumer = Executors.newSingleThreadExecutor();
    private ExecutorService producer = Executors.newSingleThreadExecutor();
    SimpleLineSymbol lineSymbolGls = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 0.5f);
    PointCollection points = new PointCollection(SpatialReference.create(4544));
    private Gson gson = new Gson();
    private ICEventListener icEventListener = new ICEventListener() {
        @Override
        public void onCEvent(String topic, int msgCode, int resultCode, Object obj) {
                producer.execute(()->{
                    String json = (String)obj;
                    Log.i(TAG,String.format("当前线程号%d,json=%s",Thread.currentThread().getId(),json));
                    RTKInfoBean rtkInfoBean = gson.fromJson(json,RTKInfoBean.class);
                    queue.offer(rtkInfoBean);
                });
//                MyLog.i(TAG,"处理完11.时间="+Utils.formatTimeYYMMDDHHmmSSSSS(System.currentTimeMillis()));
        }
    };
    private ICEventListener icEventListener1 = new ICEventListener() {
        @Override
        public void onCEvent(String topic, int msgCode, int resultCode, Object obj) {
            if (msgCode==13){
                ExamStatus examStatus = (ExamStatus)obj;
                if (examStatus.getMap_id()>-1){
                    if (examStatus.getEnter()==ENTER){
                        MyLog.i(TAG,String.format("进入[%d] map",examStatus.getMap_id()));
                        double scale = mMapView.getMapScale();
                        mMapView.setViewpointScaleAsync(scale * 0.2*0.2);
                    }else{
                        MyLog.i(TAG,String.format("退出[%d] map",examStatus.getMap_id()));
                        double scale = mMapView.getMapScale();
                        mMapView.setViewpointScaleAsync(scale * 5*5);
                    }
                }
            }
        }
    };
    public static SupportFragment newInstance(String s){
        ArcGisMapFragmentVTPK jiaXiaoFragment = new ArcGisMapFragmentVTPK();
        Bundle bundle = new Bundle();
        bundle.putString("arcgis_url",s);
        jiaXiaoFragment.setArguments(bundle);
        return jiaXiaoFragment;
    }
    private MapView mMapView ;
    private static final int MSG_CAR = 100;
    double yaw = 0;
    GraphicsOverlay mGraphicsOverlay;
    GraphicsOverlay mGraphicsOverlay_body;
    private double startY = 428882,startX = 3291858;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_CAR:
                    List<safeluck.drive.evaluation.bean.Point> newCarPoints = (List<safeluck.drive.evaluation.bean.Point>) msg.obj;
                    Log.i(TAG,"handle message newcarPoints.size="+newCarPoints.size());
                    drawGlses(newCarPoints,gisCarModel);
                    break;
            }
        }
    };
    PointCollection mPointCollection = new PointCollection(SpatialReference.create(4544));
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_arc_gis,container,false);
        mMapView = view.findViewById(R.id.mapView);
        view.findViewById(R.id.btn_change_map).setOnClickListener(this);
        Log.i(TAG,String.format("当前线程号%d,json=%s",Thread.currentThread().getId(),"onCreateView"));
        url = getArguments().getString("arcgis_url");
        CThreadPoolExecutor.runInBackground(()->{
            readGisCar();
        });
        consumer.execute(new CalRunnable());
        setupMap();
//        addTrailheadsLayer();
        url = Environment.getExternalStorageDirectory().getAbsolutePath()+"/ArcGISTileVectorMine.vtpk";
        Log.i(TAG,"url ========="+url);
        ArcGISVectorTiledLayer arcGISTiledLayer = new ArcGISVectorTiledLayer (url);
        Basemap basemap = new Basemap(arcGISTiledLayer);
        ArcGISMap arcGISMap = new ArcGISMap(basemap);
        mMapView.setMap(arcGISMap);
        return view;
    }
    RTKInfoBean rtkInfoBean;
    boolean flag = true;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_change_map:
                if (ExamPlatformData.getInstance().getExamType()>ExamPlatformData.EXAM_TYPE_ChangKAO){
                    RoadDriveMapFragmentab jiaXiaoFragment = findFragment(RoadDriveMapFragmentab.class);
                    if (jiaXiaoFragment == null) {
                        jiaXiaoFragment = (RoadDriveMapFragmentab) RoadDriveMapFragmentab.newInstance();
                    }
                    startWithPop(jiaXiaoFragment);
                }else{
                    MapFragment jiaXiaoFragment = findFragment(MapFragment.class);
                    if (jiaXiaoFragment == null) {
                        jiaXiaoFragment = (MapFragment) MapFragment.newInstance();
                    }
                    startWithPop(jiaXiaoFragment);
                }
                break;
        }
    }
    class CalRunnable implements Runnable{
        @Override
        public void run() {
            while (flag){
                rtkInfoBean = (RTKInfoBean)queue.poll();
                if (rtkInfoBean != null){
                    Log.i(TAG,String.format("取出一个,queue.size=%d,rtkinfo=%s,线程号=%d",queue.size(),rtkInfoBean.toString(),Thread.currentThread().getId()));
                    yaw = rtkInfoBean.getHeading();
                    startX = rtkInfoBean.getCoord_y();
                    startY = rtkInfoBean.getCoord_x();
                addGraphicLayer(yaw,startX,startY);
                }
            }
        }
    }
    private void setupMap() {
        if (mMapView != null) {
            mGraphicsOverlay = addGraphicsOverlay(mMapView);
        }
    }
String url ;
    private void addTrailheadsLayer() {
        if (!TextUtils.isEmpty(url)){
            Log.i(TAG,"map_url="+url);
            final ArcGISMapImageLayer mapImageLayer = new ArcGISMapImageLayer(url);
            // create an empty map instance
            ArcGISMap map = new ArcGISMap();
            Log.i(TAG,String.format("map.getMiniScale=%f",map.getMinScale()));
            map.setMinScale(1000.0);
            // add map image layer as operational layer
            map.getOperationalLayers().add(mapImageLayer);
            mMapView.setMap(map);
        }else{
            Toast.makeText(_mActivity, "url为空", Toast.LENGTH_SHORT).show();
        }
    }
    GisCarModel gisCarModel;
    boolean once =true;
    private void addGraphicLayer(double yaw,double x,double y){
        Log.i(TAG,"addgraphicLayer开始");
        long time = System.currentTimeMillis();
        if (gisCarModel != null){
            long  qudianTime = System.currentTimeMillis();
            List<safeluck.drive.evaluation.bean.Point> carNew =Utils.getCarPoint(0,yaw,new safeluck.drive.evaluation.bean.Point(x,y),gisCarModel);
            Log.i(TAG,String.format("取到点耗时=%d毫秒,线程号=%d",System.currentTimeMillis()-qudianTime,Thread.currentThread().getId()));
            if (carNew == null) return;
            if (once){
                Message message = Message.obtain();
                message.what = MSG_CAR;
                message.obj = carNew;
                mHandler.sendMessage(message);
            }
        }
        long period= System.currentTimeMillis()-time;
        Log.i(TAG,"执行addGraphicLayer方法,耗时="+period);
    }
    private GraphicsOverlay addGraphicsOverlay(MapView mapView){
        //create the graphics overlay
        GraphicsOverlay graphicsOverlay = new GraphicsOverlay();
        mGraphicsOverlay_body = new GraphicsOverlay();
        //add the overlay to the map view
        mapView.getGraphicsOverlays().add(mGraphicsOverlay_body);
        mapView.getGraphicsOverlays().add(graphicsOverlay);
        return graphicsOverlay;
    }
    private void readGisCar() {
        String carFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+_mActivity.getPackageName()+"/giscar.json";
        if (TextUtils.isEmpty(carFilePath)){
            MyLog.i (TAG, "GISCar车辆模型文件不存在");
            return ;
        }
        byte[] fileContentBytes= FileUtil.readFile(carFilePath);
        if (fileContentBytes !=null&&fileContentBytes.length>0){
            String buffer= new String(fileContentBytes);
            gisCarModel = new Gson().fromJson(buffer, GisCarModel.class);
        }else{
            return;
        }
    }
    PointCollection points1 = new PointCollection(SpatialReference.create(4544));
    PointCollection points2 = new PointCollection(SpatialReference.create(4544));
    PointCollection points3 = new PointCollection(SpatialReference.create(4544));
    PointCollection points4 = new PointCollection(SpatialReference.create(4544));
    SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.rgb(232,0,0), 0.5f);
    SimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.argb(255,232,0,0), lineSymbol);
    SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.WHITE, 5);
    SimpleFillSymbol simpleFillSymbolGls = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.argb(255,0,0,0), lineSymbolGls);
    private void drawGlses(List<safeluck.drive.evaluation.bean.Point> carNew,  GisCarModel gisCarModel) {
        if(gisCarModel== null){
            return;
        }
        long beginTime = System.currentTimeMillis();
/**==============================car body=========================================*/
        List<Integer> bodys =gisCarModel.getBody();
        points.clear();
        for (int i = 0; i <bodys.size(); i++) {
            points.add(carNew.get(bodys.get(i)).getX(),carNew.get(bodys.get(i)).getY());
        }
        Polygon polygon = new Polygon(points);
        Graphic graphic = new Graphic(polygon,simpleFillSymbol);
        /**===============================car body end========================================*/
/**==============================画天线=========================================*/
//        Graphic graphicAnt = new Graphic(new Point(startX,startY), simpleMarkerSymbol);
        /**==============================画天线结束 END=========================================*/
        List<Integer> leftCenterGls = gisCarModel.getLeft_center_glass();
        points1.clear();
        for (int i = 0; i < leftCenterGls.size(); i++) {
            int pos = leftCenterGls.get(i);
            points1.add(carNew.get(pos).getX(), carNew.get(pos).getY());
        }
        List<Integer> rightCenterGls = gisCarModel.getRight_center_glass();
        points2.clear();
        for (int i = 0; i < leftCenterGls.size(); i++) {
            int pos = rightCenterGls.get(i);
            points2.add(carNew.get(pos).getX(), carNew.get(pos).getY());
        }
                List<Integer> frontCLs = new ArrayList<>();
        frontCLs.addAll(gisCarModel.getLeft_front_glass());
        frontCLs.addAll(gisCarModel.getRight_front_glass());
        points3.clear();
        for (int i = 0; i < frontCLs.size(); i++) {
            int pos = frontCLs.get(i);
            points3.add(carNew.get(pos).getX(), carNew.get(pos).getY());
        }
                frontCLs.clear();
        frontCLs.addAll(gisCarModel.getLeft_rear_glass());
        frontCLs.addAll(gisCarModel.getRight_rear_glass());
        points4.clear();
        for (int i = 0; i < frontCLs.size(); i++) {
            int pos = frontCLs.get(i);
            points4.add(carNew.get(pos).getX(), carNew.get(pos).getY());
        }
        Polygon polygon1 = new Polygon(points1);
        Polygon polygon2 = new Polygon(points2);
        Polygon polygon3 = new Polygon(points3);
        Polygon polygon4 = new Polygon(points4);
        //create graphics
        Graphic buoyGraphic1 = new Graphic(polygon1, simpleFillSymbolGls);
        Graphic buoyGraphic2 = new Graphic(polygon2, simpleFillSymbolGls);
        Graphic buoyGraphic3 = new Graphic(polygon3, simpleFillSymbolGls);
        Graphic buoyGraphic4 = new Graphic(polygon4, simpleFillSymbolGls);
        //add the graphics to the graphics overlay
        /**==============================清除GraphicsOverlay上所有graphic=========================================*/
        long clearTime = System.currentTimeMillis();
        mGraphicsOverlay.getGraphics().clear();
        Log.i(TAG,"clear方法时间+"+(System.currentTimeMillis()-clearTime));
        /**==============================清除GraphicsOverlay上所有graphic   END=========================================*/
        mGraphicsOverlay.getGraphics().add(buoyGraphic1);
        mGraphicsOverlay.getGraphics().add(buoyGraphic2);
        mGraphicsOverlay.getGraphics().add(buoyGraphic3);
        mGraphicsOverlay.getGraphics().add(buoyGraphic4);
        mGraphicsOverlay_body.getGraphics().clear();
        mGraphicsOverlay_body.getGraphics().add(graphic);
//        mGraphicsOverlay.getGraphics().add(graphicAnt);
        Log.i(TAG,"GraphicsOverLay add graphic完成"+(System.currentTimeMillis()-beginTime));
//        if (mMapView != null){
//            mMapView.setViewpointCenterAsync(new Point(startX,startY));
//        }
    }
    /**
     * 绘制面
     */
    private void drawPolygon() {
//        List<Point> points = new ArrayList<>();
//        points.add(new Point(21.21,21.32, SpatialReference.create("4544")));
//        PointCollection pointCollection = new PointCollection(points);
        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(_mActivity, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                mGraphicsOverlay.getGraphics().clear();
                Point point = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
                mPointCollection.add(point);
                Polygon polygon = new Polygon(mPointCollection);
                if (mPointCollection.size() == 1) {
                    SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 10);
                    Graphic pointGraphic = new Graphic(point, simpleMarkerSymbol);
                    mGraphicsOverlay.getGraphics().add(pointGraphic);
                }
                SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.GREEN, 3.0f);
                SimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.parseColor("#33e97676"), lineSymbol);
                Graphic graphic = new Graphic(polygon, simpleFillSymbol);
                mGraphicsOverlay.getGraphics().add(graphic);
                return super.onSingleTapConfirmed(e);
            }
        });
    }
    /**
     * 绘制点
     */
    private void drawPoint() {
        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(_mActivity, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Point clickPoint = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
                SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 20);
                Graphic graphic = new Graphic(clickPoint, simpleMarkerSymbol);
                //清除上一个点
                mGraphicsOverlay.getGraphics().clear();
                mGraphicsOverlay.getGraphics().add(graphic);
                //使用渲染器
                //                Graphic graphic1 = new Graphic(clickPoint);
                //                SimpleRenderer simpleRenderer = new SimpleRenderer(simpleMarkerSymbol);
                //                mGraphicsOverlay.setRenderer(simpleRenderer);
                //                mGraphicsOverlay.getGraphics().clear();
                //                mGraphicsOverlay.getGraphics().add(graphic1);
                return super.onSingleTapConfirmed(e);
            }
        });
    }
    /**
     * 绘制线
     */
    private void drawPolyline() {
        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(_mActivity, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Point point = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
                mPointCollection.add(point);
                Polyline polyline = new Polyline(mPointCollection);
                //点
                SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 10);
                Graphic pointGraphic = new Graphic(point, simpleMarkerSymbol);
                mGraphicsOverlay.getGraphics().add(pointGraphic);
                //线
                SimpleLineSymbol simpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.parseColor("#FC8145"), 3);
                Graphic graphic = new Graphic(polyline, simpleLineSymbol);
                mGraphicsOverlay.getGraphics().add(graphic);
                return super.onSingleTapConfirmed(e);
            }
        });
    }
    @Override
    public void onPause() {
        if (mMapView != null) {
            mMapView.pause();
        }
        super.onPause();
    }
    @Override
    public void onResume() {
        super.onResume();
        if (mMapView != null) {
            mMapView.resume();
        }
    }
    @Override
    public void onDetach() {
        super.onDetach();
        if (mMapView != null) {
            mMapView.dispose();
        }
        Log.i(TAG,"清空队列");
        flag = false;
        producer.shutdown();
        consumer .shutdown();
        queue.clear();
        CEventCenter.onBindEvent(false,icEventListener, Constant.BIND_RTK_INFO_MAP);
        CEventCenter.onBindEvent(false,icEventListener1, Constant.BIND_EXAM_STATUS_TOPIC);
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        CEventCenter.onBindEvent(true,icEventListener,Constant.BIND_RTK_INFO_MAP);
        CEventCenter.onBindEvent(true,icEventListener1,Constant.BIND_EXAM_STATUS_TOPIC);
    }
}