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 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.api.Constant;
import com.navinfo.outdoor.base.BaseDrawerFragment;
import com.navinfo.outdoor.bean.GetPhoneBean;
import com.navinfo.outdoor.bean.Info;
import com.navinfo.outdoor.bean.OtherUploadPicBean;
import com.navinfo.outdoor.bean.PhoneBean;
import com.navinfo.outdoor.bean.PoiSaveBean;
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.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.PhotoUtils;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
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.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * poi记录的Fragment
 * 2021-5-25
 */
public class PoiFragment extends BaseDrawerFragment implements View.OnClickListener {

    private EditText editDescribe;
    private RelativeLayout rlPanorama, rlName, rlInternalPhotos, rlCard, rlElse;
    private ImageView ivPanorama, ivName, ivInternal, ivCard, ivElse;
    private TextView tvPanorama, tvPoiNamePic, tvInternal, tvCard, tvElse;
    public TextView tvPoiExamine;
    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 LatLng latLng;
    String[] spinner = new String[]{"存在", "不存在", "无法验证"};
    private int existence = 0;
    private RelativeLayout linearExist;
    private Spinner spinnerExist;
    String str = "";


    //获取的拍照图片

    private LinearLayout linearContact;
    private ContactView contactView;
    private ArrayList<File> poiPicList;
    private File file;
    private NestedScrollView nestedScrollView;
    private Marker markerPoi;
    private Point screenPoiPositions;


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

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

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

    }

    @Override
    public void onResume() {
        super.onResume();
        View header = mView.findViewById(R.id.poi_header);
        header.findViewById(R.id.iv_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_explain).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FragmentManagement.class);
                intent.putExtra("tag", 8);
                startActivity(intent);
            }
        });
        moveLatlng(latLng, null);
    }

    @Override
    protected void initView() {
        super.initView();
        poiDatabase = PoiDatabase.getInstance(getContext());
        poiDao = poiDatabase.getPoiDao();
        checkBoxLife = findViewById(R.id.check_pot_life);
        checkBoxRight = findViewById(R.id.check_pot_right);
        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() {
                            screenPoiPositions = tencentMap.getProjection().toScreenLocation(latLng);
                            //创建Marker对象之前，设置属性
                            if (markerPoi != null) {
                                markerPoi.setFixingPoint(screenPoiPositions.x, screenPoiPositions.y);
                            }
                        }

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

            }
        });
        setSlidingUpPanelLayout(Constant.SLIDING_LAYOUT);
        nestedScrollView = findViewById(R.id.nested_scroll_view);
        if (slidingPaneLayout != null) {
            slidingPaneLayout.setScrollableView(nestedScrollView);
        }
        checkBoxRight.setVisibility(View.GONE);
        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);
        tvPoiExamine = findViewById(R.id.tv_poi_examine);
        tvPoiExamine.setOnClickListener(this::onClick);
        editDescribe = findViewById(R.id.edit_describe);
        ivPanorama = findViewById(R.id.iv_panorama);
        tvPanorama = findViewById(R.id.tv_panorama);
        ivName = findViewById(R.id.iv_name);
        tvPoiNamePic = findViewById(R.id.tv_poi_name_pic);
        ivInternal = findViewById(R.id.iv_internal);
        tvInternal = findViewById(R.id.tv_internal);

        ivCard = findViewById(R.id.iv_card);
        tvCard = findViewById(R.id.tv_card);

        ivElse = findViewById(R.id.iv_else);
        tvElse = findViewById(R.id.tv_else);
        linearContact = findViewById(R.id.linear_contact);
        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);
        rlCard = findViewById(R.id.rl_card);
        rlCard.setOnClickListener(this::onClick);
        rlElse = findViewById(R.id.rl_else);
        rlElse.setOnClickListener(this::onClick);
        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:
                        existence = 0;
                        break;
                    case 1:
                        existence = 1;
                        break;
                    case 2:
                        existence = 2;
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        //数据展示
        initShowPoi();
        //拍照长按删除
        onLongDel();


    }

    //拍照长按删除
    private void onLongDel() {
        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;
            }
        });
        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;
            }
        });
        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;
            }
        });
        rlCard.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) {
                        ivCard.setImageDrawable(null);
                        return false;
                    }
                });
                return false;
            }
        });
    }

    private void initShowPoi() {
        // 添加信息：
        showPoiEntity = (PoiEntity) getArguments().getSerializable("poiEntity");
        if (showPoiEntity.getTaskStatus() == 1 || showPoiEntity.getTaskStatus() == 5) {
            tvPoiExamine.setVisibility(View.GONE);
        } else {
            tvPoiExamine.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);
        }
        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);
            markerPoi = tencentMap.addMarker(new MarkerOptions(latLng).icon(pileDescriptor) .anchor(0.5f,1.0f));
            markerPoi.setZIndex(4);
            moveLatlng(latLng, null);
        }
        //得到区号
        initPhone();
        String memo = showPoiEntity.getMemo();//任务描述
        if (memo != null && !memo.equals("")) {
            editDescribe.setText(memo + "");
        }
        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 (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);
        }
        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);
                    tvPoiNamePic.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(ivCard);
                    tvCard.setTag(photo);
                } else if (split[split.length - 1].startsWith("e")) {
                    Glide.with(getActivity()).load(photo).into(ivElse);
                    tvElse.setTag(photo);
                }
            }
        }
        if (showPoiEntity.getTaskStatus() == 3) {
            disables();
        }


    }

    /**
     * 得到电话区号，电话位数
     */
    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)

                .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;
                        }else {
                            Toast.makeText(getActivity(), getPhoneBean.getMessage()+"", Toast.LENGTH_SHORT).show();
                        }
                    }

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


    //禁用所有可操作性控件
    public void disables() {
        checkBoxLife.setEnabled(false);
        editNameContent.setEnabled(false);
        tvPoiExamine.setEnabled(false);
        rlPanorama.setEnabled(false);//禁用拍照全景
        rlName.setEnabled(false);
        rlCard.setEnabled(false);
        rlInternalPhotos.setEnabled(false);
        rlElse.setEnabled(false);
        editSiteContent.setEnabled(false);
        linearContact.setEnabled(false);
        ivPanorama.setEnabled(false);
        ivName.setEnabled(false);
        ivInternal.setEnabled(false);
        ivCard.setEnabled(false);
        ivElse.setEnabled(false);
        editDescribe.setEnabled(false);
        btnSaveLocal.setEnabled(false);
    }

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

    }

    @Subscribe
    public void onEvent(Message data) {
        if (data.what == Constant.POI_WORD) {
            latLng = (LatLng) data.obj;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save_local:
                initPoiSaveLocal(false);
                break;
            case R.id.btn_uploading:
                poiPicList = new ArrayList<>();

                String name = editNameContent.getText().toString().trim();//名称
                if (name == null || name.equals("")) {
                    Toast.makeText(getActivity(), "请输入poi 名称", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (latLng == null) {
                    Toast.makeText(getActivity(), "请确定点位", Toast.LENGTH_SHORT).show();
                    return;
                }
                String tagPanorama = (String) tvPanorama.getTag();
                if (tagPanorama == null) {
                    Toast.makeText(getActivity(), "请拍照", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    poiPicList.add(new File(tagPanorama));
                }
                String tagName = (String) tvPoiNamePic.getTag();
                if (tagName == null) {
                    Toast.makeText(getActivity(), "请拍照", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    poiPicList.add(new File(tagName));
                }

                String tagInternal = (String) tvInternal.getTag();
                if (tagInternal != null) {
                    poiPicList.add(new File(tagInternal));
                }

                String tagCard = (String) tvCard.getTag();
                if (tagCard != null) {
                    poiPicList.add(new File(tagCard));
                }

                String tagElse = (String) tvElse.getTag();
                if (tagElse != null) {
                    poiPicList.add(new File(tagElse));
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PoiEntity poiDaoPoiEntity = poiDao.getPoiEntity(showPoiEntity.getId());
                        if (poiDaoPoiEntity == null || poiDaoPoiEntity.getTaskStatus() == 1 || poiDaoPoiEntity.getTaskStatus() == 2 || poiDaoPoiEntity.getTaskStatus() == 0 || poiDaoPoiEntity.getTaskStatus() == 5) {
                            initPoiSaveLocal(true);
                        } else {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    poiUploadByNetWork(poiDaoPoiEntity.getBodyId(), poiPicList);
                                }
                            });
                        }
                    }
                }).start();
                break;
            case R.id.tv_poi_examine:
                findingDuplicateByWork();
                break;
            case R.id.rl_panorama:
                Intent intentPanorama = new Intent("android.media.action.IMAGE_CAPTURE");
                file = PhotoUtils.showPhotoFile("a", latLng);
                intentPanorama.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intentPanorama, 101);
                break;
            case R.id.rl_name:
                Intent intentName = new Intent("android.media.action.IMAGE_CAPTURE");
                file = PhotoUtils.showPhotoFile("b", latLng);
                intentName.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intentName, 102);
                break;
            case R.id.rl_internal_photos:
                Intent intentInternal = new Intent("android.media.action.IMAGE_CAPTURE");
                file = PhotoUtils.showPhotoFile("c", latLng);
                intentInternal.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intentInternal, 103);
                break;
            case R.id.rl_card:
                Intent intentCard = new Intent("android.media.action.IMAGE_CAPTURE");
                file = PhotoUtils.showPhotoFile("d", latLng);
                intentCard.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intentCard, 104);
                break;
            case R.id.rl_else:
                Intent intentElse = new Intent("android.media.action.IMAGE_CAPTURE");
                file = PhotoUtils.showPhotoFile("e", latLng);
                intentElse.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intentElse, 105);
                break;
        }
    }

    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();
    }

    public void initPoiSaveLocal(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() {
                                            poiSaveByNet(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 poiUploadByNetWork(int body, ArrayList<File> poiPicList) {
        if (body == 0) {
            Toast.makeText(getActivity(), "没有保存本地", Toast.LENGTH_SHORT).show();
            Log.e("TAG", "poiUploadByNetWork: " + body + poiPicList);
            return;
        }
        showLoadingDialog();
        setLoadingDialogText("上传中...");
        HttpParams httpParams = new HttpParams();
        httpParams.put("auditId", body);
        OkGoBuilder.getInstance()
                .url(HttpInterface.POI_TASK_UPLOAD_PIC)
                .cls(OtherUploadPicBean.class)
                .token(Constant.ACCESS_TOKEN)
                .fileList(poiPicList)
                .params(httpParams)
                .postFileAsynchronous(new Callback<OtherUploadPicBean>() {
                    @Override
                    public void onSuccess(OtherUploadPicBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    PoiEntity poiDaoPoiEntity = poiDao.getPoiEntity(showPoiEntity.getId());
                                    poiDao.deletePoiEntity(poiDaoPoiEntity);
                                    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(), response.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }

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

    }

    private void poiSaveByNet(PoiEntity poiEntity, boolean isLocal) {

        HttpParams httpParams = new HttpParams();
        httpParams.put("taskId", poiEntity.getTaskId());
        httpParams.put("name", poiEntity.getName());
        httpParams.put("address", poiEntity.getAddress());
        httpParams.put("existence", poiEntity.getExistence());
        httpParams.put("geo", poiEntity.getGeoWkt());
        httpParams.put("memo", poiEntity.getMemo());
        httpParams.put("telephone", poiEntity.getTelPhone());
        showLoadingDialog();
        setLoadingDialogText("保存中...");
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(HttpInterface.SUBMIT_POI_TASK)
                .cls(PoiSaveBean.class)
                .params(httpParams)
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<PoiSaveBean>() {
                    @Override
                    public void onSuccess(PoiSaveBean poiSaveBean, int id) {
                        dismissLoadingDialog();
                        if (poiSaveBean.getCode() == 200) {
                            Integer body = poiSaveBean.getBody();
                            if (body != null && body != 0) {
                                poiEntity.setBodyId(body);
                                poiEntity.setTaskStatus(3);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        InsertAndUpdateUtils.getInstance().insertOrUpdate(getContext(), poiEntity);
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (isLocal) {
                                                    poiUploadByNetWork(body, poiPicList);//上传
                                                } 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();
                                                }
                                            }
                                        });
                                    }
                                }).start();
                            } else {
                                Toast.makeText(getActivity(), "" + poiSaveBean.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getActivity(), "" + poiSaveBean.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();
    }

    /**
     * 防止当页面崩溃后出现数据丢失
     */
    public void initPoiSharePre() {
        //获取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 (file == null || !file.exists()) {
                Toast.makeText(getActivity(), "请先拍照", Toast.LENGTH_SHORT).show();
                return;
            } else {
                String s = PhotoUtils.showPhotoAndGetPath(file, ivPanorama);
                tvPanorama.setTag(s);
            }
            file = 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 (file == null || !file.exists()) {
                Toast.makeText(getActivity(), "请先拍照", Toast.LENGTH_SHORT).show();
                return;
            } else {
                String s = PhotoUtils.showPhotoAndGetPath(file, ivName);
                tvPoiNamePic.setTag(s);
            }
            file = 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 (file == null || !file.exists()) {
                Toast.makeText(getActivity(), "请先拍照", Toast.LENGTH_SHORT).show();
                return;
            } else {
                String s = PhotoUtils.showPhotoAndGetPath(file, ivInternal);
                tvInternal.setTag(s);
            }
            file = 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 (file == null || !file.exists()) {
                Toast.makeText(getActivity(), "请先拍照", Toast.LENGTH_SHORT).show();
                return;
            } else {
                String s = PhotoUtils.showPhotoAndGetPath(file, ivCard);
                tvCard.setTag(s);
            }
            file = 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 (file == null || !file.exists()) {
                Toast.makeText(getActivity(), "请先拍照", Toast.LENGTH_SHORT).show();
                return;
            } else {
                String s = PhotoUtils.showPhotoAndGetPath(file, ivElse);
                tvElse.setTag(s);
            }
            file = 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 {}*/


        }
    }

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

    @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 (markerPoi != null) {
            markerPoi.remove();
        }
    }

    @Override
    protected PoiEntity initPoiEntityByUI(PoiEntity poiEntity) {
        ArrayList<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) tvPoiNamePic.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 tagCard = (String) tvCard.getTag();
        if (tagCard != null && !tagCard.equals("")) {
            infoPhoto.add(new Info(tagCard));
        }
        String tagElse = (String) tvElse.getTag();
        if (tagElse != null && !tagElse.equals("")) {
            infoPhoto.add(new Info(tagElse));
        }

        poiEntity.setPhotoInfo(infoPhoto);
        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(1);
        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 (tvPoiNamePic.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;
    }


}