package com.tofly.ghrq_route.module.trouble.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatSpinner;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.AudioRecordButton;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.google.gson.Gson;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.common.ui.adapter.SingleUserListAdapter;
import com.tofly.ghrq_route.module.trouble.ui.dialog.TroubleDeviceSelectBottomDialog;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.common.util.Location.LocationUtil;
import com.tofly.ghrq_route.common.util.Location.LocationUtil_xu;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.file.FileViewUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;
import com.tofly.ghrq_route.common.util.recorder.AudioRecordHelper;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.controller.TroubleCallBack;
import com.tofly.ghrq_route.module.trouble.domain.DeviceAttributesBean;
import com.tofly.ghrq_route.module.trouble.domain.MyTroubleEvent;
import com.tofly.ghrq_route.module.trouble.domain.PipeAttributesBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.troubleType.TroubleTypeTool;
import com.tofly.ghrq_route.module.troubleType.controller.TroubleTypeCallBack;
import com.tofly.ghrq_route.module.troubleType.domain.TroubleRiskLevelBean;
import com.tofly.ghrq_route.module.troubleType.domain.TroubleTypeBean;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.DepartmentBean;
import com.tofly.ghrq_route.module.user.domain.DepartmentUserBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemSelected;
import cn.hzw.graffiti.WaterMarkParams;

public class UiTroubleReport extends BaseUi {
    @BindView(R.id.layout_device_num)
    LinearLayout layoutDeviceNum;
    @BindView(R.id.text_device_num)
    TextView textDeviceNum;
    @BindView(R.id.text_pipe_num)
    TextView textPipeNum;
    @BindView(R.id.layout_select_device)
    LinearLayout layoutSelectDevice;
    @BindView(R.id.text_select_device)
    TextView textSelectDevice;
    @BindView(R.id.edit_trouble_name)
    EditText editTroubleName;
    @BindView(R.id.edit_trouble_belong)
    EditText editTroubleBelong;
    @BindView(R.id.spinner_trouble_work_state)
    AppCompatSpinner spinnerWorkState;
    @BindView(R.id.spinner_trouble_type)
    AppCompatSpinner spinnerTroubleType;
    @BindView(R.id.spinner_risk_level)
    AppCompatSpinner spinnerRiskLevel;
    @BindView(R.id.layout_type_risk_module)
    LinearLayout layoutTypeRiskModule;
    @BindView(R.id.spinner_trouble_depart)
    AppCompatSpinner spinnerDepart;
    @BindView(R.id.spinner_trouble_user)
    AppCompatSpinner spinnerUser;
    @BindView(R.id.layout_assigner_module)
    LinearLayout layoutAssignerModule;
    @BindView(R.id.edit_report_addr)
    EditText editReportAddr;
    @BindView(R.id.edit_report_note)
    EditText editReportNote;
    @BindView(R.id.btn_add_photo)
    Button btnAddPhoto;
    @BindView(R.id.btn_audio_record)
    MyAudioRecordButton btnAddAudio;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindArray(R.array.trouble_report_work_states)
    String[] workStates;

    private int mWorkState = 1; // 0:非工作日 1: 工作日在现场 2: 工作日不在现场

    private List<DepartmentBean> mDepartmentList;

    private List<DepartmentUserBean> mUserList;

    private SingleUserListAdapter userListAdapter;

    private int indexDepartment = -1;

    private int indexUser = -1;

    private List<TroubleTypeBean> mTroubleTypeList;

    private List<TroubleRiskLevelBean> mTroubleLevelList;

    private int indexTroubleType = -1;

    private int indexTroubleLevel = -1;

    private List<PipeAttributesBean> mPipeFeatures;

    private String mPipeDesc;

    private List<DeviceAttributesBean> mDeviceFeatures;

    private String mDeviceDesc;

    protected PhotoHelper photoHelper;

    protected PermissionHelper permissionHelper;

    private TroubleBean mTroubleBean = new TroubleBean();

    private List<TroublePictureBean> mPicturesUpload = new ArrayList<>();

    private List<Record> mAudiosRecords = new ArrayList<>();

    private List<TroubleAudioBean> mDocumentsUpload = new ArrayList<>();

    private AudioRecordHelper audioRecordHelper;

    private TroubleTool troubleTool;

    private FileViewUtil fileViewUtil;

    private LocationUtil_xu.CoordinateClass mTappedCoordinate = null;

