package com.sjkj.appthreefloor_tsgz.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.model.LatLng;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.sjkj.appthreefloor_tsgz.R;
import com.sjkj.appthreefloor_tsgz.activity.viewModel.EventCenterViewModel;
import com.sjkj.appthreefloor_tsgz.adapter.ImageAdapter;
import com.sjkj.appthreefloor_tsgz.adapter.VideoDelAdapter;
import com.sjkj.appthreefloor_tsgz.address.OnFinishClickListener;
import com.sjkj.appthreefloor_tsgz.app.App;
import com.sjkj.appthreefloor_tsgz.bean.DailyBean;
import com.sjkj.appthreefloor_tsgz.bean.FileBean;
import com.sjkj.appthreefloor_tsgz.bean.ImageBean;
import com.sjkj.appthreefloor_tsgz.bean.ImageEventBean;
import com.sjkj.appthreefloor_tsgz.databinding.ActivityNewEventBinding;
import com.sjkj.appthreefloor_tsgz.net.DepartmentRequest;
import com.sjkj.appthreefloor_tsgz.net.EventNewRequest;
import com.sjkj.appthreefloor_tsgz.net.UploadFileRequest;
import com.sjkj.appthreefloor_tsgz.utils.EventDepartmentTools;
import com.sjkj.appthreefloor_tsgz.utils.SlideItemTouchHelper;
import com.sjkj.appthreefloor_tsgz.weight.photoview.PhotoViewActivity;
import com.sjkj.base_lib.adapter.BaseRecAdapter;
import com.sjkj.base_lib.app.AppManager;
import com.sjkj.base_lib.entity.Params;
import com.sjkj.base_lib.map.ChooseMapActivity;
import com.sjkj.base_lib.net.domain.interactor.ProcessErrorSubscriber;
import com.sjkj.base_lib.net.utils.RealPathFromUriUtils;
import com.sjkj.base_lib.utils.AppTools;
import com.sjkj.base_lib.utils.CommonUtils;
import com.sjkj.base_lib.utils.Constants;
import com.sjkj.base_lib.utils.DialogUtils;
import com.sjkj.base_lib.utils.LocationUtils;
import com.sjkj.base_lib.utils.ToastUtils;
import com.sjkj.base_lib.view.BaseActivity;
import com.sjkj.base_lib.weight.LoadingDialog;
import com.sjkj.base_lib.weight.silicompressor.SiliCompressor;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import top.zibin.luban.OnRenameListener;

/**
 * 新增事件
 */
public class NewEventActivity extends BaseActivity {
    private static final int TYPE_IMAGE = 1;
    private static final int TYPE_VIDEO = 2;
    static String mCurrentPhotoPath;
    static Uri capturedUri = null;


    private ActivityNewEventBinding binding;
    private EventCenterViewModel viewModel;
    private ImageAdapter adapter;
    private VideoDelAdapter video_adapter;
    private List<ImageBean> imageBeans = new ArrayList<>();
    private List<ImageBean> imageBeans_image = new ArrayList<>();
    private List<ImageBean> imageBeans_video = new ArrayList<>();
    //    private String[] eventTypeNames = new String[]{"森林防火", "秸秆燃烧"};
//    private String[] eventTypeValues = new String[]{"sys_camera_event_type_1", "sys_camera_event_type_2"};
    //    private String[] deptNames = new String[]{"首佳科技", "首家分公司"};
//    private String[] deptIds = new String[]{"1", "2"};
    private String[] windTypes = new String[]{"风向001", "风向002", "风向003", "风向004", "风向005"};
    private UploadFileRequest uploadFileRequest = new UploadFileRequest(App.getInstance());
    private EventNewRequest eventNewRequest = new EventNewRequest(App.getInstance());
    private DepartmentRequest departmentRequest = new DepartmentRequest(App.getInstance());
    private List<CharSequence> deptNames = new ArrayList<>();
    private List<CharSequence> deptIds = new ArrayList<>();
    ImageEventBean imageEventBean;
    private List<ImageEventBean> imageEventBeanList = new ArrayList<>();

    @Override
    protected int initLayout() {
        return R.layout.activity_new_event;
    }

    @Override
    public void initBinding() {
        binding = (ActivityNewEventBinding) getViewDataBinding();
        viewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(EventCenterViewModel.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);
    }

