package com.navinfo.outdoor.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
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.github.lazylibrary.util.FileUtils;
import com.github.lazylibrary.util.StringUtils;
import com.github.lazylibrary.util.ZipUtil;
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.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.activity.FragmentManagement;
import com.navinfo.outdoor.activity.PictureActivity;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseDrawerFragment;
import com.navinfo.outdoor.bean.OtherUploadPicBean;
import com.navinfo.outdoor.bean.PoiVideoBean;
import com.navinfo.outdoor.bean.RoadExtend;
import com.navinfo.outdoor.bean.RoadSaveBean;
import com.navinfo.outdoor.http.Callback;
import com.navinfo.outdoor.http.DialogCallback;
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.util.AWMp4ParserHelper;
import com.navinfo.outdoor.util.GeometryTools;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;

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

import okhttp3.OkHttpClient;

/**
 * 寻宝-点击上传弹窗-道路
 */

public class RoadFragment extends BaseDrawerFragment implements View.OnClickListener {
    private TextView tvPictures;
    private EditText etRoadName;
    private ImageView ivRoadPicture;
    private RadioButton rbCar;
    private RadioButton rbBicycle;
    private RadioButton rbWalking;
    private EditText etDesc;
    private Button btnRoadSave;
    private RadioGroup rgType;
    private PoiDatabase poiDatabase;
    private PoiDao poiDao;
    private Button roadUpload;
    private File fileZip;
    private FrameLayout fmRoadPic;
    private NestedScrollView nestedScrollView;
    private Marker markerRoad;
    private LatLng latLng;

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

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