    private TroubleDeviceSelectBottomDialog deviceSelectBottomDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_trouble_report);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();
    }

    private void initView() {
        setDarkStatusBar();
    }

    private void initData() {
        permissionHelper = new PermissionHelper(this);
        photoHelper = new PhotoHelper(this, permissionHelper);
        fileViewUtil = new FileViewUtil(this);

        audioRecordHelper = new AudioRecordHelper(this, permissionHelper, btnAddAudio);
        audioRecordHelper.initRecordButton();

        troubleTool = TroubleTool.getInstance();

        setWorkStateAdapter();
    }

    private void initListener() {
        AudioRecordButton.AudioFinishRecorderListener mRecorderListener = (seconds, filePath) -> {
            String time = DateUtils.getDate(new Date().getTime());
            int audioLength = (int) seconds <= 0 ? 1 : (int) seconds;

            final Record recordModel = new Record();
            recordModel.setSecond(audioLength);
            recordModel.setPath(filePath);
            recordModel.setPlayed(false);
            recordModel.setCreateTime(time);
            mAudiosRecords.add(recordModel);

            View view = getRecordViewFromAudio(recordModel);
            photoGallery.addView(view);
        };
        btnAddAudio.setAudioFinishRecorderListener(mRecorderListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commit, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_commit) {
            hideSoftKeyboard();
            if (isValid()) {
                uploadTroubleAlert();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private void setWorkStateAdapter(){
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                R.layout.my_simple_spinner_item, workStates){
        };
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        //加载适配器
        spinnerWorkState.setAdapter(adapterDevType);
        spinnerWorkState.setSelection(mWorkState);
        onSetWorkState();
    }

    @OnItemSelected({R.id.spinner_trouble_work_state, R.id.spinner_trouble_type, R.id.spinner_risk_level,
            R.id.spinner_trouble_depart, R.id.spinner_trouble_user})
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
        switch (parent.getId()) {
            case R.id.spinner_trouble_work_state:
                mWorkState = position;
                onSetWorkState();
                break;
            case R.id.spinner_trouble_type:
                indexTroubleType = position;
                break;
            case R.id.spinner_risk_level:
                indexTroubleLevel = position;
                break;
            case R.id.spinner_trouble_depart:
                indexDepartment = position;
                indexUser = -1;
                if (mDepartmentList != null) {
                    DepartmentBean departmentBean = mDepartmentList.get(position);
                    getDepartmentUsers(departmentBean.getId());
                }
                break;
            case R.id.spinner_trouble_user:
                indexUser = position;
                userListAdapter.setSelection(position);
                break;
        }
    }

    private void onSetWorkState() {
        switch (mWorkState) {
            case 0:  //非工作日
                layoutAssignerModule.setVisibility(View.GONE);
                layoutTypeRiskModule.setVisibility(View.GONE);
                break;
            case 1:   //工作日在现场
                layoutTypeRiskModule.setVisibility(View.VISIBLE);
                layoutAssignerModule.setVisibility(View.VISIBLE);
                getTroubleTypeRisk();
                getDepartAssigner();
                break;
            case 2:   //工作日不在现场
                layoutTypeRiskModule.setVisibility(View.GONE);
                layoutAssignerModule.setVisibility(View.VISIBLE);
                getDepartAssigner();
                break;
        }
    }

    private void getDepartAssigner() {
        if (mDepartmentList == null || mDepartmentList.isEmpty()) {
            getDepartments();
        }
    }

    private void getTroubleTypeRisk() {
        if (mTroubleTypeList == null || mTroubleTypeList.isEmpty()) {
            getTroubleTypes();
        }

        if (mTroubleLevelList == null || mTroubleLevelList.isEmpty()) {
            getTroubleLevels();
        }
    }

    private void getTroubleTypes() {
        TroubleTypeTool troubleTypeTool = TroubleTypeTool.getInstance();
        troubleTypeTool.getTroubleTypeList(this, new TroubleTypeCallBack(){
            @Override
            public void onGetTroubleTypeList(boolean isSuccess, int errorCode, String errMsg, List<TroubleTypeBean> troubleTypeList) {
                super.onGetTroubleTypeList(isSuccess, errorCode, errMsg, troubleTypeList);
                if (isSuccess) {
                    mTroubleTypeList = troubleTypeList;
                    setTroubleTypeAdapter();
                }
            }
        });
    }

    private void setTroubleTypeAdapter(){
        if (mTroubleTypeList != null) {
            List<String> typeNameList = new ArrayList<>();
            for (TroubleTypeBean troubleTypeBean : mTroubleTypeList) {
                typeNameList.add(troubleTypeBean.getName());
            }
            ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                    R.layout.my_simple_spinner_item, typeNameList){
            };
            adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
            //加载适配器
            spinnerTroubleType.setAdapter(adapterDevType);
        }
    }

    private void getTroubleLevels() {
        TroubleTypeTool troubleTypeTool = TroubleTypeTool.getInstance();
        troubleTypeTool.getTroubleLevelList(this, new TroubleTypeCallBack(){
            @Override
            public void onGetTroubleRiskLevelList(boolean isSuccess, int errorCode, String errMsg, List<TroubleRiskLevelBean> riskLevelList) {
                super.onGetTroubleRiskLevelList(isSuccess, errorCode, errMsg, riskLevelList);
                if (isSuccess) {
                    mTroubleLevelList = riskLevelList;
                    setTroubleLevelAdapter();
                }
            }
        });
    }

    private void setTroubleLevelAdapter(){
        List<String> levelNameList = new ArrayList<>();
        for (TroubleRiskLevelBean levelBean : mTroubleLevelList) {
            levelNameList.add(levelBean.getName());
        }
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                R.layout.my_simple_spinner_item, levelNameList){
        };
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        //加载适配器
        spinnerRiskLevel.setAdapter(adapterDevType);
    }

    private void getDepartments() {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartments(this, false, new UserCallBack(){
            @Override
            public void onGetDepartmentList(boolean isSuccess, int errorCode, String errMsg, List<DepartmentBean> departmentList) {
                super.onGetDepartmentList(isSuccess, errorCode, errMsg, departmentList);
                if (isSuccess) {
                    mDepartmentList = departmentList;
                    setDepartmentAdapter();
                }
            }
        });
    }

    private void setDepartmentAdapter(){
        List<String> departNameList = new ArrayList<>();
        for (DepartmentBean departmentBean : mDepartmentList) {
            departNameList.add(departmentBean.getName());
        }
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                R.layout.my_simple_spinner_item, departNameList){
        };
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        //加载适配器
        spinnerDepart.setAdapter(adapterDevType);
    }

    private void getDepartmentUsers(String departId) {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartmentUsers(this, departId, new UserCallBack(){
            @Override
            public void onGetDepartmentUserList(boolean isSuccess, int errorCode, String errMsg,
                                                List<DepartmentUserBean> userList) {
                super.onGetDepartmentUserList(isSuccess, errorCode, errMsg, userList);
                if (isSuccess) {
                    mUserList = userList;
                    setUserAdapter();
                }
            }
        });
    }

    private void setUserAdapter(){
        //适配器
        userListAdapter = new SingleUserListAdapter(this, mUserList);
        spinnerUser.setAdapter(userListAdapter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UiTroubleSelectDevice.SELECT_DEVICE_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    if (bundle.containsKey(PipeAttributesBean.TROUBLE_PIPE_ATTRIBUTES_BEAN_KEY)) {
                        mPipeFeatures = (List<PipeAttributesBean>)bundle.getSerializable(PipeAttributesBean.TROUBLE_PIPE_ATTRIBUTES_BEAN_KEY);
                        String pipeNote = bundle.getString(TroubleBean.TROUBLE_PIPE_NOTE_KEY, "");
                        mPipeDesc = pipeNote;
                        mTroubleBean.setPipeInfoDesc(pipeNote);
                        textPipeNum.setText(mPipeFeatures.size() + "");
                    }
                    if (bundle.containsKey(DeviceAttributesBean.TROUBLE_DEVICE_ATTRIBUTES_BEAN_KEY)) {
                        mDeviceFeatures = (List<DeviceAttributesBean>)bundle.getSerializable(DeviceAttributesBean.TROUBLE_DEVICE_ATTRIBUTES_BEAN_KEY);
                        String deviceNote = bundle.getString(TroubleBean.TROUBLE_DEVICE_NOTE_KEY, "");
                        mDeviceDesc = deviceNote;
                        mTroubleBean.setDeviceInfoDesc(deviceNote);
                        textDeviceNum.setText(mDeviceFeatures.size() + "");
                    }
                    mTappedCoordinate =
                            (LocationUtil_xu.CoordinateClass) bundle.getSerializable(LocationUtil.CURRENT_LOCATION_KEY);
                    if (mTappedCoordinate != null && mTappedCoordinate.addr != null) {
                        editReportAddr.setText(mTappedCoordinate.addr);
                    }
                }
            }
        }else {
            if (photoHelper != null) {
                photoHelper.handleActivityResult(requestCode, resultCode, data);
            }
        }
    }

    @OnClick({R.id.btn_add_photo, R.id.layout_select_device, R.id.layout_trouble_device})
    void onClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_add_photo:
                showAddPictureDialog();
                break;
            case R.id.layout_select_device:
                gotoUiSelectDevice();
                break;
            case R.id.layout_trouble_device:
                break;
        }
    }

    private void showTroubleDeviceDialog() {
        if ((mPipeFeatures != null && mPipeFeatures.size() > 0) ||
                (mDeviceFeatures != null && mDeviceFeatures.size() > 0)) {
            if (deviceSelectBottomDialog == null) {
                deviceSelectBottomDialog = new TroubleDeviceSelectBottomDialog(this, mPipeFeatures, mDeviceFeatures);
            }
            if (!deviceSelectBottomDialog.isShowing()) {
                deviceSelectBottomDialog.show();
            }
        }
    }

    private void gotoUiSelectDevice() {
        Intent intent = new Intent();
        intent.setClass(this, UiTroubleSelectDevice.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(TroubleBean.TROUBLE_BEAN_KEY, mTroubleBean);
        int select_type = TroubleBean.TROUBLE_SELECT_DEVICE_NEW;
        if ((mPipeFeatures != null && mPipeFeatures.size() > 0) || (mDeviceFeatures != null && mDeviceFeatures.size() > 0)) {
           if (mPipeFeatures != null && mPipeFeatures.size() > 0) {
                bundle.putSerializable(PipeAttributesBean.TROUBLE_PIPE_ATTRIBUTES_BEAN_KEY, (Serializable) mPipeFeatures);
            }
           if (mDeviceFeatures != null && mDeviceFeatures.size() > 0) {
               bundle.putSerializable(DeviceAttributesBean.TROUBLE_DEVICE_ATTRIBUTES_BEAN_KEY, (Serializable) mDeviceFeatures);
           }

            if (mTappedCoordinate != null)
                bundle.putSerializable(LocationUtil.CURRENT_LOCATION_KEY, mTappedCoordinate);

            select_type = TroubleBean.TROUBLE_SELECT_DEVICE_NEW_UPDATE;
        }
        bundle.putInt(TroubleBean.TROUBLE_BEAN_SELECT_DEVICE_TYPE, select_type);
        intent.putExtras(bundle);
        startActivityForResult(intent, UiTroubleSelectDevice.SELECT_DEVICE_REQUEST_CODE);
        overridePendingTransition(R.anim.anim_rightin, R.anim.anim_leftout);
    }

    private void showAddPictureDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this).
                setItems(new String[]{"拍照", "照片", "录音", "小视频", "附件"},
                        (arg0, i) -> {
                            if (i == 0) {
                                getPicFromSysCamera();
                            } else if (i == 1) {
                                getPicFromSysAlbums();
                            } else if (i == 2) {
                                startAudioRecord();
                            } else if (i == 3) {
                                recordVideo();
                            }else if (i == 4) {
                                requestFileView();
                            }
                        });
        dialog.setCancelable(true);
        dialog.show();
    }

    private WaterMarkParams getWaterMarkParams() {
        WaterMarkParams params = null;
        if (mTroubleBean != null) {
            params = new WaterMarkParams();
            params.mbNeedGps = 1;
            if (mTappedCoordinate != null) {
                String strLng = LocationUtil.formatLocation(mTappedCoordinate.Longtitude);
                String strLat = LocationUtil.formatLocation(mTappedCoordinate.Latitude);
                if (!strLng.isEmpty() && !strLat.isEmpty()) {
                    double lng = Double.parseDouble(strLng);
                    double lat = Double.parseDouble(strLat);
                    strLng = LocationUtil.formatLocation(lng);
                    strLat = LocationUtil.formatLocation(lat);
                    params.mLongitude = strLng;
                    params.mLatitude = strLat;
                }
                params.mAddress = mTappedCoordinate.addr;
            }
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null) {
                params.mUser = userBean.getUsername();
                params.mCompany = userBean.getCompany_name();
            }
            params.mReportTime = DateUtils.getDate(new Date().getTime());
        }
        return params;
    }

    private void getPicFromSysCamera() {
        photoHelper.requestCameraPhoto(true, this::getWaterMarkParams, (success, errStr, pictureBean) -> {
            if (success) {
                if (pictureBean != null) {
                    mPicturesUpload.add(pictureBean);//本地缓存
                    View view = getPhotoViewFromPath(pictureBean);
                    photoGallery.addView(view);
                }
            } else {
                toast(errStr);
            }
        });
    }

    private void getPicFromSysAlbums() {
        photoHelper.requestImagePhoto(true, this::getWaterMarkParams, (success, errStr, pictureBean) -> {
            if (success) {
                if (pictureBean != null) {
                    mPicturesUpload.add(pictureBean);//本地缓存
                    View view = getPhotoViewFromPath(pictureBean);
                    photoGallery.addView(view);
                }
            } else {
                toast(errStr);
            }
        });
    }

    private View getPhotoViewFromPath(TroublePictureBean pictureBean) {
        return photoHelper.getPhotoViewFromPath(pictureBean,
                (view, picture) -> {
                    photoGallery.removeView(view);
                    mPicturesUpload.remove(picture);
                });
    }

    private void startAudioRecord() {
        if (audioRecordHelper != null) {
           boolean hasPermission = audioRecordHelper.checkRecordPermission();
           if (!hasPermission) {
               audioRecordHelper.requestRecordPermission();
           }else {
               btnAddAudio.setCanRecord(true);
               btnAddAudio.setRecordMode();
           }
        }
        btnAddAudio.performClick();
    }

    private View getRecordViewFromAudio(Record record) {
        return audioRecordHelper.getRecordViewFromAudio(record,
                mAudiosRecords, (view, record1) -> {
                    mAudiosRecords.remove(record1);
                    photoGallery.removeView(view);
                });
    }

    private View getVideoViewFromPath(TroublePictureBean pictureBean) {
        return photoHelper.getVideoViewFromPath(pictureBean, (view, picture) -> {
            photoGallery.removeView(view);
            mPicturesUpload.remove(picture);
        });
    }

    private void recordVideo() {
        if (photoHelper == null)
            photoHelper = new PhotoHelper(this, permissionHelper);
        photoHelper.requestRecordSmallVideo((success, errStr, pictureBean) -> {
            if (success) {
                mPicturesUpload.add(pictureBean);//本地缓存
                View view = getVideoViewFromPath(pictureBean);
                photoGallery.addView(view);
            }
        });
    }

    private void requestFileView() {
        photoHelper.requestDocumentFile((success, errStr, document) -> {
            if (success && document != null) {
                View rootView = fileViewUtil.getDocumentView(document, (view1, document1) -> {
                    photoGallery.removeView(view1);
                    mDocumentsUpload.remove(document1);
                });
                if (rootView != null) {
                    mDocumentsUpload.add(document);
                    photoGallery.addView(rootView);
                }
            }
        });
    }

    private boolean isValid() {
        if (mTappedCoordinate == null ||
                mTappedCoordinate.Longtitude == null || mTappedCoordinate.Latitude == null) {
            toast("当前位置不可用");
            return false;
        }

        if ((mPipeFeatures == null || mPipeFeatures.isEmpty()) &&
                (mDeviceFeatures == null || mDeviceFeatures.isEmpty())) {
            toast(R.string.trouble_report_empty_device);
            return false;
        }

        if (editTroubleName.getText().toString().isEmpty()) {
            editTroubleName.requestFocus();
            toast(R.string.trouble_report_empty_name);
            return false;
        }

        if (editReportNote.getText().toString().isEmpty()) {
            editReportNote.requestFocus();
            toast(R.string.trouble_report_empty_info);
            return false;
        }

        if (editReportAddr.getText().toString().isEmpty()) {
            editReportAddr.requestFocus();
            toast(R.string.trouble_report_empty_addr);
            return false;
        }

        if (mWorkState == 1) {    //工作日在现场
            if (mTroubleTypeList == null || mTroubleTypeList.isEmpty() || indexTroubleType == -1) {
                toast(R.string.trouble_report_empty_trotype);
                return false;
            }

            if (mTroubleLevelList == null || mTroubleLevelList.isEmpty() || indexTroubleLevel == -1) {
                toast(R.string.trouble_report_empty_trolevel);
                return false;
            }
            if (mDepartmentList == null || mDepartmentList.isEmpty() || indexDepartment == -1) {
                toast(R.string.trouble_report_empty_depart);
                return false;
            }
            if (mUserList == null || mUserList.isEmpty() || indexUser == -1) {
                toast(R.string.trouble_report_empty_assigner);
                return false;
            }
        }else if (mWorkState == 2) {    //工作日不在现场
            if (mDepartmentList == null || mDepartmentList.isEmpty() || indexDepartment == -1) {
                toast(R.string.trouble_report_empty_depart);
                return false;
            }
            if (mUserList == null || mUserList.isEmpty() || indexUser == -1) {
                toast(R.string.trouble_report_empty_assigner);
                return false;
            }
        }
        return true;
    }

    private void collectData() {
        String troubleId = UUID.randomUUID().toString();
        mTroubleBean.setId(troubleId);
        /*隐患名称*/
        String name = editTroubleName.getText().toString();
        mTroubleBean.setTroubleName(name);
        /*隐患所属单位*/
        String unitName = editTroubleBelong.getText().toString();
        mTroubleBean.setUnitName(unitName);
        /*隐患详情*/
        String notes = editReportNote.getText().toString();
        mTroubleBean.setTroubleInfo(notes);
        /*隐患地址*/
        String lng = LocationUtil.formatLocation(mTappedCoordinate.Longtitude);
        mTroubleBean.setLocationX(lng);
        String lat = LocationUtil.formatLocation(mTappedCoordinate.Latitude);
        mTroubleBean.setLocationY(lat);
        String addr = editReportAddr.getText().toString();
        mTroubleBean.setAddress(addr);
        if (mWorkState == 1) {    //工作日在现场
            TroubleTypeBean typeBean = mTroubleTypeList.get(indexTroubleType);
            mTroubleBean.setTroubleTypeId(typeBean.getId());
            mTroubleBean.setTroubleTypeName(typeBean.getName());
            TroubleRiskLevelBean levelBean = mTroubleLevelList.get(indexTroubleLevel);
            mTroubleBean.setLevelId(levelBean.getId());
            mTroubleBean.setLevelName(levelBean.getName());
            DepartmentBean departmentBean = mDepartmentList.get(indexDepartment);
            mTroubleBean.setDeptId(departmentBean.getId());
            DepartmentUserBean userBean = mUserList.get(indexUser);
            mTroubleBean.setUndertakerUserid(userBean.getId());
        } else if (mWorkState == 2) {    //工作日不在现场
            DepartmentBean departmentBean = mDepartmentList.get(indexDepartment);
            mTroubleBean.setDeptId(departmentBean.getId());
            DepartmentUserBean userBean = mUserList.get(indexUser);
            mTroubleBean.setUndertakerUserid(userBean.getId());
        }
        mTroubleBean.setUploadType(mWorkState);
        if (mPipeFeatures != null && mPipeFeatures.size() > 0) {
            Gson gson = new Gson();
            String strJson = gson.toJson(mPipeFeatures);
            mTroubleBean.setPipeInfo(strJson);
        }
        if (mDeviceFeatures != null && mDeviceFeatures.size() > 0) {
            Gson gson = new Gson();
            String strJson = gson.toJson(mDeviceFeatures);
            mTroubleBean.setDeviceInfo(strJson);
        }
    }

    private void uploadTroubleAlert() {
        String title = "上传数据";
        String content = "是否上传数据?";
        showAlertWithConfirmCancelButton(title, content, true, (dialogInterface, i) -> {
            uploadNewTrouble();
        });
    }

    private void uploadNewTrouble() {
        collectData();
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        troubleTool.uploadNewTrouble(this, mTroubleBean, mPicturesUpload, mAudiosRecords, mDocumentsUpload, new TroubleCallBack(){
            @Override
            public void onAddTrouble(boolean isSuccess, int errorCode, String errMsg, String photoId) {
                super.onAddTrouble(isSuccess, errorCode, errMsg, photoId);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    EventBus.getDefault().post(new MyTroubleEvent(MyTroubleEvent.TROUBLE_UPLOADED));
                    showUploadFinishedDialog();
                }
            }
        });
    }

    private void showUploadFinishedDialog() {
        int title = R.string.trouble_report_title;
        int msg = R.string.trouble_report_upload_ok;
        showAlertWithConfirmButton(title, msg, false, (dialogInterface, i) -> this.finish());
    }
}