    @Override
    public void initListener() {
        super.initListener();
        binding.locationIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocationMap();
            }
        });
    }

    @Override
    public void initView() {
        super.initView();
        getTitleView().setText(getString(R.string.report_event));
        XXPermissions.with(this)
                .permission(Permission.RECORD_AUDIO)
//                .permission(Permission.READ_EXTERNAL_STORAGE)
//                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {

                        } else {
                            ToastUtils.show("获取部分权限成功，但部分权限未正常授予");
                        }
                    }

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

        viewModel.deptId.set(AppTools.getDeptId());
        viewModel.deptName.set(AppTools.getDeptName());
        imageBeans.clear();
        imageBeans_video.clear();
        imageBeans_image.clear();
        binding.inputBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.contentEt.setFocusableInTouchMode(true);
                binding.contentEt.requestFocus();
            }
        });
//        binding.titleEt.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                viewModel.title.set(s.toString().trim());
//            }
//        });
//        binding.contentEt.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                viewModel.content.set(s.toString().trim());
//            }
//        });
        binding.imageAddIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppTools.chooseImage();

            }
        });
        binding.videoAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chooseVideo();
            }
        });
        LinearLayoutManager manager = new LinearLayoutManager(NewEventActivity.this);
        manager.setOrientation(RecyclerView.HORIZONTAL);
        LinearLayoutManager manager1 = new LinearLayoutManager(NewEventActivity.this);
        manager1.setOrientation(RecyclerView.HORIZONTAL);
        binding.imageRecyclerView.setLayoutManager(manager);
        binding.videoRecyclerView.setLayoutManager(manager1);
        adapter = new ImageAdapter(NewEventActivity.this);
        video_adapter = new VideoDelAdapter(NewEventActivity.this);
        adapter.setItemClick(new BaseRecAdapter.OnItemClick<ImageBean>() {
            @Override
            public void onItemClick(ImageBean bean, int position) {
                if (adapter.getList() != null && adapter.getList().size() > 0) {
                    ArrayList<String> imageList = new ArrayList<>();
                    for (int i = 0; i < adapter.getList().size(); i++) {
                        imageList.add(adapter.getList().get(i).getRealUrl());
                    }

                    Intent intent = new Intent(NewEventActivity.this, PhotoViewActivity.class);
                    intent.putStringArrayListExtra("positionDataList", imageList);
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }
        });
        video_adapter.setItemClick(new BaseRecAdapter.OnItemClick<ImageBean>() {
            @Override
            public void onItemClick(ImageBean bean, int position) {

                // startActivity(OpenFileUtil.openFile(NewEventActivity.this, mCurrentPhotoPath));
                Intent intent = new Intent(NewEventActivity.this, MyVideoPlayerActivity.class);
                intent.putExtra("videoUrl", mCurrentPhotoPath);
                startActivity(intent);
            }
        });

        //添加拖拽事件                                                                 longClickPosition：初始索引值            ActionUpPosition：结束索引值
        ItemTouchHelper.Callback callback = new SlideItemTouchHelper(NewEventActivity.this, adapter);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(binding.imageRecyclerView);
        binding.imageRecyclerView.setAdapter(adapter);
        binding.videoRecyclerView.setAdapter(video_adapter);
//        adapter.setOnDeleteClick(new OnDeleteClick() {
//            @Override
//            public void delete(ImageBean bean, int positio) {
//
//                if (imageBeans_image != null && imageBeans_image.size() > 0) {
//                    imageBeans_image.remove(positio);
//                    adapter.notifyDataSetChanged();
//                }
//                if (imageBeans != null && imageBeans.size() > 0) {
//                    for (int i = 0; i < imageBeans.size(); i++) {
//                        if (bean.getFileNname().equals(imageBeans.get(i).getFileNname())) {
//                            imageBeans.remove(i);
//
//                        }
//                    }
//                }
//            }
//        });
        binding.submitEventTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(viewModel.title.get())) {
                    ToastUtils.show("请输入事件标题");
                    return;
                }
                if (TextUtils.isEmpty(viewModel.eventType.get())) {
                    ToastUtils.show("请选择事件类型");
                    return;
                }
//                if (TextUtils.isEmpty(viewModel.deptId.get()) || TextUtils.isEmpty(viewModel.deptName.get())) {
//                    ToastUtils.show("请选择部门");
//                    return;
//                }
                if (viewModel.longitude.get() <= 0 || viewModel.latitude.get() <= 0) {
                    ToastUtils.show("当前位置坐标有误，请重试");
                    return;
                }
                if (TextUtils.isEmpty(viewModel.position.get())) {
                    ToastUtils.show("请输入地址");
                    return;
                }
                if (TextUtils.isEmpty(viewModel.content.get())) {
                    ToastUtils.show("请输入事件内容");
                    return;
                }
