package com.navinfo.outdoor.fragment;

import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.model.HttpParams;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseFragment;
import com.navinfo.outdoor.bean.PolygonTaskBean;
import com.navinfo.outdoor.bean.ReceivedBean;
import com.navinfo.outdoor.bean.ReceivedPoiBean;
import com.navinfo.outdoor.bean.TaskByNetBean;
import com.navinfo.outdoor.bean.UnPolygonTaskBean;
import com.navinfo.outdoor.http.Callback;
import com.navinfo.outdoor.http.HttpInterface;
import com.navinfo.outdoor.http.OkGoBuilder;
import com.navinfo.outdoor.room.ChargingPileDao;
import com.navinfo.outdoor.room.ChargingPileEntity;
import com.navinfo.outdoor.room.InsertAndUpdateUtils;
import com.navinfo.outdoor.room.PoiDao;
import com.navinfo.outdoor.room.PoiDatabase;
import com.navinfo.outdoor.room.PoiEntity;
import com.navinfo.outdoor.util.Geohash;
import com.navinfo.outdoor.util.GeometryTools;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;
import com.vividsolutions.jts.geom.Geometry;

import org.greenrobot.eventbus.EventBus;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 领取采集的fragment
 */
public class GatherGetFragment extends BaseFragment implements View.OnClickListener {
    private Button btnCancelGet, btnGetTask, btnGather, btnFinishGather;
    private TextView tvTitle, tvMoney, tvTime, tvDistance, tvDescribe;
    private PoiEntity poiEntity;
    private PoiDao poiDao;
    private ChargingPileDao chargingPileDao;
    private Marker poiMarker;


    public static GatherGetFragment newInstance(Bundle bundle) {
        GatherGetFragment fragment = new GatherGetFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        getFocus();
    }

    //主界面获取焦点
    private void getFocus() {
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    boolean aBoolean = getArguments().getBoolean("boolean", false);
                    Message obtain = Message.obtain();
                    obtain.what = Constant.GATHER_GET_RETURN;
                    obtain.obj = aBoolean;
                    EventBus.getDefault().post(obtain);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_gather_get;
    }

    @Override
    protected void initView() {
        super.initView();
        PoiDatabase poiDatabase = PoiDatabase.getInstance(getContext());
        poiDao = poiDatabase.getPoiDao();
        chargingPileDao = poiDatabase.getChargingPileDao();
        tvTitle = findViewById(R.id.tv_title);
        tvMoney = findViewById(R.id.tv_money);
        tvTime = findViewById(R.id.tv_time);
        tvDistance = findViewById(R.id.tv_distance);
        tvDescribe = findViewById(R.id.tv_describe);
        btnCancelGet = findViewById(R.id.btn_cancel_get);//取消领取
        btnCancelGet.setOnClickListener(this::onClick);
        btnGetTask = findViewById(R.id.btn_get_task);//领取任务
        btnGetTask.setOnClickListener(this::onClick);
        btnGather = findViewById(R.id.btn_gather);//立即采集
        btnGather.setOnClickListener(this::onClick);
        btnFinishGather = findViewById(R.id.btn_finish_gather);//结束采集
        btnFinishGather.setOnClickListener(this::onClick);
        Bundle arguments = getArguments();
        if (arguments != null) {//poiEntity
            poiEntity = (PoiEntity) arguments.getSerializable("poiEntity");
            if (poiEntity != null) {
                tvTitle.setText(poiEntity.getName());
                if (poiEntity.getPrecision() == null) {
                    tvMoney.setText("￥" + 0);
                } else {
                    tvMoney.setText("￥" + format2(Double.valueOf(poiEntity.getPrecision())));
                }
                if (poiEntity != null) {
                    if (poiEntity.getDescribe() != null && !"".equals(poiEntity.getDescribe())) {
                        tvDescribe.setText("任务描述:" + poiEntity.getDescribe());
                    }
                    if (poiEntity.getCreateTime() != null && !"".equals(poiEntity.getCreateTime())) {
                        tvTime.setText("到期时间:" + poiEntity.getCreateTime());
                    }
                }


                if (poiEntity.getDist() != null) {
                    tvDistance.setText("距离:" + format5(Double.valueOf(poiEntity.getDist()) / 1000) + "km");
                }
            }
            int taskStatus = poiEntity.getTaskStatus();
            initViewByTaskStatus(taskStatus);
        }
    }

