package com.navinfo.outdoor.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.dialog.v3.MessageDialog;
import com.lzy.okgo.model.HttpParams;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.activity.FragmentManagement;
import com.navinfo.outdoor.adapter.ChargingPileAdapter;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseDrawerFragment;
import com.navinfo.outdoor.bean.ChargingPileSaveBean;
import com.navinfo.outdoor.bean.ChargingStationBean;
import com.navinfo.outdoor.bean.GetPhoneBean;
import com.navinfo.outdoor.bean.Info;
import com.navinfo.outdoor.bean.PhoneBean;
import com.navinfo.outdoor.bean.PoiUploadBean;
import com.navinfo.outdoor.bean.TaskNameBean;
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.ui.view.ContactView;
import com.navinfo.outdoor.util.Geohash;
import com.navinfo.outdoor.util.GeometryTools;
import com.navinfo.outdoor.util.PhotoUtils;
import com.navinfo.outdoor.util.ToastUtil;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.interfaces.Removable;
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 org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import okhttp3.Response;

import static android.app.Activity.RESULT_OK;

/**
 * 充电站的Fragment
 * 2021-5-25
 */
public class ChargingStationFragment extends BaseDrawerFragment implements View.OnClickListener {

    private EditText editDescribe;
    private RelativeLayout rlPanorama, rlName, rlInternalPhotos, rlElse, rlScutcheon, rlNull;
    private ImageView ivPanorama, ivName, ivInternal, ivElse, ivScutcheon;
    private TextView tvExamine;
    private TextView tvPanorama, tvNamePic, tvInternal, tvElse, tvScutcheon;
    private EditText editNameContent, editSiteContent;
    private ArrayList<PhoneBean> poiBeans;
    private Button btnSaveLocal;
    private Button btnUploading;
    private PoiDatabase poiDatabase;
    private PoiDao poiDao;
    private CheckBox checkBoxLife;
    private CheckBox checkBoxRight;
    private Spinner spinnerType;
    String[] ctype = new String[]{"充电站", "充换电站", "充电桩组", "换电站"};//1."充电站"2 "充换电站"3 "充电桩组"4 "换电站"5 ,
    String[] spinner = new String[]{"存在", "不存在", "无法验证"};
    private int existence = 0;
    private ArrayAdapter<String> adapter;
    private LinearLayout linearChargingPile;
    private RecyclerView recyclerStation;
    private ChargingPileAdapter chargingPileAdapter;
    private int station_type = 0;
    private ChargingPileDao chargingPileDao;
    private LatLng latLng;
    private RelativeLayout linearExist;
    private Spinner spinnerExist;
    private Integer bodyId;
    private LinearLayout linearContact;
    private ContactView contactView;
    private ArrayList<File> chargingStationList;
    String str = "";

//    private ArrayList<File> fileList;
    private File photoFile; // 拍照保存的路径
    private NestedScrollView nestedScrollView;
    private Marker markerStation;
    private Point screenStationPositions;
    private List<Removable> removablesLocality;

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

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

