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

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.mapping.view.Callout;
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.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.MarkerSymbol;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.Symbol;
import com.esri.arcgisruntime.symbology.TextSymbol;
import com.esri.arcgisruntime.util.ListenableList;
import com.lcp.arecyclerview.widget.ARecycleView;
import com.mgq.base.utils.customview.CircleImageView;
import com.mgq.base.utils.image.BitmapUtils;
import com.mgq.base.utils.toast.ToastUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
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.base.C;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.common.ui.adapter.MonitorAdapter;
import com.tofly.ghrq_route.common.ui.adapter.MonitorCarAdapter;
import com.tofly.ghrq_route.module.incident.domain.CarUploadBean;
import com.tofly.ghrq_route.module.incident.domain.DeviceUploadBean;
import com.tofly.ghrq_route.module.service.GetDeviceUploadService;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.DepartmentBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.ArcgisUtils.SizeMarkerSymbol;
import com.tofly.latte_core.base.IPresenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnItemSelected;

public class UiMonitor extends BaseMapActivity {
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.radio_group_route_mode)
    RadioGroup radioGroupMode;
    @BindView(R.id.layout_department)
    CardView layoutDepartment;
    @BindView(R.id.spinner_depart)
    AppCompatSpinner spinnerDepart;
    @BindView(R.id.incident_relview)
    ARecycleView recyclerView;
    @BindArray(R.array.monitor_sign_status)
    String[] sign_status;
    @BindArray(R.array.monitor_car_sign_status)
    String[] car_sign_status;

    private GraphicsOverlay deviceGl;
    private String selectUserid;
    private List<DeviceUploadBean> deviceUploadBeans;
    private MonitorAdapter monitorAdapter;

    private List<DepartmentBean> mDepartmentList;

    private boolean bShowCallout = true;

    private boolean mBound = false;
    private String mDepartmentId;
    private GetDeviceUploadService getDeviceUploadService = null;
    private int pageindex = 1;

    private BitmapDrawable onlineDrawable;
    private BitmapDrawable offlineDrawable;
    private MarkerSymbol onlineSymbol;
    private MarkerSymbol offlineSymbol;

    private boolean isCarMode = false;

    private List<CarUploadBean> carUploadBeans;
    private MonitorCarAdapter monitorCarAdapter;

    private BitmapDrawable onlineCarDrawable;
    private BitmapDrawable offlineCarDrawable;
    private MarkerSymbol onlineCarSymbol;
    private MarkerSymbol offlineCarSymbol;

    private void showDevices(List<DeviceUploadBean> deviceUploadBeans) {
        if (mapView == null)
            return;

        int total = 0;
        if (deviceUploadBeans != null && deviceUploadBeans.size() > 0) {
            total = deviceUploadBeans.size();
            ListenableList<GraphicsOverlay> overlays = mapView.getGraphicsOverlays();
            if (deviceGl != null) {
                deviceGl.getGraphics().clear();
            }else {
                deviceGl = new GraphicsOverlay();
                overlays.add(deviceGl);
            }

            for (DeviceUploadBean deviceUploadBean : deviceUploadBeans) {
                double lng = deviceUploadBean.getX();
                double lat = deviceUploadBean.getY();
                if (lng != 0 && lat != 0) {
                    if (TextUtils.isEmpty(selectUserid)) {
                        selectUserid = deviceUploadBean.getUserid();
                    }
                    if (deviceUploadBean.getUserid().equals(selectUserid)) {
                        showCallout(deviceUploadBean, false);
                    }

                    Point point = new Point(lng, lat, mapView.getSpatialReference());
                    int sign_state = deviceUploadBean.get_sign_state();
                    boolean isOnline = sign_state >= 1;
                    HashMap<String, Object> attributes = deviceUploadBean.getAttrsFromDevice();
                    Graphic graphic;
                    if (isOnline) {
                        graphic = new Graphic(point, attributes, onlineSymbol);
                    } else {
                        graphic = new Graphic(point, attributes, offlineSymbol);
                    }
                    deviceGl.getGraphics().add(graphic);

                    TextSymbol textSymbol = new TextSymbol();
                    textSymbol.setText(deviceUploadBean.getRealname());
                    textSymbol.setSize(14);
                    textSymbol.setFontWeight(TextSymbol.FontWeight.BOLD);
                    int color = getResources().getColor(isOnline ? R.color.blue4 : R.color.callout_text_color);
                    textSymbol.setColor(color);
                    textSymbol.setOffsetY(-25f);
                    Graphic textGraphic = new Graphic(point, textSymbol);
                    deviceGl.getGraphics().add(textGraphic);
                }
            }

            if (pageindex == 1){
                getDeviceUploadList();
            }else {
                List<DeviceUploadBean> list = deviceUploadBeans.subList(0, monitorAdapter.getItemCount());
                monitorAdapter.setData(list);
            }
        }else {
            monitorAdapter.clearAll();
            if (deviceGl != null) {
                deviceGl.getGraphics().clear();
            }
        }
        recyclerView.setTotal(total);
    }

    private void showCars(List<CarUploadBean> carUploadBeans) {
        if (mapView == null)
            return;

        int total = 0;
        if (carUploadBeans != null && carUploadBeans.size() > 0) {
            total = carUploadBeans.size();
            ListenableList<GraphicsOverlay> overlays = mapView.getGraphicsOverlays();
            if (deviceGl != null) {
                deviceGl.getGraphics().clear();
            }else {
                deviceGl = new GraphicsOverlay();
                overlays.add(deviceGl);
            }

            for (CarUploadBean carUploadBean : carUploadBeans) {
                Double lng = carUploadBean.getLng();
                Double lat = carUploadBean.getLat();
                if (lng != null && lat != null) {
                    if (TextUtils.isEmpty(selectUserid)) {
                        selectUserid = carUploadBean.getCarnum();
                    }
                    if (carUploadBean.getCarnum().equals(selectUserid)) {
                        showCarCallout(carUploadBean, false);
                    }

                    Point point = new Point(lng, lat, mapView.getSpatialReference());
                    int sign_state = carUploadBean.get_sign_state();
                    boolean isOnline = sign_state >= 1;
                    HashMap<String, Object> attributes = carUploadBean.getAttrsFromDevice();
                    Graphic graphic;
                    if (isOnline) {
                        graphic = new Graphic(point, attributes, onlineCarSymbol);
                    } else {
                        graphic = new Graphic(point, attributes, offlineCarSymbol);
                    }
                    deviceGl.getGraphics().add(graphic);

                    TextSymbol textSymbol = new TextSymbol();
                    textSymbol.setText(carUploadBean.getCarnum());
                    textSymbol.setSize(14);
                    textSymbol.setFontWeight(TextSymbol.FontWeight.BOLD);
                    int color = getResources().getColor(isOnline ? R.color.blue4 : R.color.callout_text_color);
                    textSymbol.setColor(color);
                    textSymbol.setOffsetY(-15f);
                    Graphic textGraphic = new Graphic(point, textSymbol);
                    deviceGl.getGraphics().add(textGraphic);
                }
            }

            if (pageindex == 1){
                getCarUploadList();
            }else {
                List<CarUploadBean> list = carUploadBeans.subList(0, monitorCarAdapter.getItemCount());
                monitorCarAdapter.setData(list);
            }
        }else {
            monitorCarAdapter.clearAll();
            if (deviceGl != null) {
                deviceGl.getGraphics().clear();
            }
        }
        recyclerView.setTotal(total);
    }

    private void initAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        deviceUploadBeans = new ArrayList<>();
        monitorAdapter = new MonitorAdapter(this, deviceUploadBeans);
        //recyclerView.setRootBackground(getResources().getColor(R.color.transparent));
        recyclerView.setAdapter(monitorAdapter);

        carUploadBeans = new ArrayList<>();
        monitorCarAdapter = new MonitorCarAdapter(this, carUploadBeans);
    }

    /**
     * 显示 callout
     * @param deviceUploadBean  设备信息
     * @param isZoom      是否移动
     */
    @SuppressLint("InflateParams")
    private void showCallout(DeviceUploadBean deviceUploadBean, boolean isZoom) {
        if (isZoom)
            bShowCallout = true;

        if (!bShowCallout)
            return;

        if (deviceUploadBean.getX() != 0 && deviceUploadBean.getY() != 0) {
            this.selectUserid = deviceUploadBean.getUserid();
            Point point = new Point(deviceUploadBean.getX(), deviceUploadBean.getY(), mapView.getSpatialReference());
            View view = LayoutInflater.from(this).inflate(R.layout.callout_monitor, null);
            TextView nameTv = view.findViewById(R.id.callout_incident_name);
            TextView depNameTv = view.findViewById( R.id.callout_incident_depname);
            final CircleImageView headIv = view.findViewById(R.id.callout_incident_head);
            TextView stateIv = view.findViewById(R.id.callout_incident_state);
            TextView onTimeIv = view.findViewById(R.id.callout_incident_ontime);
            TextView offTimeIv = view.findViewById(R.id.callout_incident_offtime);
            ImageView btnClose = view.findViewById(R.id.btn_feature_close);
            nameTv.setText(deviceUploadBean.getRealname());
            depNameTv.setText(deviceUploadBean.getDeptname());

//          上下班状态
            int sign_state = deviceUploadBean.get_sign_state();
            String text = "未上班";
            if (sign_state >= 0 && sign_state < sign_status.length)
                text = sign_status[sign_state];
            stateIv.setText(text);
            boolean isSignUp = sign_state >= 1;
            int colorId = isSignUp ?
                    R.color.blue4 : sign_state == -1 || sign_state == 0 ?
                    R.color.callout_text_color : R.color.red;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                stateIv.setTextColor(getResources().getColor(colorId, null));
                nameTv.setTextColor(getResources().getColor(colorId, null));
            } else {
                stateIv.setTextColor(getResources().getColor(colorId));
                nameTv.setTextColor(getResources().getColor(colorId));
            }
            if (stateIv.getText().equals("上班-GPS信号弱") || stateIv.getText().equals("上班-网络信号弱")) {
                nameTv.setTextColor(getResources().getColor(R.color.top_bar_light));
                stateIv.setTextColor(getResources().getColor(R.color.top_bar_light));
            }
            onTimeIv.setText(deviceUploadBean.getOnTime());
            offTimeIv.setText(deviceUploadBean.getOffTime());

            String userAvatar = deviceUploadBean.getAvatar();
            if (userAvatar != null && !userAvatar.isEmpty()) {
                //加载头像
                String faceurl = NetRequestURL.newApi_dyrq.getFormattedPicture(userAvatar);
                ImageLoader imageLoader = ImageLoader.getInstance();
                DisplayImageOptions displayOptions = BaseApp.getDefaultDisplayOptions();
                imageLoader.displayImage(faceurl, headIv,  displayOptions, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String s, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String s, View view, FailReason failReason) {
                        headIv.setImageDrawable(isSignUp ? onlineDrawable : offlineDrawable);
                    }

                    @Override
                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                        if (isSignUp){
                            headIv.setImageBitmap(bitmap);
                        }else {
                            Bitmap grayBitmap = BitmapUtils.saturation(bitmap, 0);
                            if (grayBitmap != null)
                                headIv.setImageBitmap(grayBitmap);
                        }
                    }

                    @Override
                    public void onLoadingCancelled(String s, View view) {

                    }
                });
            }else {
                headIv.setImageDrawable(isSignUp ? onlineDrawable : offlineDrawable);
            }
            final Callout callout = mapView.getCallout();
            if (callout.isShowing()){
                callout.setContent(view);
                callout.show(view, point);
            }else {
                callout.show(view, point);
            }

            if (isZoom) {
                mapView.setViewpointCenterAsync(point);
            }

            btnClose.setOnClickListener(v -> {
                bShowCallout = false;
                callout.dismiss();
            });
        } else {
            ToastUtil.showToast(this, "暂无该用户坐标！");
        }
    }

    @SuppressLint("InflateParams")
    private void showCarCallout(CarUploadBean carUploadBean, boolean isZoom) {
        if (isZoom)
            bShowCallout = true;

        if (!bShowCallout)
            return;

        if (carUploadBean.getLng() != null && carUploadBean.getLat() != null) {
            this.selectUserid = carUploadBean.getCarnum();
            Point point = new Point(carUploadBean.getLng(), carUploadBean.getLat(), mapView.getSpatialReference());
            View view = LayoutInflater.from(this).inflate(R.layout.callout_monitor, null);
            TextView nameTv = view.findViewById(R.id.callout_incident_name);
            TextView depNameTv = view.findViewById( R.id.callout_incident_depname);
            final CircleImageView headIv = view.findViewById(R.id.callout_incident_head);
            TextView stateIv = view.findViewById(R.id.callout_incident_state);
            TextView onTimeIv = view.findViewById(R.id.callout_incident_ontime);
            LinearLayout layoutOffTime = view.findViewById(R.id.layout_offTime);
            ImageView btnClose = view.findViewById(R.id.btn_feature_close);
            nameTv.setText(carUploadBean.getCarnum());
            depNameTv.setText(carUploadBean.getDeptname());
            layoutOffTime.setVisibility(View.GONE);

//          上下班状态
            int sign_state = carUploadBean.get_sign_state();
            String text = "未上班";
            if (sign_state >= 0 && sign_state < car_sign_status.length)
                text = car_sign_status[sign_state];
            stateIv.setText(text);
            boolean isSignUp = sign_state >= 1;
            int colorId = isSignUp ?
                    R.color.blue4 : sign_state == -1 || sign_state == 0 ?
                    R.color.callout_text_color : R.color.red;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                stateIv.setTextColor(getResources().getColor(colorId, null));
                nameTv.setTextColor(getResources().getColor(colorId, null));
            } else {
                stateIv.setTextColor(getResources().getColor(colorId));
                nameTv.setTextColor(getResources().getColor(colorId));
            }
            onTimeIv.setText(carUploadBean.getOnTime());

            String userAvatar = carUploadBean.getAvatar();
            if (userAvatar != null && !userAvatar.isEmpty()) {
                //加载头像
                String faceurl = NetRequestURL.newApi_dyrq.getFormattedPicture(userAvatar);
                ImageLoader imageLoader = ImageLoader.getInstance();
                DisplayImageOptions displayOptions = BaseApp.getDefaultDisplayOptions();
                imageLoader.displayImage(faceurl, headIv,  displayOptions, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String s, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String s, View view, FailReason failReason) {
                        headIv.setImageDrawable(isSignUp ? onlineCarDrawable : offlineCarDrawable);
                    }

                    @Override
                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                        if (isSignUp){
                            headIv.setImageBitmap(bitmap);
                        }else {
                            Bitmap grayBitmap = BitmapUtils.saturation(bitmap, 0);
                            if (grayBitmap != null)
                                headIv.setImageBitmap(grayBitmap);
                        }
                    }

                    @Override
                    public void onLoadingCancelled(String s, View view) {

                    }
                });
            }else {
                headIv.setImageDrawable(isSignUp ? onlineCarDrawable : offlineCarDrawable);
            }
            final Callout callout = mapView.getCallout();
            if (callout.isShowing()){
                callout.setContent(view);
                callout.show(view, point);
            }else {
                callout.show(view, point);
            }

            if (isZoom) {
                mapView.setViewpointCenterAsync(point);
            }

            btnClose.setOnClickListener(v -> {
                bShowCallout = false;
                callout.dismiss();
            });
        } else {
            ToastUtil.showToast(this, "暂无该用户坐标！");
        }
    }

    private void hideCallout() {
        Callout callout = mapView.getCallout();
        if (callout != null) {
            callout.dismiss();
            bShowCallout = false;
        }
    }

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

        int size = BaseApp.dip2px(12);
        onlineDrawable = (BitmapDrawable) getResources().getDrawable(R.mipmap.ic_peopel_head);
        onlineSymbol = SizeMarkerSymbol.sizeSymbol(onlineDrawable, size, size);
        offlineDrawable = (BitmapDrawable) getResources().getDrawable(R.mipmap.ic_people_head_offline);
        offlineSymbol = SizeMarkerSymbol.sizeSymbol(offlineDrawable, size, size);

        onlineCarDrawable = (BitmapDrawable) getResources().getDrawable(R.mipmap.ic_car_head);
        onlineCarSymbol = SizeMarkerSymbol.sizeSymbol(onlineCarDrawable, size, size);
        offlineCarDrawable = (BitmapDrawable) getResources().getDrawable(R.mipmap.ic_car_head_offline);
        offlineCarSymbol = SizeMarkerSymbol.sizeSymbol(offlineCarDrawable, size, size);

        initAdapter();
    }

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

        initListener();

        bindService();
        getDepartAssigner();
    }

    protected void initListener() {
        mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent event) {
                onMapTaped(event.getX(), event.getY());
                return true;
            }
        });

        recyclerView.setOnLoadMoreListener(() -> {
            pageindex++;
            getDeviceUploadList();
        });

        monitorAdapter.setOnItemClickListener((view, position) -> {
            DeviceUploadBean deviceBean = monitorAdapter.getItem(position);
            if (deviceBean != null){
                showCallout(deviceBean, true);
            }
        });

        monitorCarAdapter.setOnItemClickListener((view, position) -> {
            CarUploadBean carUploadBean = monitorCarAdapter.getItem(position);
            if (carUploadBean != null){
                showCarCallout(carUploadBean, true);
            }
        });
    }

    private void getDepartAssigner() {
        if (mDepartmentList == null || mDepartmentList.isEmpty()) {
            getDepartments();
        }
    }

    private void getDepartments() {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartments(this, false, new UserCallBack(){
            @Override
            public void onGetDepartmentList(boolean isSuccess, int errorCode, String errMsg, List<DepartmentBean> departmentList) {
                super.onGetDepartmentList(isSuccess, errorCode, errMsg, departmentList);
                if (isSuccess) {
                    mDepartmentList = departmentList;
                    setDepartmentAdapter();
                }
            }
        });
    }

    private void setDepartmentAdapter(){
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        List<String> departNameList = new ArrayList<>();
        int index = -1;
        for (int i = 0; i < mDepartmentList.size(); i++) {
            DepartmentBean departmentBean = mDepartmentList.get(i);
            departNameList.add(departmentBean.getName());
            if (userBean != null && userBean.getDepartmentId() != null) {
                if (departmentBean.getId().equals(userBean.getDepartmentId())) {
                    index = i;
                }
            }
        }
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                R.layout.my_simple_spinner_item, departNameList){
        };
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        //加载适配器
        spinnerDepart.setAdapter(adapterDevType);

        if (index >= 0)
            spinnerDepart.setSelection(index);
    }

    private void onMapTaped(float x, float y) {
        if (deviceGl != null) {
            android.graphics.Point screenPoint = new android.graphics.Point(Math.round(x), Math.round(y));
            ListenableFuture<IdentifyGraphicsOverlayResult> future =
                    mapView.identifyGraphicsOverlayAsync(deviceGl, screenPoint, 15, false, 10);
            future.addDoneListener(() -> {
                try {
                    IdentifyGraphicsOverlayResult result = future.get();
                    List<Graphic> graphics = result.getGraphics();
                    if (graphics != null && graphics.size() > 0) {
                        if (isCarMode) {
                            showTapedCars(graphics);
                        }else {
                            showTapedDevices(graphics);
                        }
                    }else {
                        Toast.makeText(this, "未点击到用户", Toast.LENGTH_SHORT).show();
                    }
                } catch (ExecutionException | InterruptedException ex) {
                    ex.printStackTrace();
                }
            });
        }
    }

    private void showTapedDevices(List<Graphic> graphics) {
        deviceGl.clearSelection();
        List<String> nameList = new ArrayList<>();
        final ArrayList<DeviceUploadBean> deviceUploadBeans = new ArrayList<>();
        for (int i = 0; i < graphics.size(); i++) {
            Graphic graphic =  graphics.get(i);
            if (graphic != null) {
                Symbol graphicSymbol = graphic.getSymbol();
                if (graphicSymbol instanceof PictureMarkerSymbol) {
                    Map<String, Object> attributes = graphic.getAttributes();
                    if (attributes != null) {
                        DeviceUploadBean deviceUploadBean = DeviceUploadBean.getDeviceFromAttrs(attributes);
                        deviceUploadBeans.add(deviceUploadBean);
                        nameList.add(deviceUploadBean.getRealname());
                    }
                }
            }
        }
        String[] names = nameList.toArray(new String[nameList.size()]);
        new AlertDialog.Builder(UiMonitor.this).setSingleChoiceItems
                (names, -1, (dialog, which) -> {
                    DeviceUploadBean deviceUploadBean = deviceUploadBeans.get(which);
                    selectUserid = deviceUploadBean.getUserid();
                    Graphic graphic = graphics.get(which);
                    if (graphic != null)
                        graphic.setSelected(true);
                    showCallout(deviceUploadBean, true);
                    dialog.dismiss();
                }).show();
    }

    private void getDeviceUploadList() {
        if (deviceUploadBeans != null) {
            int total = deviceUploadBeans.size();
            int pagesize = C.DEFAULT_LOAD_PAGESIZE;
            int index = (pageindex - 1) * pagesize;
            int offset = index + pagesize;
            offset = Math.min(offset, total);
            if (index >= 0 && index < total) {
                List<DeviceUploadBean> devices = deviceUploadBeans.subList(index, offset);
                if (pageindex == 1) {
                    recyclerView.setTotal(total);
                    monitorAdapter.clearAll();
                }
                monitorAdapter.addAll(devices);
            }
        }

        recyclerView.postDelayed(() -> {
            recyclerView.setRefreshing(false);
            recyclerView.hideMoreProgress();
        }, 100);
    }

    private void showTapedCars(List<Graphic> graphics) {
        deviceGl.clearSelection();
        List<String> nameList = new ArrayList<>();
        final ArrayList<CarUploadBean> carUploadBeans = new ArrayList<>();
        for (int i = 0; i < graphics.size(); i++) {
            Graphic graphic =  graphics.get(i);
            if (graphic != null) {
                Symbol graphicSymbol = graphic.getSymbol();
                if (graphicSymbol instanceof PictureMarkerSymbol) {
                    Map<String, Object> attributes = graphic.getAttributes();
                    if (attributes != null) {
                        CarUploadBean carUploadBean = CarUploadBean.getCarFromAttrs(attributes);
                        carUploadBeans.add(carUploadBean);
                        nameList.add(carUploadBean.getCarnum());
                    }
                }
            }
        }
        String[] names = nameList.toArray(new String[nameList.size()]);
        new AlertDialog.Builder(UiMonitor.this).setSingleChoiceItems
                (names, -1, (dialog, which) -> {
                    CarUploadBean carUploadBean = carUploadBeans.get(which);
                    selectUserid = carUploadBean.getCarnum();
                    Graphic graphic = graphics.get(which);
                    if (graphic != null)
                        graphic.setSelected(true);
                    showCarCallout(carUploadBean, true);
                    dialog.dismiss();
                }).show();
    }

    private void getCarUploadList(){
        if (carUploadBeans != null) {
            int total = carUploadBeans.size();
            int pagesize = C.DEFAULT_LOAD_PAGESIZE;
            int index = (pageindex - 1) * pagesize;
            int offset = index + pagesize;
            offset = Math.min(offset, total);
            if (index >= 0 && index < total) {
                List<CarUploadBean> cars = carUploadBeans.subList(index, offset);
                if (pageindex == 1) {
                    recyclerView.setTotal(total);
                    monitorCarAdapter.clearAll();
                }
                monitorCarAdapter.addAll(cars);
            }
        }

        recyclerView.postDelayed(() -> {
            recyclerView.setRefreshing(false);
            recyclerView.hideMoreProgress();
        }, 100);
    }

    private void bindService() {
        Intent intent = new Intent(this, GetDeviceUploadService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void unbindService() {
        if (mBound) {
            getDeviceUploadService.stopTimer();
            unbindService(serviceConnection);
            mBound = false;
            System.out.println("解绑service");
        }
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            getDeviceUploadService = ((GetDeviceUploadService.MyBinder) service).getService();
            mBound = true;
            getDeviceUploadService.setonGetDeviceUpload(mDepartmentId, uploadBeans -> {
                deviceUploadBeans = uploadBeans;
                showDevices(uploadBeans);
            });
        }
    };

    private void renderDeviceOnMap() {
        deviceGl = new GraphicsOverlay();
        mapView.getGraphicsOverlays().add(deviceGl);
    }

    @OnItemSelected({R.id.spinner_depart})
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getId() == R.id.spinner_depart) {
            if (mDepartmentList != null) {
                if (mBound && getDeviceUploadService != null) {
                    DepartmentBean departmentBean = mDepartmentList.get(position);
                    if (departmentBean != null && departmentBean.getId() != null) {
                        mDepartmentId = departmentBean.getId();
                        getDeviceUploadService.setonGetDeviceUpload(mDepartmentId, null);
                        getDeviceUploadService.stopTimer();
                        hideCallout();

                        Handler handler = new Handler(getMainLooper());
                        handler.postDelayed(() -> {
                            pageindex = 1;
                            recyclerView.setTotal(0);
                            monitorAdapter.clearAll();
                            getDeviceUploadService.resetTimer();
                            getDeviceUploadService.setonGetDeviceUpload(mDepartmentId, uploadBeans -> {
                                deviceUploadBeans = uploadBeans;
                                showDevices(uploadBeans);
                            });
                        }, 500);
                    }
                }
            }
        }
    }

    @OnCheckedChanged({R.id.radio_btn_people, R.id.radio_btn_car})
    public void onRadioCheck(CompoundButton view, boolean isChecked){
        switch (view.getId()) {
            case R.id.radio_btn_people:
                if (isChecked) {
                    isCarMode = false;
                    layoutDepartment.setVisibility(View.VISIBLE);
                    onCarModeChanged();
                }
                break;
            case R.id.radio_btn_car:
                if (isChecked) {
                    isCarMode = true;
                    layoutDepartment.setVisibility(View.GONE);
                    onCarModeChanged();
                }
                break;
        }
    }

    private void onCarModeChanged() {
        if (mBound && getDeviceUploadService != null) {
            getDeviceUploadService.setonGetDeviceUpload(mDepartmentId, null);
            getDeviceUploadService.stopTimer();
            hideCallout();

            Handler handler = new Handler(getMainLooper());
            handler.postDelayed(() -> {
                pageindex = 1;
                recyclerView.setTotal(0);
                if (isCarMode) {
                    monitorCarAdapter.clearAll();
                    recyclerView.setAdapter(monitorCarAdapter);
                    getDeviceUploadService.setOnGetCarUpload(uploadBeans -> {
                        carUploadBeans = uploadBeans;
                        showCars(uploadBeans);
                    });
                }else {
                    monitorAdapter.clearAll();
                    recyclerView.setAdapter(monitorAdapter);
                    getDeviceUploadService.setonGetDeviceUpload(mDepartmentId, uploadBeans -> {
                        deviceUploadBeans = uploadBeans;
                        showDevices(uploadBeans);
                    });
                }
                getDeviceUploadService.resetTimer();
            }, 500);
        }
    }

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

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

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

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

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

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

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

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

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

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

        BaseApp.cancelAllRequest(getClass().getName());
    }

}
