package com.tofly.ghrq_route.common.ui.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

import com.esri.arcgisruntime.geometry.Part;
import com.esri.arcgisruntime.geometry.PartCollection;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.Polyline;
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.MarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.util.ListenableList;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseMapActivity;
import com.tofly.ghrq_route.common.util.ArcgisUtils.ArcgisUtils;
import com.tofly.ghrq_route.common.util.ArcgisUtils.SizeMarkerSymbol;
import com.tofly.ghrq_route.module.map.controller.MapController;
import com.tofly.ghrq_route.module.plan.PlanTool;
import com.tofly.ghrq_route.module.plan.domain.OfflinePathBean;
import com.tofly.ghrq_route.module.plan.domain.PlanBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.latte_core.base.IPresenter;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by zombiexq on 2016/7/4.
 */
public class UiPlanMapPoint extends BaseMapActivity {
    @BindView(R.id.mapview)
    MapView mapView;

    private PlanTool planTool;

    private PlanBean mPlan;

    private GraphicsOverlay lineLayer = null;

    private GraphicsOverlay overLineLayer = null;

    private GraphicsOverlay serviceLocationLayer = null;
    private Graphic locationGraphic = null;
    private Graphic locCircleGraphic = null;
    private MarkerSymbol locationSymbol = null;
    private MarkerSymbol locationCarSymbol = null;
    private SimpleLineSymbol locCircleSymbol = null;

    @Override
    public int setLayout() {
        return R.layout.ui_plan_map_point;
    }

    @Override
    protected IPresenter createPresenter() {
        return null;
    }