    /**
     * 保存小数点后两位
     *
     * @param value
     * @return
     */
    public static String format2(double value) {
        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.HALF_UP);
        return df.format(value);

    }

    private void initViewByTaskStatus(int taskStatus) {
        switch (taskStatus) {
            case 0://未领取
                btnCancelGet.setVisibility(View.GONE);//取消领取
                btnGetTask.setVisibility(View.VISIBLE);//领取任务
                btnGather.setVisibility(View.VISIBLE);//立即采集
                btnFinishGather.setVisibility(View.GONE);//结束采集
                break;
            case 1://已领取
                btnCancelGet.setVisibility(View.VISIBLE);
                btnGetTask.setVisibility(View.GONE);
                btnGather.setVisibility(View.VISIBLE);
                btnFinishGather.setVisibility(View.GONE);
                break;
            case 2://已保存
            case 3://已提交
                btnCancelGet.setVisibility(View.VISIBLE);
                btnGetTask.setVisibility(View.GONE);
                btnGather.setVisibility(View.GONE);
                btnFinishGather.setVisibility(View.VISIBLE);
                break;
            case 4://结束采集
                btnCancelGet.setVisibility(View.GONE);
                btnGetTask.setVisibility(View.GONE);
                btnGather.setVisibility(View.GONE);
                btnFinishGather.setVisibility(View.GONE);
                break;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel_get://结束领取
                if (poiEntity != null) {
                    initEndReceiveTask(HttpInterface.UNRECEIVED_POLYGON_TASK, poiEntity.getTaskId(), poiEntity);
                }
                break;
            case R.id.btn_get_task://领取任务
               /* if (poiEntity.getTaskStatus() < 2) {
                    double latitude = Constant.currentLocation.getLatitude();
                    double longitude = Constant.currentLocation.getLongitude();
                    LatLng startLatLng = new LatLng(latitude, longitude);          //用户当前位置
                    LatLng endLatLng = new LatLng(Double.valueOf(poiEntity.getY()), Double.valueOf(poiEntity.getX()));
                    double geometry = GeometryTools.distanceToDouble(startLatLng, endLatLng);
                    if (geometry > 5000) {
                        Toast.makeText(getActivity(), "作业不在领取范围内,无法领取", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }*/

                if (poiEntity != null) {
                    int type = poiEntity.getType();
                    if (type == 6) {//面状任务的领取类型
                        initPolygonTask(HttpInterface.RECEIVED_POLYGON_TASK, poiEntity.getTaskId(), false);
                    } else if (type == 1) {//poi的领取类型
                        receivedTaskByNet(HttpInterface.RECEIVED_POI_TASK, poiEntity.getTaskId(), false, poiEntity, 1);
                    } else if (type == 2) {//充电站的领取类型
                        chargingTaskByWork(HttpInterface.RECEIVED_CTASK, poiEntity.getTaskId(), false, 1);
                    } else if (type == 3) {//poi录像的领取类型
                        taskByNet(HttpInterface.RECEIVED_POI_VIDEO_TASK, poiEntity.getTaskId(), false, poiEntity, 1);
                    } else if (type == 4) {//道路的领取类型
                        taskByNet(HttpInterface.RECEIVED_ROAD_TASK, poiEntity.getTaskId(), false, poiEntity, 1);
                    } else if (type == 5) {//其他的领取类型
                        receivedTaskByNet(HttpInterface.RECEIVED_OTHER_TASK, poiEntity.getTaskId(), false, poiEntity, 1);
                    }
                }
                break;
            case R.id.btn_gather://立即采集
                if (poiEntity.getTaskStatus() < 2) {
                    double latitude = Constant.currentLocation.getLatitude();
                    double longitude = Constant.currentLocation.getLongitude();
                    LatLng startLatLng = new LatLng(latitude, longitude);          //用户当前位置
                    LatLng endLatLng = new LatLng(Double.valueOf(poiEntity.getY()), Double.valueOf(poiEntity.getX()));
                    double geometry = GeometryTools.distanceToDouble(startLatLng, endLatLng);
                    if (geometry > 5000) {
                        Toast.makeText(getActivity(), "作业不在领取范围内,无法领取", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (poiEntity != null) {
                    int type = poiEntity.getType();
                    if (type == 6) {
                        int taskStatus = poiEntity.getTaskStatus();
                        if (taskStatus != 1) {

                            initPolygonTask(HttpInterface.RECEIVED_POLYGON_TASK, poiEntity.getTaskId(), true);
                        } else {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    PoiEntity taskIdPoiEntity = poiDao.getTaskIdPoiEntity(poiEntity.getTaskId());
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            initCompleteTask(HttpInterface.SUBMIT_POLYGON_TASK, poiEntity.getTaskId(), true, taskIdPoiEntity);
                                        }
                                    });
                                }
                            }).start();

                        }
                    } else if (type == 1) {//poi的领取类型
                        receivedTaskByNet(HttpInterface.RECEIVED_POI_TASK, poiEntity.getTaskId(), true, poiEntity, 5);
                    } else if (type == 2) {//充电站的领取类型
                        chargingTaskByWork(HttpInterface.RECEIVED_CTASK, poiEntity.getTaskId(), true, 5);
                    } else if (type == 3) {//poi录像的领取类型
                        taskByNet(HttpInterface.RECEIVED_POI_VIDEO_TASK, poiEntity.getTaskId(), true, poiEntity, 5);
                    } else if (type == 4) {//道路的领取类型
                        taskByNet(HttpInterface.RECEIVED_ROAD_TASK, poiEntity.getTaskId(), true, poiEntity, 5);
                    } else if (type == 5) {//其他的领取类型
                        receivedTaskByNet(HttpInterface.RECEIVED_OTHER_TASK, poiEntity.getTaskId(), true, poiEntity, 5);
                    }
                }
                break;
            case R.id.btn_finish_gather://结束采集
                if (poiEntity != null) {
                    int type = poiEntity.getType();
                    if (type == 6) {
                        initSubmitPolygonTask(HttpInterface.COMPLETE, poiEntity.getTaskId());
                    } else {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                poiDao.deletePoiEntity(poiEntity);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        poiEntity.setTaskStatus(0);
                                        initViewByTaskStatus(0);
                                    }
                                });
                            }
                        }).start();
                    }
                }
                break;
        }
    }

    /**
     * @param url 筛选充电站领取任务
     * @param
     */
    private void chargingTaskByWork(String url, int taskId, boolean isSaver, int statusId) {
        showLoadingDialog();
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(url + "/" + taskId)
                .cls(ReceivedBean.class)
                .token(Constant.ACCESS_TOKEN)
                .params(new HttpParams())
                .getRequest(new Callback<ReceivedBean>() {
                    @Override
                    public void onSuccess(ReceivedBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            ReceivedBean.BodyBean stationBean = response.getBody();
                            if (stationBean != null) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        PoiEntity taskIdPoiEntity = poiDao.getTaskIdPoiEntity(taskId);
                                        if (taskIdPoiEntity == null) {
                                            PoiEntity chargingStationEntity = new PoiEntity();
                                            chargingStationEntity.setTaskId(taskId);
                                            chargingStationEntity.setStation_type(stationBean.getSptype());
                                            chargingStationEntity.setName(stationBean.getName());
                                            chargingStationEntity.setDescribe(stationBean.getMemo());
                                            chargingStationEntity.setCreateTime(stationBean.getEndDate());
                                            chargingStationEntity.setPrecision(stationBean.getPrice() + "");
                                            chargingStationEntity.setAddress(stationBean.getAddress());
                                            chargingStationEntity.setTelPhone(stationBean.getTelephone() + "");
                                            chargingStationEntity.setType(Integer.valueOf(stationBean.getType()));
                                            chargingStationEntity.setTaskStatus(statusId);
                                            chargingStationEntity.setIsLocalData(1);

                                            String encodeStr = stationBean.getGeo();
                                            String geo = Geohash.getInstance().decode(encodeStr);
                                            chargingStationEntity.setGeoWkt(geo);
                                            Geometry geometry = GeometryTools.createGeometry(geo);
                                            if (geometry.getGeometryType().equals("Point")) {//点
                                                LatLng latLng = GeometryTools.createLatLng(geo);
                                                chargingStationEntity.setX(latLng.longitude + "");
                                                chargingStationEntity.setY(latLng.latitude + "");
                                            } else if (geometry.getGeometryType().equals("LineString")) {//线
                                                List<LatLng> latLineString = GeometryTools.getLatLngs(geo);
                                                chargingStationEntity.setX(latLineString.get(0).longitude + "");
                                                chargingStationEntity.setY(latLineString.get(0).latitude + "");
                                            } else if (geometry.getGeometryType().equals("Polygon")) {//面
                                                List<LatLng> latPolygon = GeometryTools.getLatLngs(geo);
                                                chargingStationEntity.setX(latPolygon.get(0).longitude + "");
                                                chargingStationEntity.setY(latPolygon.get(0).latitude + "");
                                            }

                                            //充电桩
                                            List<ReceivedBean.BodyBean.CsTaskListBean> csTaskList = response.getBody().getCsTaskList();
                                            if (csTaskList != null && !csTaskList.isEmpty()) {
                                                ChargingPileEntity[] chargingPileEntityList = new ChargingPileEntity[csTaskList.size()];
                                                for (int i = 0; i < csTaskList.size(); i++) {
                                                    ChargingPileEntity chargingPileEntity = new ChargingPileEntity();
                                                    chargingPileEntity.setFid(chargingStationEntity.getId());
                                                    chargingPileEntity.setName(csTaskList.get(i).getName());
                                                    chargingPileEntity.setMemo(csTaskList.get(i).getAddress());
                                                    chargingPileEntity.setP(csTaskList.get(i).getGeo());
                                                    chargingPileEntityList[i] = chargingPileEntity;
                                                }
                                                InsertAndUpdateUtils.getInstance().insertOrUpdateChargingPile(getActivity(), chargingPileEntityList);
                                            }
                                           // senMessageMarker(chargingStationEntity.getType(), chargingStationEntity.getY(), chargingStationEntity.getX());
                                            if (statusId==1){
                                                InsertAndUpdateUtils.getInstance().insertOrUpdate(getContext(), chargingStationEntity);
                                            }
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    initViewByTaskStatus(1);
                                                    if (isSaver) {
                                                        Message obtain = Message.obtain();
                                                        obtain.what = Constant.GATHER_GET_MAP;
                                                        obtain.obj = chargingStationEntity;
                                                        EventBus.getDefault().post(obtain);
                                                    }
                                                    Message obtain = Message.obtain();
                                                    obtain.what = Constant.JOB_WORD_MONITOR;
                                                    obtain.obj = true;
                                                    EventBus.getDefault().post(obtain);
                                                }
                                            });
                                        } else {
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    initViewByTaskStatus(1);
                                                    if (isSaver) {
                                                        Message obtain = Message.obtain();
                                                        obtain.what = Constant.GATHER_GET_MAP;
                                                        obtain.obj = taskIdPoiEntity;
                                                        EventBus.getDefault().post(obtain);
                                                    }
                                                    Message obtain = Message.obtain();
                                                    obtain.what = Constant.JOB_WORD_MONITOR;
                                                    obtain.obj = true;
                                                    EventBus.getDefault().post(obtain);
                                                }
                                            });
                                        }
                                    }
                                }).start();
                            }
                        } else {
                            Toast.makeText(getActivity(), response.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + e.getMessage());
                    }
                });
        dismissDialog();

    }

    /**
     * @param url 面妆任务领取任务
     * @param
     */
    private void initPolygonTask(String url, int taskId, boolean aBoolean) {
        if (taskId == 0) {
            Toast.makeText(getActivity(), "无此任务", Toast.LENGTH_SHORT).show();
            return;
        }
        showLoadingDialog();
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(url + "/" + taskId)
                .cls(PolygonTaskBean.class)
                .token(Constant.ACCESS_TOKEN)
                .params(new HttpParams())
                .getRequest(new Callback<PolygonTaskBean>() {
                    @Override
                    public void onSuccess(PolygonTaskBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {// 0.未领取 1.已领取，2.未保存(保存到本地但未提交成功),3.已保存(保存到本地提交成功)，4已上传（结束采集）,
                            PolygonTaskBean.BodyBean listBean = response.getBody();
                            PoiEntity polygonEntity = new PoiEntity();
                            if (listBean != null) {
                                polygonEntity.setTaskId(listBean.getId());
                                polygonEntity.setName(listBean.getName());
                                polygonEntity.setType(Integer.valueOf(listBean.getType()));
                                String encodeStr = listBean.getGeo();
                                String geo = Geohash.getInstance().decode(encodeStr);
                                polygonEntity.setGeoWkt(geo);
                                Geometry geometry = GeometryTools.createGeometry(geo);
                                if (geometry.getGeometryType().equals("Point")) {//点
                                    LatLng latLng = GeometryTools.createLatLng(geo);
                                    polygonEntity.setX(latLng.longitude + "");
                                    polygonEntity.setY(latLng.latitude + "");
                                } else if (geometry.getGeometryType().equals("LineString")) {//线
                                    List<LatLng> latLineString = GeometryTools.getLatLngs(geo);
                                    polygonEntity.setX(latLineString.get(0).longitude + "");
                                    polygonEntity.setY(latLineString.get(0).latitude + "");
                                } else if (geometry.getGeometryType().equals("Polygon")) {//面
                                    List<LatLng> latPolygon = GeometryTools.getLatLngs(geo);
                                    polygonEntity.setX(latPolygon.get(0).longitude + "");
                                    polygonEntity.setY(latPolygon.get(0).latitude + "");
                                }
                                polygonEntity.setTaskStatus(1);
                            }


                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    InsertAndUpdateUtils.getInstance().insertOrUpdate(getContext(), polygonEntity);
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            initViewByTaskStatus(1);
                                            Toast.makeText(getActivity(), "领取成功", Toast.LENGTH_SHORT).show();
                                            if (aBoolean) {
                                                initCompleteTask(HttpInterface.SUBMIT_POLYGON_TASK, GatherGetFragment.this.poiEntity.getTaskId(), true, polygonEntity);
                                            }
                                        }
                                    });
                                }
                            }).start();
                        } else {
                            Toast.makeText(getActivity(), "" + response.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + e.getMessage());
                    }
                });
        dismissDialog();
    }

    /**
     * @param url       所以类型的结束领取
     * @param poiEntity
     */
    private void initEndReceiveTask(String url, int taskId, PoiEntity poiEntity) {
        if (taskId == 0) {
            Toast.makeText(getActivity(), "无此任务", Toast.LENGTH_SHORT).show();
            return;
        }
        showLoadingDialog();
        HttpParams httpParams = new HttpParams();
        httpParams.put("taskIds", taskId);
        httpParams.put("auditIds", "");
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(url)
                .params(httpParams)
                .cls(UnPolygonTaskBean.class)
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<UnPolygonTaskBean>() {
                    @Override
                    public void onSuccess(UnPolygonTaskBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    poiDao.deletePoiEntity(poiEntity);
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Log.d("TAG", "run: " + response.getMessage());
                                            initViewByTaskStatus(0);
                                        }
                                    });
                                }
                            }).start();

                        } else {
                            Toast.makeText(getActivity(), "" + response.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + e.getMessage());
                    }
                });
        dismissDialog();
    }

    /**
     * @param url 面妆任务立即采集
     * @param b
     */
    private void initCompleteTask(String url, int taskId, boolean b, PoiEntity poiEntity) {
        if (taskId == 0) {
            Toast.makeText(getActivity(), "无此任务", Toast.LENGTH_SHORT).show();
            return;
        }
        showLoadingDialog();
        HttpParams httpParams = new HttpParams();
        httpParams.put("id", taskId);
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(url)
                .cls(UnPolygonTaskBean.class)
                .token(Constant.ACCESS_TOKEN)
                .params(httpParams)
                .getRequest(new Callback<UnPolygonTaskBean>() {
                    @Override
                    public void onSuccess(UnPolygonTaskBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            poiEntity.setTaskStatus(2);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    InsertAndUpdateUtils.getInstance().insertOrUpdate(getContext(), poiEntity);
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Message obtain = Message.obtain();
                                            obtain.what = Constant.UN_POLY_GEN_TASK;
                                            obtain.obj = true;
                                            EventBus.getDefault().post(obtain);
                                            onBackPressed();
                                        }
                                    });
                                }
                            }).start();
                        } else {
                            Toast.makeText(getActivity(), "" + response.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + e.getMessage());
                    }
                });
        dismissDialog();
    }

    /**
     * @param url 面妆任务 结束采集
     */
    private void initSubmitPolygonTask(String url, int taskId) {
        if (taskId == 0) {
            Toast.makeText(getActivity(), "无此任务", Toast.LENGTH_SHORT).show();
            return;
        }
        showLoadingDialog();
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(url)
                .params(new HttpParams("id", String.valueOf(taskId)))
                .cls(UnPolygonTaskBean.class)
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<UnPolygonTaskBean>() {
                    @Override
                    public void onSuccess(UnPolygonTaskBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    poiDao.deleteFormTaskID(taskId);
                                }
                            }).start();

                        } else {
                            Toast.makeText(getActivity(), "" + response.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + e.getMessage());
                    }
                });
        dismissDialog();
    }


    /**
     * @param url       poi类型对应的url
     * @param poiEntity
     */
    private void receivedTaskByNet(String url, int taskId, boolean isSaver, PoiEntity poiEntity, int statusId) {
        showLoadingDialog();
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(url + "/" + taskId)
                .cls(ReceivedPoiBean.class)
                .params(new HttpParams())
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<ReceivedPoiBean>() {
                    @Override
                    public void onSuccess(ReceivedPoiBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            ReceivedPoiBean.BodyBean body = response.getBody();
                            if (body != null) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        PoiEntity taskIdPoiEntity = poiDao.getTaskIdPoiEntity(taskId);
                                        if (taskIdPoiEntity == null) {//数据库没有这条数据
                                            ReceivedPoiBean.BodyBean listBean = response.getBody();
                                            PoiEntity poiListEntity = new PoiEntity();
                                            poiListEntity.setTaskId(taskId);
                                            poiListEntity.setName(listBean.getName());
                                            poiListEntity.setDescribe(listBean.getMemo());
                                            poiListEntity.setCreateTime(listBean.getEndDate());
                                            poiListEntity.setAddress(listBean.getAddress());
                                            poiListEntity.setType(Integer.valueOf(listBean.getType()));
                                            poiListEntity.setIsExclusive(listBean.getIsExclusive());
                                            poiListEntity.setTaskStatus(statusId);
                                            poiListEntity.setIsLocalData(1);
                                            String encodeStr = listBean.getGeo();
                                            String geo = Geohash.getInstance().decode(encodeStr);
                                            poiListEntity.setGeoWkt(geo);
                                            Geometry geometry = GeometryTools.createGeometry(geo);
                                            if (geometry.getGeometryType().equals("Point")) {//点
                                                LatLng latLng = GeometryTools.createLatLng(geo);
                                                poiListEntity.setX(latLng.longitude + "");
                                                poiListEntity.setY(latLng.latitude + "");
                                            } else if (geometry.getGeometryType().equals("LineString")) {//线
                                                List<LatLng> latLineString = GeometryTools.getLatLngs(geo);
                                                poiListEntity.setX(latLineString.get(0).longitude + "");
                                                poiListEntity.setY(latLineString.get(0).latitude + "");
                                            } else if (geometry.getGeometryType().equals("Polygon")) {//面
                                                List<LatLng> latPolygon = GeometryTools.getLatLngs(geo);
                                                poiListEntity.setX(latPolygon.get(0).longitude + "");
                                                poiListEntity.setY(latPolygon.get(0).latitude + "");
                                            }
                                          //senMessageMarker(poiEntity.getType(), poiEntity.getY(), poiEntity.getX());
                                            if (statusId==1){
                                                InsertAndUpdateUtils.getInstance().insertOrUpdate(getContext(), poiListEntity);
                                            }
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    initViewByTaskStatus(1);//已领取
                                                    if (isSaver) {
                                                        Message obtain = Message.obtain();
                                                        obtain.what = Constant.GATHER_GET_MAP;
                                                        obtain.obj = poiListEntity;
                                                        EventBus.getDefault().post(obtain);
                                                    }
                                                    Message obtain = Message.obtain();
                                                    obtain.what = Constant.JOB_WORD_MONITOR;
                                                    obtain.obj = true;
                                                    EventBus.getDefault().post(obtain);
                                                }
                                            });
                                        } else {
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    initViewByTaskStatus(1);
                                                    if (isSaver) {
                                                        Message obtain = Message.obtain();
                                                        obtain.what = Constant.GATHER_GET_MAP;
                                                        obtain.obj = taskIdPoiEntity;
                                                        EventBus.getDefault().post(obtain);
                                                    }
                                                    Message obtain = Message.obtain();
                                                    obtain.what = Constant.JOB_WORD_MONITOR;
                                                    obtain.obj = true;
                                                    EventBus.getDefault().post(obtain);
                                                }
                                            });
                                        }
                                    }
                                }).start();
                            }
                        } else {
                            Toast.makeText(getActivity(), "" + response.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Log.d("TAG", "onError: " + e.getMessage());
                        Toast.makeText(getActivity(), e.getMessage() + "", Toast.LENGTH_SHORT).show();
                    }
                });
        dismissDialog();
    }

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

    private void senMessageMarker(int type, String y, String x) {
        Message markerMsg = Message.obtain();
        markerMsg.what = Constant.EVENT_WHAT_CURRENT_MARKER;
        LatLng latLng = new LatLng(Double.parseDouble(y), Double.parseDouble(x));
        markerMsg.obj = latLng;
        markerMsg.arg1 = type;
        EventBus.getDefault().post(markerMsg);
    }

    /**
     * @param url       不同任务类型对应的url
     * @param poiEntity
     */
    private void taskByNet(String url, int taskId, boolean isSaver, PoiEntity poiEntity, int statusId) {
        showLoadingDialog();
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(url + "/" + taskId)
                .cls(TaskByNetBean.class)
                .params(new HttpParams())
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<TaskByNetBean>() {
                    @Override
                    public void onSuccess(TaskByNetBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            TaskByNetBean.BodyBean listBean = response.getBody();
                            if (listBean != null) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        PoiEntity taskIdPoiEntity = poiDao.getTaskIdPoiEntity(taskId);
                                        if (taskIdPoiEntity == null) {//数据库没有这条数据
                                            PoiEntity poiListEntity = new PoiEntity();
                                            poiListEntity.setTaskId(taskId);
                                            poiListEntity.setName(listBean.getName());
                                            poiListEntity.setDescribe(listBean.getMemo());
                                            poiListEntity.setCreateTime(listBean.getEndDate());
                                            poiListEntity.setAddress(listBean.getAddress());
                                            poiListEntity.setType(Integer.valueOf(listBean.getType()));
                                            poiListEntity.setPrecision(String.valueOf(listBean.getPrice()));
                                            poiListEntity.setIsExclusive(listBean.getIsExclusive());
                                            poiListEntity.setTaskStatus(statusId);
                                            poiListEntity.setIsLocalData(1);
                                            String encodeStr = listBean.getGeo();
                                            String geo = Geohash.getInstance().decode(encodeStr);
                                            poiListEntity.setGeoWkt(geo);
                                            Geometry geometry = GeometryTools.createGeometry(geo);
                                            if (geometry.getGeometryType().equals("Point")) {//点
                                                LatLng latLng = GeometryTools.createLatLng(geo);
                                                poiListEntity.setX(latLng.longitude + "");
                                                poiListEntity.setY(latLng.latitude + "");
                                            } else if (geometry.getGeometryType().equals("LineString")) {//线
                                                List<LatLng> latLineString = GeometryTools.getLatLngs(geo);
                                                poiListEntity.setX(latLineString.get(0).longitude + "");
                                                poiListEntity.setY(latLineString.get(0).latitude + "");
                                            } else if (geometry.getGeometryType().equals("Polygon")) {//面
                                                List<LatLng> latPolygon = GeometryTools.getLatLngs(geo);
                                                poiListEntity.setX(latPolygon.get(0).longitude + "");
                                                poiListEntity.setY(latPolygon.get(0).latitude + "");
                                            }
                                            //senMessageMarker(poiEntity.getType(), poiEntity.getY(), poiEntity.getX());
                                            if (statusId==1){
                                                InsertAndUpdateUtils.getInstance().insertOrUpdate(getContext(), poiListEntity);
                                            }
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    initViewByTaskStatus(1);
                                                    if (isSaver) {
                                                        Message obtain = Message.obtain();
                                                        obtain.what = Constant.GATHER_GET_MAP;
                                                        obtain.obj = poiListEntity;
                                                        EventBus.getDefault().post(obtain);
                                                    }
                                                    Message obtain = Message.obtain();
                                                    obtain.what = Constant.JOB_WORD_MONITOR;
                                                    obtain.obj = true;
                                                    EventBus.getDefault().post(obtain);
                                                }
                                            });
                                        } else {
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    initViewByTaskStatus(1);
                                                    if (isSaver) {
                                                        Message obtain = Message.obtain();
                                                        obtain.what = Constant.GATHER_GET_MAP;
                                                        obtain.obj = taskIdPoiEntity;
                                                        EventBus.getDefault().post(obtain);
                                                    }
                                                    Message obtain = Message.obtain();
                                                    obtain.what = Constant.JOB_WORD_MONITOR;
                                                    obtain.obj = true;
                                                    EventBus.getDefault().post(obtain);
                                                }
                                            });
                                        }
                                    }
                                }).start();
                            }
                        } else {
                            Toast.makeText(getActivity(), "" + response.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Log.d("TAG", "onError: " + e.getMessage());
                        Toast.makeText(getActivity(), e.getMessage() + "", Toast.LENGTH_SHORT).show();
                    }
                });
        dismissDialog();
    }

    public static String format5(double value) {
        return String.format("%.2f", value).toString();
    }
}