//                if (TextUtils.isEmpty(viewModel.windDirection.get())) {
//                    ToastUtils.show("请选择风向");
//                    return;
//                }
                imageEventBeanList.clear();

                if (adapter.getList() != null && adapter.getList().size() > 0) {
                    for (int i = 0; i < adapter.getList().size(); i++) {
                        if (!TextUtils.isEmpty(adapter.getList().get(i).getUrl())) {

                            //viewModel.fileList.add(imageBeans.get(i).getUrl());
                            imageEventBean = new ImageEventBean();
                            imageEventBean.setFileName(adapter.getList().get(i).getFileNname());
                            imageEventBean.setAttachPath(adapter.getList().get(i).getUrl());
                            imageEventBeanList.add(imageEventBean);

                        }
                    }
                }
                if (video_adapter.getList() != null && video_adapter.getList().size() > 0) {
                    for (int i = 0; i < video_adapter.getList().size(); i++) {
                        if (!TextUtils.isEmpty(video_adapter.getList().get(i).getUrl())) {

                            //viewModel.fileList.add(imageBeans.get(i).getUrl());
                            imageEventBean = new ImageEventBean();
                            imageEventBean.setFileName(video_adapter.getList().get(i).getFileNname());
                            imageEventBean.setAttachPath(video_adapter.getList().get(i).getUrl());
                            imageEventBeanList.add(imageEventBean);

                        }
                    }
                }
                showLoadingDialog();
                Params params = new Params();
                params.put("eventType", viewModel.eventTypeValue1.get());
                params.put("eventTypeXl", viewModel.eventTypeValue2.get());
                params.put("eventTypeXlName", viewModel.eventTypeName2.get());
                params.put("eventName", viewModel.title.get());
                params.put("eventDescription", viewModel.content.get());
                params.put("longitude", viewModel.longitude.get());
                params.put("latitude", viewModel.latitude.get());
                /*params.put("reportById", viewModel.userId.get());
                params.put("reportBy", viewModel.userName.get());*/
                params.put("deptId", viewModel.deptId.get());
                params.put("deptName", viewModel.deptName.get());
//                params.put("hgjDeptId", viewModel.eventTypeValue3.get());
//                params.put("hgjDeptName", viewModel.eventTypeValuEName.get());
//                params.put("windDirection", viewModel.windDirection.get());
                params.put("attach", imageEventBeanList);
                params.put("reportSource", "reporting_source_3");
                params.put("address", viewModel.position.get());
                if (TextUtils.isEmpty(binding.tvHuo.getText().toString())) {
                    params.put("fireRadius", "0");
                } else {
                    params.put("fireRadius", binding.tvHuo.getText().toString());
                }
                eventNewRequest.setParams(params);
                eventNewRequest.execute(new ProcessErrorSubscriber<Object>() {
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideLoadingDialog(LoadingDialog.LOADING_FAILED);
                        ToastUtils.show(e.getMessage());
                    }

                    @Override
                    public void onNext(Object o) {
                        super.onNext(o);
                        hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                        ToastUtils.show("上报成功");
                        setResult(1000);
                        finish();
                    }
                });
            }
        });
        binding.typeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              /*  DialogUtils.showBottomMenu("请选择事件类型", eventTypeNames, new DialogUtils.BottomMenuCallBack() {
                    @Override
                    public void itemListener(String text, int index) {
                        viewModel.eventType.set(text);
                        viewModel.eventTypeValue.set(eventTypeValues[index]);
                    }
                });*/
                if (CommonUtils.isFastClick()) return;
                EventDepartmentTools.GetEventFL(NewEventActivity.this);
                EventDepartmentTools.setOnFinishClickListener(new OnFinishClickListener() {
                    @Override
                    public void FinishClick(String ONEstr, String ONEID, String TWOstr, String TWOID, String THREEstr, String THREEID, String FOURstr, String FOURID) {
                        if (ONEstr.equals("火情事件")) {
                            binding.llHuo.setVisibility(View.VISIBLE);
                            binding.viewHuo.setVisibility(View.VISIBLE);
                        } else {
                            binding.llHuo.setVisibility(View.GONE);
                            binding.viewHuo.setVisibility(View.GONE);
                        }
                        viewModel.eventType.set(ONEstr + "/" + TWOstr /*+ "/" + THREEstr*/);
                        viewModel.eventTypeValue1.set(ONEID);
                        viewModel.eventTypeValue2.set(TWOID);
//                        viewModel.eventTypeValue3.set(THREEID);
//                        viewModel.eventTypeValuEName.set(TWOstr);
                        viewModel.eventTypeName2.set(TWOstr);
                    }
                });
            }
        });