    @Override
    public void initView() {
        super.initView();

        setDarkStatusBar();

        BitmapDrawable serviceLoc = (BitmapDrawable)getResources().getDrawable(R.drawable.ic_people_purple_400_24dp);
        locationSymbol = SizeMarkerSymbol.sizeSymbol(serviceLoc, 24, 24);
        BitmapDrawable serviceCarLoc = (BitmapDrawable)getResources().getDrawable(R.mipmap.profile_car_mode);
        locationCarSymbol = SizeMarkerSymbol.sizeSymbol(serviceCarLoc, 24, 24);

        int lineColor = getResources().getColor(R.color.colorPrimary);
        locCircleSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, lineColor, 2.0f);
    }

    @Override
    public void initNet() {
        super.initNet();

        planTool = PlanTool.getInstance();
        amapLocationHelper.startLocating();

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle.containsKey("plan")) {
            mPlan = (PlanBean) bundle.getSerializable("plan");
        }
    }

    @Subscribe
    public void onMessageEvent(UiPlan.PlanEvent event) {
        switch (event.message) {
            case UiPlan.PLAN_SERVICE_LOCATION:
                Point point = (Point) event.arg0;
                if (point != null) {
                    mLocation = point;

                    MarkerSymbol symbol = mPlan.getPlan_mode() == UserBean.PATROL_TYPE_CAR ?
                            locationCarSymbol : locationSymbol;
                    if (serviceLocationLayer == null) {
                        locationGraphic = new Graphic(point, symbol);
                        GraphicsOverlay pointLayer = new GraphicsOverlay();
                        pointLayer.getGraphics().add(locationGraphic);
                        Polygon polygon = getLocationCircleGeometry(point);
                        if (polygon != null) {
                            locCircleGraphic = new Graphic(polygon, locCircleSymbol);
                            pointLayer.getGraphics().add(locCircleGraphic);
                        }
                        mapView.getGraphicsOverlays().add(pointLayer);
                        serviceLocationLayer = pointLayer;
                    } else {
                        ListenableList<Graphic> graphics = serviceLocationLayer.getGraphics();
                        for (Graphic graphic : graphics) {
                            graphic.setGeometry(point);
                        }
                        if (locationGraphic != null) {
                            serviceLocationLayer.getGraphics().remove(locationGraphic);
                            locationGraphic = new Graphic(point, symbol);
                            serviceLocationLayer.getGraphics().add(locationGraphic);
                        }
                        if (locCircleGraphic != null) {
                            serviceLocationLayer.getGraphics().remove(locCircleGraphic);
                            Polygon polygon = getLocationCircleGeometry(point);
                            if (polygon != null) {
                                locCircleGraphic = new Graphic(polygon, locCircleSymbol);
                                serviceLocationLayer.getGraphics().add(locCircleGraphic);
                            }
                        }
                    }
                }
                break;
        }
    }

    private Polygon getLocationCircleGeometry(Point point) {
        int radius = mPlan.getPlan_mode() == 0 ? BaseApp.getInstance().getPointCheckRadius():
                BaseApp.getInstance().getPointCheckRadiusCar();
        if (mPlan.isDeviceType()) {
            radius = BaseApp.getInstance().getPointCheckRadiusDevice();
        }
        double tolerance = mPlan.getTolerance();
        if (!Double.isNaN(tolerance) && tolerance > 0) {
            radius = (int) tolerance;
        }
        return ArcgisUtils.getLocationCircleGeometry(point, radius, mapView.getSpatialReference());
    }

    private void mapPointAnalyze() {
        runOnUiThread(this::showProgress);
        /*mapController.mapPointAnalyzeHttpTask(this, mapView, mPlan.getPlan_id(), mPlan.getDevice_type_name(), new MapController.OnGetPipeJobMapResult() {
            @Override
            public void onGetJobHide() {

            }

            @Override
            public void onGetJobCanceled() {
                runOnUiThread(UiPlanMapPoint.this::hideProgress);
            }

            @Override
            public void onGetResult(boolean isSuccess, PipeAnalysisResultBean resultBean, ArcGISMapImageLayer layer) {
                runOnUiThread(UiPlanMapPoint.this::hideProgress);
            }
        });*/

        String plan_id = mPlan.getPlan_id();
        PartCollection allCollection = new PartCollection(mapView.getSpatialReference());
        Map<String, List<OfflinePathBean>> pathMaps = planTool.getLocalPlanPointsOrderByPath(plan_id);
        for (Map.Entry<String, List<OfflinePathBean>> entry : pathMaps.entrySet()) {
            Part linePart = new Part(mapView.getSpatialReference());
            List<OfflinePathBean> points = entry.getValue();
            for (OfflinePathBean pathBean : points) {
                linePart.addPoint(pathBean.getLng(), pathBean.getLat());
            }
            allCollection.add(linePart);
        }

        PartCollection overCollection = new PartCollection(mapView.getSpatialReference());
        Map<String, List<OfflinePathBean>> overPathMaps = planTool.getLocalOverPlanPointsOrderByPath(plan_id);
        for (Map.Entry<String, List<OfflinePathBean>> entry : overPathMaps.entrySet()) {
            List<OfflinePathBean> points = entry.getValue();
            if (points.size() > 1) {
                Part linePart = new Part(mapView.getSpatialReference());
                for (OfflinePathBean pathBean : points) {
                    linePart.addPoint(pathBean.getLng(), pathBean.getLat());
                }
                overCollection.add(linePart);
            }
        }

        Polyline lineAll = new Polyline(allCollection, mapView.getSpatialReference());
        int lineColor = getResources().getColor(R.color.colorAccent);
        SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, lineColor, 5.0f);
        Graphic graphic = new Graphic(lineAll, lineSymbol);
        GraphicsOverlay graphicsLayer = new GraphicsOverlay();
        graphicsLayer.getGraphics().add(graphic);
        mapView.getGraphicsOverlays().add(graphicsLayer);
        lineLayer = graphicsLayer;

        Polyline lineOver = new Polyline(overCollection, mapView.getSpatialReference());
        int overColor = getResources().getColor(R.color.colorPrimary);
        SimpleLineSymbol overLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, overColor, 8.0f);
        Graphic overGraphic = new Graphic(lineOver, overLineSymbol);
        GraphicsOverlay overGraphicsLayer = new GraphicsOverlay();
        overGraphicsLayer.getGraphics().add(overGraphic);
        mapView.getGraphicsOverlays().add(overGraphicsLayer);
        overLineLayer = overGraphicsLayer;

        Handler handler = new Handler(getMainLooper());
        handler.postDelayed(() -> {
            mapView.setViewpointGeometryAsync(lineAll, ArcgisUtils.render_padding);
        }, 500);

        runOnUiThread(this::hideProgress);
    }

    private void showProgress() {
        ProgressManager.getInstance().showProgress(this, () -> {
            MapController mapController = baseMapController.mapController;
            mapController.cancelMapPointAnalyzeHttpTask();
        }, "正在查询管线数据，请稍后.", true);
    }

    private void hideProgress() {
        ProgressManager.getInstance().cancelProgress();
    }

    @OnClick({R.id.btn_back})
    public void onClick(View view){
        if (view.getId() == R.id.btn_back) {
            super.onBackPressed();
        }
    }

    @Override
    public void onBaseMapLoaded() {
        mapPointAnalyze();
    }

    @Override
    public boolean enableLoadMap() {
        return true;
    }

    @Override
    public boolean enableMoveMapListener() {
        return false;
    }

    @Override
    public boolean enableArcgisLocating() {
        return false;
    }

    @Override
    public boolean enableAmapLocationListener() {
        return true;
    }

    @Override
    public boolean enableMapMoveToLocation() {
        return true;
    }

    @Override
    public TextView getTextAddrView() {
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