 @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setSlidingUpPanelLayout(Constant.SLIDING_LAYOUT);
            if (slidingPaneLayout!=null) {
                slidingPaneLayout.setScrollableView(nestedScrollView);
            }
            initHeader();

        }
    }

    private void initHeader() {
        View header = mView.findViewById(R.id.charging_station_header);
        header.findViewById(R.id.iv_charging_station_final).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle arguments = getArguments();
                if (arguments != null) {
                    isSliding = arguments.getBoolean("isSliding", true);
                    Log.d("TAG", "onCreatessss: " + isSliding);
                }
                if (isSliding) {
                    // 监听到返回按钮点击事件
                    Message obtain = Message.obtain();
                    obtain.what = Constant.TREASURE_FRAGMENT;
                    obtain.obj = isSliding;
                    EventBus.getDefault().post(obtain);
                }
                onBackPressed();
            }
        });
        header.findViewById(R.id.tv_charging_station_explain).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FragmentManagement.class);
                intent.putExtra("tag",8);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        initHeader();
        moveLatlng(latLng,null);

    }
    @Override
    protected void initView() {
        super.initView();
        poiDatabase = PoiDatabase.getInstance(getContext());
        poiDao = poiDatabase.getPoiDao();
        chargingPileDao = poiDatabase.getChargingPileDao();
        checkBoxLife = findViewById(R.id.check_pot_life);
        checkBoxRight = findViewById(R.id.check_pot_right);
        nestedScrollView = findViewById(R.id.nested_scroll_view);
        removablesLocality=new ArrayList<>();
        setSlidingUpPanelLayout(Constant.SLIDING_LAYOUT);
        if (slidingPaneLayout!=null) {
            slidingPaneLayout.setScrollableView(nestedScrollView);
        }
        //添加桩
        linearChargingPile = findViewById(R.id.linear_charging_pile);
        linearChargingPile.setOnClickListener(this::onClick);
        btnSaveLocal = findViewById(R.id.btn_save_local);
        btnSaveLocal.setOnClickListener(this::onClick);
        btnUploading = findViewById(R.id.btn_uploading);
        btnUploading.setOnClickListener(this::onClick);
        editNameContent = findViewById(R.id.tv_name_content);
        editSiteContent = findViewById(R.id.tv_site_content);
        tvExamine = findViewById(R.id.tv_station_examine);
        tvExamine.setOnClickListener(this::onClick);
        editDescribe = findViewById(R.id.edit_describe);
        ivPanorama = findViewById(R.id.iv_panorama);
        ivName = findViewById(R.id.iv_name);
        linearContact = findViewById(R.id.linear_contact);
        ivInternal = findViewById(R.id.iv_internal);
        ivElse = findViewById(R.id.iv_else);
        ivScutcheon = findViewById(R.id.iv_scutcheon);
        rlPanorama = findViewById(R.id.rl_panorama);
        rlPanorama.setOnClickListener(this::onClick);
        rlName = findViewById(R.id.rl_name);
        rlName.setOnClickListener(this::onClick);
        rlInternalPhotos = findViewById(R.id.rl_internal_photos);
        rlInternalPhotos.setOnClickListener(this::onClick);
        rlNull = findViewById(R.id.rl_null);

        rlElse = findViewById(R.id.rl_else);
        rlElse.setOnClickListener(this::onClick);
        rlScutcheon = findViewById(R.id.rl_scutcheon);
        rlScutcheon.setOnClickListener(this::onClick);
        tvPanorama = findViewById(R.id.tv_panorama);
        tvElse = findViewById(R.id.tv_else);
        tvInternal = findViewById(R.id.tv_internal);
        tvNamePic = findViewById(R.id.tv_name_pic);
        tvScutcheon = findViewById(R.id.tv_scutcheon);
       /* recyclerPhone = findViewById(R.id.recycler_phone);
        recyclerPhone.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerPhone.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        poiRecycleAdapter = new PoiRecycleAdapter(getContext());
        recyclerPhone.setAdapter(poiRecycleAdapter);*/
        recyclerStation = findViewById(R.id.recycler_station);
        recyclerStation.setLayoutManager(new GridLayoutManager(getContext(), 3));
        chargingPileAdapter = new ChargingPileAdapter(getContext());
        recyclerStation.setAdapter(chargingPileAdapter);
        chargingPileAdapter.setOnLickItem(new ChargingPileAdapter.onLickItem() {
            @Override
            public void item(ChargingPileEntity chargingPileEntity) {
                String showStation = initShowStation();
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("chargingPileEntity",chargingPileEntity);
                stringObjectHashMap.put("showStation",showStation);
                Message obtain = Message.obtain();
                obtain.what = Constant.CHARGING_STATION;
                obtain.obj = stringObjectHashMap;
                EventBus.getDefault().post(obtain);
            }
        });

        checkBoxLife.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    checkBoxLife.setText("保存");
                    checkBoxLife.setTextColor(Color.WHITE);
                    moveLatlng(latLng, new TencentMap.CancelableCallback() {
                        @Override
                        public void onFinish() {
                            screenStationPositions = tencentMap.getProjection().toScreenLocation(latLng);
                            //创建Marker对象之前，设置属性
                            if (markerStation != null) {
                                markerStation.setFixingPoint(screenStationPositions.x, screenStationPositions.y);
                            }
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
                } else {
                    checkBoxLife.setText("编辑");
                    checkBoxLife.setTextColor(Color.BLACK);
                    latLng = tencentMap.getProjection().fromScreenLocation(screenStationPositions);
                    markerStation.setPosition(latLng);
                    markerStation.setFixingPointEnable(false);
                }

            }
        });
        checkBoxRight.setVisibility(View.GONE);
        spinnerType = findViewById(R.id.spinner_type);
        adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, ctype);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //设置下拉列表框的下拉选项样式
        spinnerType.setAdapter(adapter);
        spinnerType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        station_type = 1;
                        break;
                    case 1:
                        station_type = 2;
                        break;
                    case 2:
                        station_type = 3;
                        break;
                    case 3:
                        station_type = 4;
                        break;

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        linearExist = findViewById(R.id.linear_exist);
        spinnerExist = findViewById(R.id.spinner_exist);
        ArrayAdapter<String> adapterExist = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, spinner);
        adapterExist.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //设置下拉列表框的下拉选项样式
        spinnerExist.setAdapter(adapterExist);
        spinnerExist.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        rlInternalPhotos.setVisibility(View.VISIBLE);
                        rlElse.setVisibility(View.VISIBLE);
                        rlScutcheon.setVisibility(View.VISIBLE);
                        rlNull.setVisibility(View.VISIBLE);
                        existence = 0;
                        break;
                    case 1:
                        rlInternalPhotos.setVisibility(View.GONE);
                        rlElse.setVisibility(View.GONE);
                        rlScutcheon.setVisibility(View.GONE);
                        rlNull.setVisibility(View.GONE);
                        existence = 1;
                        break;
                    case 2:

                        rlInternalPhotos.setVisibility(View.GONE);
                        rlElse.setVisibility(View.GONE);
                        rlScutcheon.setVisibility(View.GONE);
                        rlNull.setVisibility(View.GONE);
                        existence = 2;
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        //数据展示
        initShowPoi();

        onLongDelPic();

    }

    private void onLongDelPic() {
        rlElse.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "是否删除", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        ivElse.setImageDrawable(null);
                        return false;
                    }
                });
                return false;
            }
        });
        rlScutcheon.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "是否删除", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        ivScutcheon.setImageDrawable(null);
                        return false;
                    }
                });
                return false;
            }
        });
        rlPanorama.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "是否删除", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        ivPanorama.setImageDrawable(null);
                        return false;
                    }
                });
                return false;
            }
        });
        rlName.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "是否删除", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        ivName.setImageDrawable(null);
                        return false;
                    }
                });
                return false;
            }
        });
        rlInternalPhotos.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "是否删除", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        ivInternal.setImageDrawable(null);
                        return false;
                    }
                });
                return false;
            }
        });
    }

    private void initShowPoi() {
        // 添加信息：
        showPoiEntity = (PoiEntity) getArguments().getSerializable("poiEntity");
        if (showPoiEntity.getTaskStatus() == 1 || showPoiEntity.getTaskStatus() == 5) {
            tvExamine.setVisibility(View.GONE);
        } else {
            tvExamine.setVisibility(View.VISIBLE);
        }
        String name = showPoiEntity.getName();//名称
        if (name != null && !name.equals("")) {
            editNameContent.setText(name + "");
        }
        if (editNameContent.getText().toString()!=null||editNameContent!=null){
            editNameContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus){
                        findingDuplicateByWork();
                    }
                }
            });
        }else {
            Toast.makeText(getActivity(), "请输入名称", Toast.LENGTH_SHORT).show();
        }

        String address = showPoiEntity.getAddress();//地址
        if (address != null && !address.equals("")) {
            editSiteContent.setText(address);
        }
        bodyId = showPoiEntity.getBodyId(); // 获取当前数据的bodyId
        String x = showPoiEntity.getX();
        String y = showPoiEntity.getY();
        if (x != null && y != null) {
            latLng = new LatLng();
            latLng.setLatitude(Double.parseDouble(y));
            latLng.setLongitude(Double.parseDouble(x));
            BitmapDescriptor pileDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.datouzhen);
            markerStation = tencentMap.addMarker(new MarkerOptions(latLng).icon(pileDescriptor).anchor(0.5f,1.0f));
            markerStation.setZIndex(4);
            moveLatlng(latLng,null);
        }
        initPhone();

        String describe = showPoiEntity.getMemo();//任务描述
        if (describe != null && !describe.equals("")) {
            editDescribe.setText(describe);
        }
        int station_type = showPoiEntity.getStation_type();
        if (station_type==1){
            spinnerType.setSelection(0, true);
        }else if (station_type==2){
            spinnerType.setSelection(1, true);
        }else if (station_type==3){
            spinnerType.setSelection(2, true);
        }else if (station_type==4){
            spinnerType.setSelection(3, true);
        }

        String telPhone = showPoiEntity.getTelPhone();
        if (telPhone != null && !telPhone.equals("")) {
            String[] phones = telPhone.split("\\|");
            for (int i = 0; i < phones.length; i++) {
                if (i == 0) {
                    if (!StringUtils.isEmpty(phones[i])) if (!StringUtils.isEmpty(phones[i])) {
                        if (phones[i].contains("-")) { // 包含区号数据的电话
                            String[] split = phones[i].split("-");
                            if (split != null && split.length > 1) {
                                poiBeans.add(new PhoneBean("电话", split[1] + "", split[0] + "", R.drawable.icon_add_bg));
                            } else {
                                poiBeans.add(new PhoneBean("电话", "", "", R.drawable.icon_add_bg));
                            }
                        } else {
                            if (phones[i] != null) {
                                poiBeans.add(new PhoneBean("电话", phones[i] + "", "", R.drawable.icon_add_bg));
                            } else {
                                poiBeans.add(new PhoneBean("电话", "", "", R.drawable.icon_add_bg));
                            }
                        }
                    }
                } else {
                    if (!StringUtils.isEmpty(phones[i])) {
                        if (phones[i].contains("-")) { // 包含区号数据的电话
                            String[] split = phones[i].split("-");
                            if (split != null && split.length > 1) {
                                poiBeans.add(new PhoneBean("", split[1] + "", split[0] + "", R.drawable.icon_del_bg));
                            } else {
                                poiBeans.add(new PhoneBean("", "", "", R.drawable.icon_del_bg));
                            }
                        } else {
                            if (phones[i] != null) {
                                poiBeans.add(new PhoneBean("", phones[i] + "", "", R.drawable.icon_del_bg));
                            } else {
                                poiBeans.add(new PhoneBean("", "", "", R.drawable.icon_del_bg));
                            }
                        }
                    }
                }

            }
        } else {
            if (Constant.CODE == null || Constant.CODE.equals("")) {
                poiBeans.add(new PhoneBean("电话", "", "", R.drawable.icon_add_bg));
            } else {
                poiBeans.add(new PhoneBean("电话", "", Constant.CODE, R.drawable.icon_add_bg));
            }
        }
        contactView = new ContactView(getActivity(), linearContact, poiBeans);
        contactView.resetView();
        //poiRecycleAdapter.setList(poiBeans);
        if (showPoiEntity.getName() != null) {
            linearExist.setVisibility(View.VISIBLE);
            spinnerExist.setSelection(showPoiEntity.getExistence(), true);
            existence = showPoiEntity.getExistence();
        }
        if (showPoiEntity.getPhotoInfo() != null) {
            for (int i = 0; i < showPoiEntity.getPhotoInfo().size(); i++) {
                String photo = showPoiEntity.getPhotoInfo().get(i).getPhoto();
                String[] split = photo.split("/");
                if (split[split.length - 1].startsWith("a")) {
                    Glide.with(getActivity()).load(photo).into(ivPanorama);
                    tvPanorama.setTag(photo);
                } else if (split[split.length - 1].startsWith("b")) {
                    Glide.with(getActivity()).load(photo).into(ivName);
                    tvNamePic.setTag(photo);
                } else if (split[split.length - 1].startsWith("c")) {
                    Glide.with(getActivity()).load(photo).into(ivInternal);
                    tvInternal.setTag(photo);
                } else if (split[split.length - 1].startsWith("d")) {
                    Glide.with(getActivity()).load(photo).into(ivElse);
                    tvElse.setTag(photo);
                } else if (split[split.length - 1].startsWith("e")) {
                    Glide.with(getActivity()).load(photo).into(ivScutcheon);
                    tvScutcheon.setTag(photo);
                }
            }
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<ChargingPileEntity> chargingPileList = chargingPileDao.getChargingPileByStationId(showPoiEntity.getId());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        chargingPileAdapter.setChargingPileEntities(chargingPileList);
                        initPileMarkerShow();
                    }
                });

            }
        }).start();
        if (showPoiEntity.getTaskStatus() == 3) {
            disables();
        }
        initPile();
    }

    private void initPile() {
        //根据保存时所用的name属性，获取SharedPreferences对象
        SharedPreferences dataFile = getActivity().getSharedPreferences(Constant.DATA_FILE, 0);
        String pileFileString = dataFile.getString("chargingPileEntity", null);
        if (pileFileString != null) {
            ChargingPileEntity chargingPileEntity = new Gson().fromJson(pileFileString, ChargingPileEntity.class);
            String showStation = initShowStation();
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("chargingPileEntity",chargingPileEntity);
            stringObjectHashMap.put("showStation",showStation);
            initRemovePileSharePre();
            Message obtain = Message.obtain();
            obtain.what = Constant.CHARGING_STATION;
            obtain.obj = stringObjectHashMap;
            EventBus.getDefault().post(obtain);
        }
    }

    /**
     * 得到电话区号，电话位数
     */
    private void initPhone() {
        String encode = Geohash.getInstance().encode(latLng.latitude, latLng.longitude);
        if (encode == null) {
            Toast.makeText(getActivity(), "没有确定经纬度", Toast.LENGTH_SHORT).show();
            return;
        }
        showLoadingDialog();
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(HttpInterface.GET_PHONES)
                .params(new HttpParams("geo", encode))
                .cls(GetPhoneBean.class)
                .params(new HttpParams())
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<GetPhoneBean>() {
                    @Override
                    public void onSuccess(GetPhoneBean getPhoneBean, int id) {
                        dismissLoadingDialog();
                        if (getPhoneBean.getCode() == 200) {
                            String code = getPhoneBean.getBody().getCode();
                            Constant.CODE = code;
                        }
                    }

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

    public void initRemovePileSharePre() {
        //获取SharedPreferences对象，方法中两个参数的意思为：第一个name
        //表示文件名，系统将会在/dada/dada/包名/shared_prefs目录下生成
        //一个以该参数命名的.xml文件。第二个mode表示创建的模式，通过查看
        //方法注释得知，建议以0或者MODE_PRIVATE为默认值。

        SharedPreferences poi = getActivity().getSharedPreferences(Constant.DATA_FILE, 0);
        //获取Editor对象
        SharedPreferences.Editor edit = poi.edit();
        //根据要保存的数据的类型，调用对应的put方法,以键值对的形式添加新值。
        edit.putString("chargingPileEntity", null);
        //提交新值。必须执行，否则前面的操作都无效。
        edit.commit();
    }

    //禁用所有可操作性控件
    private void disables() {
        checkBoxLife.setEnabled(false);
        editNameContent.setEnabled(false);
        tvExamine.setEnabled(false);
        editSiteContent.setEnabled(false);
        linearContact.setEnabled(false);
        ivPanorama.setEnabled(false);
        ivName.setEnabled(false);
        ivInternal.setEnabled(false);
        ivElse.setEnabled(false);
        editDescribe.setEnabled(false);
        btnSaveLocal.setEnabled(false);
        linearChargingPile.setEnabled(false);
    }

    @Override
    protected void initData() {
        super.initData();
        //存储对象
        poiBeans = new ArrayList<>();
    }


    @Subscribe
    public void onEvent(Message data) {
        if (data.what == Constant.CHARGING_STATION_WORD) { // 移动充电站点位
            latLng = (LatLng) data.obj;
        } else if (data.what == Constant.CHARGING_PILE_STATION) { // 新增充电桩
            ChargingPileEntity chargingPileEntity = (ChargingPileEntity) data.obj;
            List<ChargingPileEntity> currentChargingPileList = chargingPileAdapter.getChargingPileEntities();
            m: if (currentChargingPileList!=null&&!currentChargingPileList.isEmpty()) {
                for (int i = 0; i < currentChargingPileList.size(); i++) {
                    if (currentChargingPileList.get(i).getPileId() == chargingPileEntity.getPileId()) {
                        currentChargingPileList.add(i, chargingPileEntity);
                        currentChargingPileList.remove(i+1);
                        break m;
                    }
                }
                currentChargingPileList.add(chargingPileEntity);
            } else {
                currentChargingPileList.add(chargingPileEntity);
            }
            chargingPileAdapter.notifyDataSetChanged();
        }else if (data.what==Constant.PILE_MARKER_SHOW){
           initPileMarkerShow();
        }
    }
    public void initPileMarkerShow(){
        for (int i = 0; i < removablesLocality.size(); i++) {
            removablesLocality.get(i).remove();
        }
        removablesLocality.clear();
        List<ChargingPileEntity> chargingPileEntities = chargingPileAdapter.getChargingPileEntities();
        for (int i = 0; i < chargingPileEntities.size(); i++) {
            BitmapDescriptor pileDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.marker_chang_pile);
            String p = chargingPileEntities.get(i).getP();
            if (p != null) {
                // 解密geo
                String decodeGeometry = Geohash.getInstance().decode(p);
                LatLng latLngPile = GeometryTools.createLatLng(decodeGeometry);
                Marker markerPile = tencentMap.addMarker(new MarkerOptions(latLngPile).icon(pileDescriptor).anchor(0.5f,1.0f));
                markerPile.setZIndex(3);
                removablesLocality.add(markerPile);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save_local:
                initRoadSaveLocal(false);
                break;
            case R.id.btn_uploading:
                Message obtain = Message.obtain();
                obtain.what = Constant.TREASURE_FRAGMENT;
                obtain.obj = false;
                EventBus.getDefault().post(obtain);
                String name = editNameContent.getText().toString().trim();//名称
                if (name == null || name.equals("")) {
                    Toast.makeText(getActivity(), "请输入充电站 名称", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (latLng == null) {
                    Toast.makeText(getActivity(), "请确定点位", Toast.LENGTH_SHORT).show();
                    return;
                }
                chargingStationList = new ArrayList<>();
                String tagPanorama = (String) tvPanorama.getTag();
                if (tagPanorama == null) {
                    Toast.makeText(getActivity(), "请拍照", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    chargingStationList.add(new File(tagPanorama));
                }
                String tagName = (String) tvNamePic.getTag();
                if (tagName == null) {
                    Toast.makeText(getActivity(), "请拍照", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    chargingStationList.add(new File(tagName));
                }
                if (existence == 0) {
                    String tagInternal = (String) tvInternal.getTag();
                    if (tagInternal == null) {
                        Toast.makeText(getActivity(), "请拍照", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        chargingStationList.add(new File(tagInternal));
                    }
                    String tagElse = (String) tvElse.getTag();
                    if (tagElse == null) {
                        Toast.makeText(getActivity(), "请拍照", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        chargingStationList.add(new File(tagElse));
                    }
                    String tagScutcheon = (String) tvScutcheon.getTag();
                    if (tagScutcheon == null) {
                        Toast.makeText(getActivity(), "请拍照", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        chargingStationList.add(new File(tagScutcheon));
                    }
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PoiEntity poiDaoPoiEntity = poiDao.getPoiEntity(showPoiEntity.getId());
                        if (poiDaoPoiEntity == null || poiDaoPoiEntity.getTaskStatus() == 0 || poiDaoPoiEntity.getTaskStatus() == 1 || poiDaoPoiEntity.getTaskStatus() == 2||poiDaoPoiEntity.getTaskStatus()==5) {
                            initRoadSaveLocal(true);
                        } else {
                            // 首先批量保存充电站对应的充电桩数据
                            saveChargingPileByChargingStation(poiDaoPoiEntity);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    stationUploadByNetWork(poiDaoPoiEntity, chargingStationList);
                                }
                            });
                        }
                    }
                }).start();
                break;
            case R.id.tv_station_examine:
                findingDuplicateByWork();
                break;
            case R.id.rl_panorama:
                Intent intentPanorama = new Intent("android.media.action.IMAGE_CAPTURE");
                photoFile = PhotoUtils.showPhotoFile("a", latLng);
                intentPanorama.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(intentPanorama, 101);
                break;
            case R.id.rl_name:
                Intent intentName = new Intent("android.media.action.IMAGE_CAPTURE");
                photoFile = PhotoUtils.showPhotoFile("b", latLng);
                intentName.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(intentName, 102);
                break;
            case R.id.rl_internal_photos:
                Intent intentInternal = new Intent("android.media.action.IMAGE_CAPTURE");
                photoFile = PhotoUtils.showPhotoFile("c", latLng);
                intentInternal.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(intentInternal, 103);
                break;
            case R.id.rl_else:
                Intent intentElse = new Intent("android.media.action.IMAGE_CAPTURE");
                photoFile = PhotoUtils.showPhotoFile("d", latLng);
                intentElse.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(intentElse, 104);
                break;
            case R.id.rl_scutcheon:
                Intent intentScutcheon = new Intent("android.media.action.IMAGE_CAPTURE");
                photoFile = PhotoUtils.showPhotoFile("e", latLng);
                intentScutcheon.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(intentScutcheon, 105);
                break;
            case R.id.linear_charging_pile:
                initChargingPile();
                break;
        }
    }

    private void initChargingPile() {
        String showStation = initShowStation();
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        ChargingPileEntity chargingPileEntity = new ChargingPileEntity();
        String encode = Geohash.getInstance().encode(latLng.latitude, latLng.longitude);
        chargingPileEntity.setP(encode);
        stringObjectHashMap.put("chargingPileEntity",chargingPileEntity);
        stringObjectHashMap.put("showStation",showStation);
        initRemovePileSharePre();
        Message obtain = Message.obtain();
        obtain.what = Constant.CHARGING_STATION;
        obtain.obj = stringObjectHashMap;
        EventBus.getDefault().post(obtain);
    }

    /**
     * 根据充电站数据检查充电桩数据，如果没有网络保存，则批量网络保存
     */
    private void saveChargingPileByChargingStation(PoiEntity chargingStationPoiEntity) {
        if (chargingStationPoiEntity != null) {
            List<ChargingPileEntity> chargingPileEntityList = PoiDatabase.getInstance(getActivity()).getChargingPileDao().getChargingPileByStationId(chargingStationPoiEntity.getId());
            if (chargingPileEntityList != null && !chargingPileEntityList.isEmpty()) {
                for (ChargingPileEntity pileEntity : chargingPileEntityList) {
                    if (pileEntity.getBodyId() == 0) {
                        saveChargingPileByWork(pileEntity);
                    }
                }
            }
        }
    }

    /**
     * 上传充电桩数据
     */
    private void chargingPileUploadNetWork(ChargingPileEntity chargingPileEntity) {
        if (chargingPileEntity == null || chargingPileEntity.getBodyId() == 0) {
            Toast.makeText(getActivity(), "没有保存本地", Toast.LENGTH_SHORT).show();
            return;
        }

        List<File> chargingPileFileList = new ArrayList<>();
        if (chargingPileEntity.getPhotos() != null && !chargingPileEntity.getPhotos().isEmpty()) {
            for (String photoPath : chargingPileEntity.getPhotos()) {
                chargingPileFileList.add(new File(photoPath));
            }
        }

        try {
            HttpParams httpParams=new HttpParams();
            httpParams.put("auditId",chargingPileEntity.getBodyId());
            Response execute = OkGoBuilder.getInstance().url(HttpInterface.CS_TASK_UP_LOAD_PIC)
                    .params(httpParams)
                    .token(Constant.ACCESS_TOKEN)
                    .fileList(chargingPileFileList).postFileSynchronization();
            String pileUpLoadResultStr = execute.body().string();
            PoiUploadBean uploadBeanResult = new Gson().fromJson(pileUpLoadResultStr, PoiUploadBean.class);
            if (uploadBeanResult != null) {
                if (uploadBeanResult.getCode() == 200) {
                    PoiDatabase.getInstance(getActivity()).getChargingPileDao().deleteChargingPileEntity(chargingPileEntity);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
/*

        OkGo
                // 请求方式和请求url
                .<PoiUploadBean>post(HttpInterface.CS_TASK_UP_LOAD_PIC)
                // 请求的 tag, 主要用于取消对应的请求
                .params("auditId", chargingPileEntity.getBodyId())
                .addFileParams("file", chargingPileFileList)
                .tag(this)
                .execute(new DialogCallback<PoiUploadBean>(PoiUploadBean.class) {
                    @Override
                    public void onSuccess(Response<PoiUploadBean> poiUploadBeanResponse) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_SHORT).show();
                        isChargingPoleUploaded = true;
                        if (isChargeStationUploaded && isChargingPoleUploaded) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    getActivity().onBackPressed();//回退
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(Response<PoiUploadBean> poiUploadBeanResponse) {
                        super.onError(poiUploadBeanResponse);
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), poiUploadBeanResponse.code() + "", Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + poiUploadBeanResponse.code() + "");
                    }
                });
*/
    }

    private void initRoadSaveLocal(boolean isLocal) {
        XXPermissions.with(this)
                //读写权限
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            //保存数据库：
                            PoiEntity poiEntity = initPoiEntityByUI(showPoiEntity);
                            PoiCheckResult poiCheckResult = checkPoiEntity(poiEntity);
                            if (poiCheckResult.getCode() == 1) {
                                Toast.makeText(getActivity(), poiCheckResult.getMsg()+"", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    InsertAndUpdateUtils.getInstance().insertOrUpdate(getContext(), poiEntity);
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            chargingStationSaveByWork(poiEntity, isLocal);
                                        }
                                    });
                                }
                            }).start();

                        } else {
                            Toast.makeText(getActivity(), "没有申请权限，请手动申请", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            Toast.makeText(getActivity(), "被永久拒绝授权，请手动授予权限", Toast.LENGTH_SHORT).show();
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getActivity(), permissions);
                        }
                    }
                });
    }

    private void stationUploadByNetWork(PoiEntity poiEntity, ArrayList<File> chargingStationList) {
     showLoadingDialog();
        setLoadingDialogText("上传中...");
        if (poiEntity == null || poiEntity.getBodyId() == 0) {
            Toast.makeText(getActivity(), "没有保存本地", Toast.LENGTH_SHORT).show();
            Log.e("TAG", "poiUploadByNetWork: " + poiEntity.getBodyId() + chargingStationList);
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 首先批量上传充电桩数据
                List<ChargingPileEntity> chargingPileEntityList = PoiDatabase.getInstance(getActivity()).getChargingPileDao().getChargingPileByStationId(poiEntity.getId());
                if (chargingPileEntityList != null && !chargingPileEntityList.isEmpty()) {
                    for (ChargingPileEntity chargingPileEntity : chargingPileEntityList) {
                        if (chargingPileEntity.getBodyId() != 0) {
                            chargingPileUploadNetWork(chargingPileEntity);
                        }
                    }
                }

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        HttpParams httpParams=new HttpParams();
                        httpParams.put("auditId",poiEntity.getBodyId());
                        OkGoBuilder.getInstance()
                                .Builder(getActivity())
                                .url(HttpInterface.C_TASK_UP_LOAD_PIC)
                                .fileList(chargingStationList)
                                .token(Constant.ACCESS_TOKEN)
                                .params(httpParams)
                                .cls(PoiUploadBean.class)
                                .postFileAsynchronous( new Callback<PoiUploadBean>() {
                            @Override
                            public void onSuccess(PoiUploadBean 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() {
                                                    Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_SHORT).show();
                                                    Message obtain = Message.obtain();
                                                    obtain.what = Constant.JOB_WORD_MONITOR;
                                                    obtain.obj = true;
                                                    EventBus.getDefault().post(obtain);
                                                    getActivity().onBackPressed();//回退
                                                }
                                            });
                                        }
                                    }).start();
                                } else {
                                    Toast.makeText(getActivity(), "上传失败", 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() + "");
                            }
                        });


 /*                       OkGo
                                // 请求方式和请求url
                                .<PoiUploadBean>post(HttpInterface.C_TASK_UP_LOAD_PIC)
                                // 请求的 tag, 主要用于取消对应的请求
                                .params("auditId", poiEntity.getBodyId())
                                .addFileParams("file", chargingStationList)
                                .tag(this)
                                .execute(new DialogCallback<PoiUploadBean>(PoiUploadBean.class) {
                                    @Override
                                    public void onSuccess(Response<PoiUploadBean> poiUploadBeanResponse) {
                                        dismissLoadingDialog();
                                        if (poiUploadBeanResponse == null || poiUploadBeanResponse.code() != 200 || poiUploadBeanResponse.body().getCode() != 200) {
                                            Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT).show();
                                            return;
                                        }

                                        if (poiUploadBeanResponse != null && poiUploadBeanResponse.code() == 200) {
                                            PoiUploadBean body = poiUploadBeanResponse.body();
                                            if (body.getCode() == 200) {
                                                Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_SHORT).show();
                                                Log.d("TAG", "onSuccess: " + poiUploadBeanResponse.toString() + "sssssssssssss");
                                                new Thread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        poiDao.deletePoiEntity(showPoiEntity);
                                                        getActivity().runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                getActivity().onBackPressed();//回退
                                                            }
                                                        });
                                                    }
                                                }).start();
                                                return;
                                            }
                                        }
                                    }

                                    @Override
                                    public void onError(Response<PoiUploadBean> poiUploadBeanResponse) {
                                        super.onError(poiUploadBeanResponse);
                                        dismissLoadingDialog();
                                        Toast.makeText(getActivity(), poiUploadBeanResponse.code() + "", Toast.LENGTH_SHORT).show();
                                        Log.d("TAG", "onError: " + poiUploadBeanResponse.code() + "");
                                    }
                                });*/
                    }
                });
            }
        }).start();
        dismissDialog();
    }

    /**
     * 保存充电站数据到服务器
     */
    private void chargingStationSaveByWork(PoiEntity poiEntity, boolean isLocal) {
        showLoadingDialog();
        HttpParams httpParams = new HttpParams();
        httpParams.put("taskId", poiEntity.getTaskId());
        httpParams.put("sptype", poiEntity.getStation_type());
        httpParams.put("name", poiEntity.getName());
        httpParams.put("address", poiEntity.getAddress());
        httpParams.put("telephone", poiEntity.getTelPhone());
        httpParams.put("memo", poiEntity.getMemo());
        httpParams.put("geo", poiEntity.getGeoWkt());
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(HttpInterface.SUBMIT_CTASK)
                .cls(ChargingStationBean.class)
                .params(httpParams)
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<ChargingStationBean>() {
                    @Override
                    public void onSuccess(ChargingStationBean chargingStationBean, int id) {
                        dismissLoadingDialog();
                        if (chargingStationBean.getCode() == 200) {
                            bodyId = chargingStationBean.getBody();
                            if (bodyId != null && bodyId != 0) {
                                poiEntity.setBodyId(bodyId);
                                poiEntity.setTaskStatus(3);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        InsertAndUpdateUtils.getInstance().insertOrUpdate(getContext(), poiEntity);
                                        // 充电站数据已经保存在服务上，批量保存充电桩数据
                                        saveChargingPileByChargingStation(poiEntity);
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (isLocal) {
                                                    stationUploadByNetWork(poiEntity, chargingStationList);
//                                                  chargingPileUploadNetWork(chargingPileBody, fileList);
                                                } else {
                                                    Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
                                                    Message obtain = Message.obtain();
                                                    obtain.what = Constant.JOB_WORD_MONITOR;
                                                    obtain.obj = true;
                                                    EventBus.getDefault().post(obtain);
                                                    getActivity().onBackPressed();
                                                }
                                                Log.d("TAG", "onSuccess: " + chargingStationBean.getBody());
                                            }
                                        });
                                    }
                                }).start();
                            } else {
                                Toast.makeText(getActivity(), "" + chargingStationBean.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getActivity(), "" + chargingStationBean.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();
    }
    private void findingDuplicateByWork() {
        showLoadingDialog();
        HttpParams httpParams = new HttpParams();
        String encode = Geohash.getInstance().encode(latLng.latitude, latLng.longitude);
        httpParams.put("geo", encode);
        httpParams.put("name", editNameContent.getText().toString());
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(HttpInterface.TASK_NAME)
                .cls(TaskNameBean.class)
                .params(httpParams)
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<TaskNameBean>() {
                    @Override
                    public void onSuccess(TaskNameBean taskNameBean, int id) {
                        dismissLoadingDialog();
                        if (taskNameBean.getCode()==200){
                            List<String> body = taskNameBean.getBody();
                            if (body!=null){
                                for (int i = 0; i < body.size(); i++) {
                                    str +=body.get(i) + ",";
                                }
                                if (str!=null){
                                    Toast.makeText(getActivity(), "存在类似名称---"+str, Toast.LENGTH_SHORT).show();
                                    str = "";
                                }else {
                                    Toast.makeText(getActivity(), "没有类似名称可以作业", Toast.LENGTH_SHORT).show();
                                }
                            }else {
                                Toast.makeText(getActivity(), "没有类似名称可以作业", Toast.LENGTH_SHORT).show();
                            }
                        }else {
                            Toast.makeText(getActivity(), taskNameBean.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();
    }
    private String initShowStation() {
        PoiEntity poiEntity = initPoiEntityByUI(showPoiEntity);
        String newPoiEntity = new Gson().toJson(poiEntity);
        return newPoiEntity;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);

        initStationSharePre();
    }

    /**
     * 防止当页面崩溃后出现数据丢失
     */
    public void initStationSharePre() {
        //获取SharedPreferences对象，方法中两个参数的意思为：第一个name
        //表示文件名，系统将会在/dada/dada/包名/shared_prefs目录下生成
        //一个以该参数命名的.xml文件。第二个mode表示创建的模式，通过查看
        //方法注释得知，建议以0或者MODE_PRIVATE为默认值。
        SharedPreferences poi = getActivity().getSharedPreferences(Constant.DATA_FILE, 0);
        //获取Editor对象
        SharedPreferences.Editor edit = poi.edit();
        //根据要保存的数据的类型，调用对应的put方法,
        PoiEntity poiEntity = initPoiEntityByUI(showPoiEntity);
        String newPoiEntity = new Gson().toJson(poiEntity);
        //以键值对的形式添加新值。
        edit.putString("poiEntity", newPoiEntity);
        //提交新值。必须执行，否则前面的操作都无效。
        edit.commit();
        Log.d("TAG", "initPoiSharePre: " + newPoiEntity);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == RESULT_OK) {
            if (photoFile == null || !photoFile.exists()) {
                ToastUtil.showShort(getActivity(), "取消拍照");
                return;
            }
            String photoPath = PhotoUtils.showPhotoAndGetPath(photoFile, ivPanorama);
            tvPanorama.setTag(photoPath);
            photoFile = null;
          /*  int height = bitmap.getHeight();
            int width = bitmap.getWidth();
            if (height > width) {
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "请重新拍照，要求横屏拍照", "确定").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        Intent intentPanorama = new Intent("android.media.action.IMAGE_CAPTURE");
                        startActivityForResult(intentPanorama, 101);
                        return false;
                    }
                });
            } else {

            }*/
        } else if (requestCode == 102 && resultCode == RESULT_OK) {
            if (photoFile == null || !photoFile.exists()) {
                ToastUtil.showShort(getActivity(), "取消拍照");
                return;
            }
            String photoPath = PhotoUtils.showPhotoAndGetPath(photoFile, ivName);
            tvNamePic.setTag(photoPath);
            photoFile = null;
            /*int height = bitmap.getHeight();
            int width = bitmap.getWidth();
            if (height > width) {
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "请重新拍照，要求横屏拍照", "确定").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        Intent intentPanorama = new Intent("android.media.action.IMAGE_CAPTURE");
                        startActivityForResult(intentPanorama, 102);
                        return false;
                    }
                });
            } else {

            }*/
        } else if (requestCode == 103 && resultCode == RESULT_OK) {
            if (photoFile == null || !photoFile.exists()) {
                ToastUtil.showShort(getActivity(), "取消拍照");
                return;
            }
            String photoPath = PhotoUtils.showPhotoAndGetPath(photoFile, ivInternal);
            tvInternal.setTag(photoPath);
            photoFile = null;
            /*int height = bitmap.getHeight();
            int width = bitmap.getWidth();
            if (height > width) {
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "请重新拍照，要求横屏拍照", "确定").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        Intent intentPanorama = new Intent("android.media.action.IMAGE_CAPTURE");
                        startActivityForResult(intentPanorama, 103);
                        return false;
                    }
                });
            } else {

            }*/
        } else if (requestCode == 104 && resultCode == RESULT_OK) {
            if (photoFile == null || !photoFile.exists()) {
                ToastUtil.showShort(getActivity(), "取消拍照");
                return;
            }
            String photoPath = PhotoUtils.showPhotoAndGetPath(photoFile, ivElse);
            tvElse.setTag(photoPath);
            photoFile = null;
           /* int height = bitmap.getHeight();
            int width = bitmap.getWidth();
            if (height > width) {
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "请重新拍照，要求横屏拍照", "确定").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        Intent intentPanorama = new Intent("android.media.action.IMAGE_CAPTURE");
                        startActivityForResult(intentPanorama, 104);
                        return false;
                    }
                });
            } else {

            }*/
        } else if (requestCode == 105 && resultCode == RESULT_OK) {
            if (photoFile == null || !photoFile.exists()) {
                ToastUtil.showShort(getActivity(), "取消拍照");
                return;
            }
            String photoPath = PhotoUtils.showPhotoAndGetPath(photoFile, ivScutcheon);
            tvScutcheon.setTag(photoPath);
            photoFile = null;
          /*  int height = bitmap.getHeight();
            int width = bitmap.getWidth();
            if (height > width) {
                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                MessageDialog.show((AppCompatActivity) getContext(), "提示", "请重新拍照，要求横屏拍照", "确定").setOkButton(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        Intent intentPanorama = new Intent("android.media.action.IMAGE_CAPTURE");
                        startActivityForResult(intentPanorama, 105);
                        return false;
                    }
                });
            } else {

            }*/

        }
    }

    /**
     * 上传充电桩数据到服务端
     */
    private void saveChargingPileByWork(ChargingPileEntity chargingPileEntity) {
        HttpParams httpParams = new HttpParams();
        httpParams.put("taskId", chargingPileEntity.getTaskId());
        httpParams.put("name", chargingPileEntity.getName());
        httpParams.put("existence", chargingPileEntity.getExist());
        httpParams.put("geo", chargingPileEntity.getP());
        httpParams.put("memo", chargingPileEntity.getMemo());
        httpParams.put("ffid", chargingPileEntity.getFid());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("cp_openType", chargingPileEntity.getCp_openType());
        hashMap.put("cp_floor", chargingPileEntity.getCp_floor());
        hashMap.put("cp_availableState", chargingPileEntity.getCp_availableState());
        hashMap.put("sign_exist", chargingPileEntity.getSign_exist());
        httpParams.put("detail", String.valueOf(hashMap));
        try {
            Response execute = OkGoBuilder.getInstance().url(HttpInterface.SUBMIT_CSTASK)
                    .token(Constant.ACCESS_TOKEN)
                    .params(httpParams).getSynchronization();
            String responseBodyStr = execute.body().string();
            if (responseBodyStr != null) {
                Gson gson = new Gson();
                ChargingPileSaveBean chargingPileSaveBean = gson.fromJson(responseBodyStr, ChargingPileSaveBean.class);
                if (chargingPileSaveBean.getCode() != 200) {
                    return;
                }
                chargingPileEntity.setBodyId(chargingPileSaveBean.getBody());
                InsertAndUpdateUtils.getInstance().insertOrUpdateChargingPile(getActivity(), chargingPileEntity); // 更新当前充电桩的bodyId
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        OkGoBuilder.getInstance()
//                .Builder(getActivity())
//                .url(HttpInterface.SUBMIT_CSTASK)
//                .method(OkGoBuilder.GET)
//                .cls(ChargingPileSaveBean.class)
//                .params(httpParams)
//                .callback(new Callback<ChargingPileSaveBean>() {
//                    @Override
//                    public void onSuccess(ChargingPileSaveBean chargingPileSaveBean, int id) {
//                        dismissLoadingDialog();
//                        chargingPileEntity.setBodyId(chargingPileSaveBean.getBody());
//                        Toast.makeText(getActivity(), "服务保存成功", Toast.LENGTH_SHORT).show();
//                        // 更新数据状态
//                        PoiDatabase.getInstance(getActivity()).getChargingPileDao().updateChargingPileEntity(chargingPileEntity);
//                        Log.d("TAG", "onSuccess: " + chargingPileSaveBean.getBody());
//                    }
//
//                    @Override
//                    public void onError(Throwable e, int id) {
//                        dismissLoadingDialog();
//                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
//                        Log.d("TAG", "onError: " + e.getMessage());
//                    }
//                }).build();
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this))//加上判断
            EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (showPoiEntity!=null){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    PoiEntity poiDaoPoiEntity = poiDao.getPoiEntity(showPoiEntity.getId());
                    if (poiDaoPoiEntity != null) {
                        if (poiDaoPoiEntity.getTaskStatus() == 5) {
                            poiDao.deletePoiEntity(poiDaoPoiEntity);
                        }

                    }
                }
            }).start();
        }
        if (markerStation!=null){
            markerStation.remove();
        }
        for (int i = 0; i < removablesLocality.size(); i++) {
            removablesLocality.get(i).remove();
        }
        removablesLocality.clear();
    }

    @Override
    protected PoiEntity initPoiEntityByUI(PoiEntity poiEntity) {
        List<Info> infoPhoto = new ArrayList<>();
        String name = editNameContent.getText().toString().trim();//名称
        if (name != null && !name.equals("")) {
            poiEntity.setName(name);
        }
        String site = editSiteContent.getText().toString().trim();
        if (site != null && !site.equals("")) {
            poiEntity.setAddress(site);
        }
        if (latLng != null) {
            String encode = Geohash.getInstance().encode(latLng.latitude, latLng.longitude);
            poiEntity.setGeoWkt(encode);
            poiEntity.setX(String.valueOf(latLng.longitude));
            poiEntity.setY(String.valueOf(latLng.latitude));
        }
        String describe = editDescribe.getText().toString().trim();
        if (describe != null && !describe.equals("")) {
            poiEntity.setMemo(describe);
        }
        boolean phoneBean = contactView.getPhoneBean();
        if (phoneBean) {
            String list = contactView.getList();
            poiEntity.setTelPhone(list);
        }
        String tagPanorama = (String) tvPanorama.getTag();
        if (tagPanorama != null && !tagPanorama.equals("")) {
            infoPhoto.add(new Info(tagPanorama));
        }
        String tagName = (String) tvNamePic.getTag();
        if (tagName != null && !tagName.equals("")) {
            infoPhoto.add(new Info(tagName));
        }
        String tagInternal = (String) tvInternal.getTag();
        if (tagInternal != null && !tagInternal.equals("")) {
            infoPhoto.add(new Info(tagInternal));
        }
        String tagElse = (String) tvElse.getTag();
        if (tagElse != null && !tagElse.equals("")) {
            infoPhoto.add(new Info(tagElse));
        }
        String tagScutcheon = (String) tvScutcheon.getTag();
        if (tagScutcheon != null && !tagScutcheon.equals("")) {
            infoPhoto.add(new Info(tagScutcheon));
        }
        poiEntity.setPhotoInfo(infoPhoto);
        poiEntity.setStation_type(station_type);
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        String format = formatter.format(calendar.getTime());
        poiEntity.setCreateTime(format);
        poiEntity.setExistence(existence);
        poiEntity.setType(2);
        poiEntity.setTaskStatus(2);
        poiEntity.setIsLocalData(1);
        return poiEntity;
    }

    @Override
    protected PoiCheckResult checkPoiEntity(PoiEntity entity) {
        PoiCheckResult poiCheckResult = new PoiCheckResult();
        if (entity.getName()==null){
            poiCheckResult.setCode(1);
            poiCheckResult.setMsg("请输入 名称");
            return poiCheckResult;
        }
        if (tvPanorama.getTag()==null){
            poiCheckResult.setCode(1);
            poiCheckResult.setMsg("请拍照 全景图");
            return poiCheckResult;
        }
        if (tvNamePic.getTag()==null){
            poiCheckResult.setCode(1);
            poiCheckResult.setMsg("请拍照 名称照片");
            return poiCheckResult;
        }
        if (entity.getExistence()==0){
            if (tvInternal.getTag()==null){
                poiCheckResult.setCode(1);
                poiCheckResult.setMsg("请拍照 服务说明");
                return poiCheckResult;
            }
            if (tvElse.getTag()==null){
                poiCheckResult.setCode(1);
                poiCheckResult.setMsg("请拍照 充电站指引牌");
                return poiCheckResult;
            }
            if (tvScutcheon.getTag()==null){
                poiCheckResult.setCode(1);
                poiCheckResult.setMsg("请拍照 收费标牌");
                return poiCheckResult;
            }
        }
        if (entity.getX()==null&&entity.getY()==null){
            poiCheckResult.setCode(1);
            poiCheckResult.setMsg("请确定 点位");
            return poiCheckResult;
        }
        if (contactView.getPhoneList()!=-1){
            poiCheckResult.setCode(1);
            poiCheckResult.setMsg("您第"+contactView.getPhoneList()+"手机号输入有误");
            return poiCheckResult;
        }
        if (entity.getTelPhone()==null){
            poiCheckResult.setCode(1);
            poiCheckResult.setMsg("请输入 手机号");
            return poiCheckResult;
        }
        return poiCheckResult;
    }

    @Override
    protected ChargingPileEntity initChargingPileEntityByUI(ChargingPileEntity entity) {
        return null;
    }

    @Override
    protected PoiCheckResult checkChargingPileEntity(ChargingPileEntity entity) {
        return null;
    }
}