    @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.road_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);
                }
                if (isSliding) {
                    Message obtain = Message.obtain();
                    obtain.what = Constant.TREASURE_FRAGMENT;
                    obtain.obj = isSliding;
                    EventBus.getDefault().post(obtain);
                }
                onBackPressed();
            }
        });
        header.findViewById(R.id.tv_road_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();
        tvPictures = (TextView) findViewById(R.id.tv_pictures);
        tvPictures.setOnClickListener(this::onClick);
        setSlidingUpPanelLayout(Constant.SLIDING_LAYOUT);
        nestedScrollView = findViewById(R.id.nested_scroll_view);
        if (slidingPaneLayout != null) {
            slidingPaneLayout.setScrollableView(nestedScrollView);
        }
        etRoadName = (EditText) findViewById(R.id.et_road_name);
        ivRoadPicture = (ImageView) findViewById(R.id.iv_road_picture);
        // Glide.with(getContext()).load(getLocalVideoBitmap(String.valueOf(R.drawable.bg_01))).into(ivRoadPicture);
        rbCar = (RadioButton) findViewById(R.id.rb_car);
        rbBicycle = (RadioButton) findViewById(R.id.rb_bicycle);
        rbWalking = (RadioButton) findViewById(R.id.rb_walking);
        etDesc = (EditText) findViewById(R.id.et_desc);
        fmRoadPic = findViewById(R.id.fm_road_picture);
        btnRoadSave = (Button) findViewById(R.id.btn_road_save);
        btnRoadSave.setOnClickListener(this::onClick);
        rgType = (RadioGroup) findViewById(R.id.rg_type);
        roadUpload = findViewById(R.id.road_upload);
        roadUpload.setOnClickListener(this::onClick);
        showPictureType(1);
        fmRoadPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getTag() == null || ((List<File>) v.getTag()).size() == 0) {
                    Toast.makeText(getActivity(), "还没有拍摄视频！", Toast.LENGTH_SHORT).show();
                    return;
                }

                File finalFile = AWMp4ParserHelper.getInstance().obtainMp4FilePath(new File(Constant.PICTURE_FOLDER, showPoiEntity.getId()).getAbsolutePath());
                Intent intent = new Intent(getContext(), PictureActivity.class);
                intent.putExtra(Constant.INTENT_VIDEO_PATH, finalFile.getAbsolutePath());
                intent.putExtra(Constant.INTENT_VIDEO_ORATATION, 0);
                intent.putExtra("poiEntity", showPoiEntity);
                startActivityForResult(intent, 0x101);
            }
        });
        fmRoadPic.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) {
                        List<File> videoFileListByUUID = AWMp4ParserHelper.getInstance().getVideoFileListByUUID(showPoiEntity.getId());
                        for (int i = 0; i < videoFileListByUUID.size(); i++) {
                            videoFileListByUUID.get(i).delete();
                        }
                        ivRoadPicture.setImageDrawable(null);
                        return false;
                    }
                });
                return false;
            }
        });
        //数据展示
        initShowPoi();
        //禁用可操作性控件
        // disables();

    }

    private void initShowPoi() {
        // 添加信息：
        showPoiEntity = (PoiEntity) getArguments().getSerializable("poiEntity");
        if (showPoiEntity != null) {
            String name = showPoiEntity.getName();//名称
            if (name != null && !name.equals("")) {
                etRoadName.setText(name + "");
            }
            String x = showPoiEntity.getX();
            String y = showPoiEntity.getY();
            if (x != null && y != null) {
                latLng = new LatLng();
                latLng.setLongitude(Double.parseDouble(x));
                latLng.setLatitude(Double.parseDouble(y));
                BitmapDescriptor pileDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.marker_road_bag);
                markerRoad = tencentMap.addMarker(new MarkerOptions(latLng).icon(pileDescriptor).anchor(0.5f,1.0f));
                markerRoad.setZIndex(4);
                moveLatlng(latLng,null);
            }
            int work_type = showPoiEntity.getWork_type();
            showPictureType(work_type);
            String describe = showPoiEntity.getDescribe();//任务描述
            if (describe != null && !describe.equals("")) {
                etDesc.setText(describe);
            }
            String photoList = showPoiEntity.getPhoto();
            if (!StringUtils.isEmpty(photoList)) {
                String[] photos = photoList.split(",");
                List<File> videoFileList = new ArrayList<>();
                boolean isImageLoad = false;
                if (photos != null && photos.length > 0) {
                    for (int i = 0; i < photos.length; i++) {
                        String photo = photos[i];
                        if (!StringUtils.isEmpty(photo)) {
                            File videoFile = new File(photo);
                            videoFileList.add(new File(photo));
                            if (videoFile.getPath().contains("0.mp4") && !videoFile.getPath().contains("0.mp4.txt")) {
                                if (videoFile.exists() && !isImageLoad) {
                                    // 使用glide加载视频的第一帧
                                    AWMp4ParserHelper.getInstance().loadFirstWithGlide(getActivity(), Uri.fromFile(videoFile).toString(), ivRoadPicture, 500);
                                    isImageLoad = true;
                                }
                            }
                        }
                    }

                    fmRoadPic.setTag(videoFileList);
                }
            }
        }

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

    }

    //禁用控件
    private void disables() {
        etRoadName.setEnabled(false);
        rgType.setEnabled(false);
        ivRoadPicture.setEnabled(false);
        tvPictures.setEnabled(false);
        etDesc.setEnabled(false);
        btnRoadSave.setEnabled(false);
        rbCar.setEnabled(false);
        rbBicycle.setEnabled(false);
        rbWalking.setEnabled(false);
    }

    @Subscribe
    public void onEvent(Message data) {
        if (data.what == Constant.PICTURE_VIDEO_WORD) {
            if ((boolean) data.obj) {
                initRoadSharePre();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_road_save:
                initPoiSaveLocal(false);
                break;
            case R.id.tv_pictures:

                // 根据用户点击的时间为视频名称赋值
//                DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
//                String videoFormatName = formatter.format(new Date());
                Intent intent = new Intent(getContext(), PictureActivity.class);
                File finalFile = AWMp4ParserHelper.getInstance().obtainMp4FilePath(new File(Constant.PICTURE_FOLDER, showPoiEntity.getId()).getAbsolutePath());
                intent.putExtra(Constant.INTENT_VIDEO_PATH, finalFile.getAbsolutePath());
                intent.putExtra(Constant.INTENT_VIDEO_ORATATION, 0);
                intent.putExtra("poiEntity", showPoiEntity);
                startActivityForResult(intent, 0x101);
                break;
            case R.id.road_upload:
             showLoadingDialog();
                setLoadingDialogText("压缩中...");
                if (fmRoadPic.getTag() != null) {
                    List<File> videoFileList = (List<File>) fmRoadPic.getTag();
                    fileZip = new File(Constant.PICTURE_FOLDER, "files" + ".zip");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            ZipUtil.zipFiles(videoFileList, fileZip, null);//压缩
                            PoiEntity poiDaoPoiEntity = poiDao.getPoiEntity(showPoiEntity.getId());
                            if (poiDaoPoiEntity == null || poiDaoPoiEntity.getTaskStatus() == 1 || poiDaoPoiEntity.getTaskStatus() == 2 || poiDaoPoiEntity.getTaskStatus() == 0 || poiDaoPoiEntity.getTaskStatus() == 5) {
                                dismissLoadingDialog();
                                initPoiSaveLocal(true);
                            } else {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissLoadingDialog();
                                        poiVideoUpload(poiDaoPoiEntity.getBodyId(), fileZip);
                                    }
                                });
                            }

                        }
                    }).start();
                } else {
                    dismissLoadingDialog();
                    Toast.makeText(getActivity(), "请录像", Toast.LENGTH_SHORT).show();
                    return;
                }
                break;

        }
    }

    public void initPoiSaveLocal(boolean isLocal) {
        XXPermissions.with(getContext())
                .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() {
                                            roadSaveBetWork(poiEntity, isLocal);
                                        }
                                    });
                                }
                            }).start();
                            //onBackPressed();
                        } 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 poiVideoUpload(int body, File fileZip) {
        if (body == 0) {
            Toast.makeText(getActivity(), "请先保存本地上传", Toast.LENGTH_SHORT).show();
            return;
        }
        if (fileZip == null) {
            Toast.makeText(getActivity(), "未压缩完成", Toast.LENGTH_SHORT).show();
            return;
        }
        HttpParams httpParams = new HttpParams();
        httpParams.put("auditId", body);
        long time = System.currentTimeMillis();
        httpParams.put("datetime", time);
        httpParams.put("file", fileZip);
       showLoadingDialog();
        setLoadingDialogText("上传中...");
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(HttpInterface.ROAD_TASK_UPLOAD_PIC)
                .params(httpParams)
                .token(Constant.ACCESS_TOKEN)
                .cls(OtherUploadPicBean.class)
                .postRequest(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(), "上传失败", Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + e.getMessage() + "");
                    }
                });
        dismissDialog();
    }

    private void roadSaveBetWork(PoiEntity poiEntity, boolean isLocal) {
        showLoadingDialog();
        HttpParams httpParams = new HttpParams();
        httpParams.put("taskId", poiEntity.getTaskId());
        httpParams.put("name", poiEntity.getName());
        httpParams.put("address", poiEntity.getAddress());
        httpParams.put("workType", poiEntity.getWork_type());
        httpParams.put("memo", poiEntity.getMemo());
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(HttpInterface.ROAD_TASK_SUBMIT)
                .cls(RoadSaveBean.class)
                .params(httpParams)
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<RoadSaveBean>() {
                    @Override
                    public void onSuccess(RoadSaveBean roadSaveBean, int id) {
                        dismissLoadingDialog();
                        if (roadSaveBean.getCode() == 200) {
                            Integer roadBody = roadSaveBean.getBody();
                            if (roadBody != null && roadBody != 0) {
                                poiEntity.setBodyId(roadBody);
                                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) {
                                                    poiVideoUpload(roadBody, fileZip);
                                                } 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);
                                                    onBackPressed();
                                                }
                                            }
                                        });
                                    }
                                }).start();
                            } else {
                                Toast.makeText(getActivity(), "" + roadSaveBean.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getActivity(), "" + roadSaveBean.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();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x101) {
            if (resultCode == 0x101) {
                if (data != null && data.hasExtra(Constant.INTENT_VIDEO_PATH)) {
                    // 扫描照片目录中当前视频的所有视频文件

                    String videoPath = data.getStringExtra(Constant.INTENT_VIDEO_PATH);
                    File videoFile = new File(videoPath);
                    if (videoFile.exists()) {
                        Bitmap bitmap = AWMp4ParserHelper.getInstance().getLocalVideoBitmap(videoPath);
                        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(getActivity(), PictureActivity.class);
                                    File finalFile = AWMp4ParserHelper.getInstance().obtainMp4FilePath(new File(Constant.PICTURE_FOLDER, showPoiEntity.getId()).getAbsolutePath());
                                    intentPanorama.putExtra(Constant.INTENT_VIDEO_PATH, finalFile.getAbsolutePath());
                                    intentPanorama.putExtra(Constant.INTENT_VIDEO_ORATATION, 0);
                                    startActivityForResult(intentPanorama, 0x101);
                                    return false;
                                }
                            });
                            return;
                        } else {
                            if (videoFile.exists()) {
                                AWMp4ParserHelper.getInstance().loadFirstWithGlide(getActivity(), Uri.fromFile(videoFile).toString(), ivRoadPicture, 500);
                                List<File> videoFileListByUUID = AWMp4ParserHelper.getInstance().getVideoFileListByUUID(showPoiEntity.getId());
                                fmRoadPic.setTag(videoFileListByUUID);
                            }
                        }

                    }
                }
            }
        }
    }


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

    /**
     * 防止程序崩溃后数据丢失
     */
    public void initRoadSharePre() {
        //获取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", "initRoadSharePre: " + newPoiEntity);
    }

    //获取拍照类型
    private int getPictureType() {
        if (rbCar != null && rbCar.isChecked()) {
            return 0;
        } else if (rbBicycle != null && rbBicycle.isChecked()) {
            return 1;
        } else if (rbWalking != null && rbWalking.isChecked()) {
            return 2;
        }
        return -1;
    }

    private void showPictureType(int type) {
        switch (type) {
            case 0:
                rbCar.setChecked(true);
                break;
            case 1:
                rbBicycle.setChecked(true);
                break;
            case 2:
                rbWalking.setChecked(true);
                break;

        }
    }

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

    @Override
    protected PoiEntity initPoiEntityByUI(PoiEntity poiEntity) {
        String roadName = etRoadName.getText().toString().trim();
        if (roadName != null && !roadName.equals("")) {
            poiEntity.setName(roadName);
        } else {
            DateFormat formatters = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            Calendar calendars = Calendar.getInstance();
            calendars.setTimeInMillis(System.currentTimeMillis());
            String formats = formatters.format(calendars.getTime());
            String city = Constant.currentLocation.getCity();//返回当前位置的城市.
            String district = Constant.currentLocation.getDistrict();//返回当前位置的区县.
            StringBuffer sb = new StringBuffer("道路录像上报");
            if (city != null && !"".equals(city)) {
                sb.append("-");
                sb.append(city);
            }
            if (district != null && !"".equals(district)) {
                sb.append(district);
            }
            sb.append("-").append(formats);
            poiEntity.setName(sb.toString());
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    etRoadName.setText(sb);
                    etRoadName.setEnabled(false);
                }
            });
        }
        int pictureType = getPictureType();
        if (pictureType != -1) {
            poiEntity.setWork_type(pictureType);
        }
        String desc = etDesc.getText().toString().trim();
        if (desc != null && !desc.equals("")) {
            poiEntity.setDescribe(desc);
        }
        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.setType(4);
        poiEntity.setTaskStatus(2);
        poiEntity.setIsLocalData(1);
        if (fmRoadPic.getTag() == null) {
            List<File> videoFileListByUUID = AWMp4ParserHelper.getInstance().getVideoFileListByUUID(showPoiEntity.getId());
            if (videoFileListByUUID != null) {
                fmRoadPic.setTag(videoFileListByUUID);
            }
        }
        if (fmRoadPic.getTag() != null && !((List<File>) fmRoadPic.getTag()).isEmpty()) {
            List<LatLng> lineStringByVideoFileList = AWMp4ParserHelper.getInstance().getLineStringByVideoFileList((List<File>) fmRoadPic.getTag());
            String lineString = GeometryTools.getLineString(lineStringByVideoFileList);
            Log.d("TAG", "onGranted: " + lineString);
            String photoStr = AWMp4ParserHelper.getInstance().getVideoFileListStr((List<File>) fmRoadPic.getTag());
            poiEntity.setPhoto(photoStr);
            if (lineString != null) {
                poiEntity.setGeoWkt(lineString);
            }
        }
        return poiEntity;
    }

    @Override
    protected PoiCheckResult checkPoiEntity(PoiEntity entity) {
        PoiCheckResult poiCheckResult = new PoiCheckResult();
        if (entity.getPhoto() == null) {
            poiCheckResult.setCode(1);
            poiCheckResult.setMsg("请录像");
            return poiCheckResult;
        }
        if (entity.getWork_type() == -1) {
            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;
    }
}