//        binding.deptTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                DialogUtils.showBottomMenu("请选择部门", deptNames, new DialogUtils.BottomMenuCallBack() {
//                    @Override
//                    public void itemListener(String text, int index) {
//                        viewModel.deptName.set(text);
//                        viewModel.deptId.set(deptIds.get(index) + "");
//                        viewModel.deptName.set(deptNames.get(index) + "");
//                    }
//                });
//            }
//        });
        binding.windDirectionTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.showBottomMenu("请选择风向", windTypes, new DialogUtils.BottomMenuCallBack() {
                    @Override
                    public void itemListener(String text, int index) {
                        viewModel.windDirection.set(text);
                    }
                });
            }
        });
        binding.positionTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                DialogUtils.showBottomInput("提示", "请输入地址", new DialogUtils.DialogInputCallBack() {
//                    @Override
//                    public void itemListener(String text) {
//                        viewModel.position.set(text);
//                    }
//                });
                location();
            }
        });
//        binding.tvAgain.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startLocationMap();
//            }
//        });
    }


    @Override
    public void loadData() {
        super.loadData();
        viewModel.userId.set(AppTools.getUserId());
        viewModel.userName.set(AppTools.getUserName());
      /*  adapter.refreshList(imageBeans_image);
        video_adapter.refreshList(imageBeans_video);*/
        //getDepartments();
        startLocationMap();
    }

    private void startLocationMap() {
        LocationUtils.getInstance().startLocation(true, new LocationUtils.OnLocationListener() {
            @Override
            public void onLocationChanged(double lat, double lng, String address, int code) {
//                if (aMapLocation != null) {
                if (!TextUtils.isEmpty(address)) {
                    viewModel.position.set(address);
                } else {
                    viewModel.position.set("定位失败,点击重试");
                }
                viewModel.longitude.set(lng);
                viewModel.latitude.set(lat);
//                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.SYSTEM_100 && resultCode == RESULT_OK) {
            try {
                List<Uri> list = AppTools.chooseImageResult(data);
                Uri uri = list.get(0);
                String path = RealPathFromUriUtils.getRealPathFromUri(this, uri);
                File file = new File(path);
                if (file.exists()) {
                    showLoadingDialog();
                    Luban.with(this).load(file).ignoreBy(100).setFocusAlpha(false).filter(new CompressionPredicate() {
                        @Override
                        public boolean apply(String path) {
                            return !(TextUtils.isEmpty(path));
                        }
                    }).setRenameListener(new OnRenameListener() {
                        @Override
                        public String rename(String filePath) {
                            String result = System.currentTimeMillis() + ".jpg";
                            return result;
                        }
                    }).setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess(File file) {
                            //TODO 压缩成功后调用，返回压缩后的图片文件
                            uploadFileRequest.setFile(file);
                            uploadFileRequest.execute(new ProcessErrorSubscriber<FileBean>() {
                                @Override
                                public void onError(Throwable e) {
                                    super.onError(e);
                                    ToastUtils.show(e.getMessage());
                                    hideLoadingDialog(LoadingDialog.LOADING_FAILED);
                                }

                                @Override
                                public void onNext(FileBean bean) {
                                    super.onNext(bean);
                                    hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                                    ImageBean imageBean = new ImageBean();
                                    imageBean.setUrl(bean.getUrl());
                                    imageBean.setRealUrl(bean.getWebUrl());
                                    imageBean.setFileNname(bean.getWebName());
                                    imageBeans.add(imageBean);
                                    imageBeans_image.add(imageBean);
                                    adapter.refreshList(imageBeans_image);
                                }
                            });
                        }

                        @Override
                        public void onError(Throwable e) {
                            //TODO 当压缩过去出现问题时调用
                            ToastUtils.show(e.getMessage() + "");
                            hideLoadingDialog(LoadingDialog.LOADING_FAILED);
                        }
                    }).launch();
                } else {
                    ToastUtils.show("图片不存在");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }


        } else if (requestCode == Constants.CODE_SUCCESS && resultCode == RESULT_OK) {
            if (data.getData() != null) {
                showLoadingDialog();
                try {

                    File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/IntegratedPlatform/videos");

                    if (f.mkdirs() || f.isDirectory()) {
                        new VideoCompressAsyncTask(this).execute(mCurrentPhotoPath, f.getPath());

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == Constants.SYSTEM_100 && resultCode == Constants.SYSTEM_100) {

            if (data != null) {
                LatLng latLng = data.getParcelableExtra("LatLng");
                String address = data.getStringExtra("address");
                if (latLng != null) {
                    viewModel.latitude.set(latLng.latitude);
                    viewModel.longitude.set(latLng.longitude);
                    if (!TextUtils.isEmpty(address)) {
                        viewModel.position.set(address);
                    } else {
                        viewModel.position.set("定位失败,点击重试");
                    }
                }
            }

        }

    }

    class VideoCompressAsyncTask extends AsyncTask<String, String, String> {

        Context mContext;

        public VideoCompressAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... paths) {
            String filePath = null;
            try {

                filePath = SiliCompressor.with(mContext).compressVideo(paths[0], paths[1], 1080, 720, 4000000);

            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            return filePath;

        }


        @Override
        protected void onPostExecute(String compressedFilePath) {
            super.onPostExecute(compressedFilePath);

            File imageFile = new File(compressedFilePath);

            uploadFileRequest.setFile(imageFile);
            uploadFileRequest.execute(new ProcessErrorSubscriber<FileBean>() {
                @Override
                public void onError(Throwable e) {
                    super.onError(e);
                    ToastUtils.show("上传失败" + e.getMessage());
                    hideLoadingDialog(LoadingDialog.LOADING_FAILED);
                }

                @Override
                public void onNext(FileBean bean) {
                    super.onNext(bean);
                    //ToastUtils.show("上传成功" + bean.getWebUrl() + "-=-=");
                    hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                    ImageBean imageBean = new ImageBean();
                    imageBean.setUrl(bean.getUrl());
                    imageBean.setRealUrl(bean.getWebUrl());
                    imageBean.setFileNname(bean.getWebName());
                    imageBeans.add(imageBean);
                    imageBeans_video.add(imageBean);
                    video_adapter.refreshList(imageBeans_video);


                }
            });

        }
    }

    //获取部门列表
    public void getDepartments() {
        showLoadingDialog();
        Params params = new Params();
        params.put("userName", AppTools.getUserName());
        departmentRequest.setParams(params);
        departmentRequest.execute(new ProcessErrorSubscriber<DailyBean>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                hideLoadingDialog(LoadingDialog.LOADING_FAILED);
            }

            @Override
            public void onNext(DailyBean data) {
                super.onNext(data);
                hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                if (data != null) {
                    deptIds.clear();
                    deptNames.clear();
                    for (int i = 0; i < data.getDepts().size(); i++) {
                        deptIds.add(data.getDepts().get(i).getDeptId());
                        deptNames.add(data.getDepts().get(i).getDeptName());
                    }
                }
            }
        });

    }


    public void chooseVideo() {
        XXPermissions.with(AppManager.getAppManager().currentActivity())
                // .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .permission(Permission.CAMERA)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            dispatchTakeVideoIntent();
                        } else {
                            ToastUtils.show("获取部分权限成功，但部分权限未正常授予");
                        }
                    }

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

    private void dispatchTakeVideoIntent() {
        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
            try {

                takeVideoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
                takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                capturedUri = FileProvider.getUriForFile(this, AppTools.getPackageNameProvider(),
                        createMediaFile(TYPE_VIDEO));

                takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
                startActivityForResult(takeVideoIntent, 200);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }

    private File createMediaFile(int type) throws IOException {

        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String fileName = (type == TYPE_IMAGE) ? "JPEG_" + timeStamp + "_" : "VID_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                type == TYPE_IMAGE ? Environment.DIRECTORY_PICTURES : Environment.DIRECTORY_MOVIES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }

        File file = File.createTempFile(
                fileName,  /* prefix */
                type == TYPE_IMAGE ? ".jpg" : ".mp4",         /* suffix */
                storageDir      /* directory */
        );

        // Get the path of the file created
        mCurrentPhotoPath = file.getAbsolutePath();
        return file;
    }

    private void location() {
        showLoadingDialog();
        LocationUtils.getInstance().startLocation(true, new LocationUtils.OnLocationListener() {
            @Override
            public void onLocationChanged(double lat, double lng, String address, int code) {
//                viewModel.lat.set(aMapLocation.getLatitude());
//                viewModel.lng.set(aMapLocation.getLongitude());
//                if (aMapLocation != null) {
                hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                startActivityForResult(new Intent(NewEventActivity.this, ChooseMapActivity.class), Constants.SYSTEM_100);
//                }
            }
        });
    }
}
