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

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.alibaba.fastjson.JSONObject;
import com.gaoyuan.weixinrecord.example.Record;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.ui.BaseFileActivity;
import com.tofly.ghrq_route.module.gps.service.AmapLocationHelper;
import com.tofly.ghrq_route.module.plan.domain.OfflinePathBean;
import com.tofly.ghrq_route.module.plan.domain.PlanBean;
import com.tofly.ghrq_route.module.planPointRepair.PointRepairTool;
import com.tofly.ghrq_route.module.planPointRepair.controller.PointRepairCallBack;
import com.tofly.ghrq_route.module.planPointRepair.domain.DeviceRouteData;
import com.tofly.ghrq_route.module.planPointRepair.domain.DeviceRouteParam;
import com.tofly.ghrq_route.module.planPointRepair.domain.PlanPointRepair;
import com.tofly.ghrq_route.module.planPointRepair.domain.PointRepairEvent;
import com.tofly.ghrq_route.module.planPointRepair.domain.RouteDeviceType;
import com.tofly.ghrq_route.module.trouble.domain.AuditFileBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
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.SnackBarUtil;
import com.tofly.ghrq_route.common.util.SpinnerUtils;
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.text.TextUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnItemSelected;

@SuppressLint("NonConstantResourceId")
public class UiRouteDeviceCheck extends BaseFileActivity {
    @BindView(R.id.coordinator_layout)
    CoordinatorLayout mainRoot;
    @BindView(R.id.spinner_device_type)
    AppCompatSpinner spinnerDeviceType;
    @BindView(R.id.layout_option)
    LinearLayout layoutOptions;
    @BindView(R.id.layout_route_edit_data)
    LinearLayout layoutEditData;
    @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.valve_materials)
    String[] arrayMaterials;

    private List<RouteDeviceType> mDeviceTypeList;

    private List<DeviceRouteParam> mRouteParamList;

    private int indexDeviceType = -1;

    private int indexMaterial = -1;

    private PlanBean mPlan;

    private OfflinePathBean mPlanPoint;

    private DeviceRouteData mRouteHistory;

    private PointRepairTool pointRepairTool;

    private FileViewUtil fileViewUtil;

    private AmapLocationHelper amapLocationHelper;

    private LocationUtil_xu.CoordinateClass mTappedCoordinate = null;

    private final Map<Integer, String> mCheckedIds = new HashMap<>();

    private final List<EditText> mEditViews = new ArrayList<>();

    private MenuItem menuCommit;

    private boolean isUpdate = false;

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

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

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

    @Override
    public void initView() {
        super.initView();

        setDarkStatusBar();
    }

    @Override
    public void initData() {
        super.initData();

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null){
            mPlan = (PlanBean) bundle.getSerializable(PlanBean.PLAN_BEAN_KEY);
            mPlanPoint = (OfflinePathBean) bundle.getSerializable(OfflinePathBean.PLAN_POINT_BEAN_KEY);
            boolean isNewRecord = bundle.getBoolean(PlanPointRepair.POINT_REPAIR_IS_NEW_KEY, true);
            if (isNewRecord) {
                isUpdate = false;
            }else {
                isUpdate = true;
                mRouteHistory = (DeviceRouteData) bundle.getSerializable(DeviceRouteData.DEVICE_ROUTE_DATA_KEY);
            }
        }

        pointRepairTool = PointRepairTool.getInstance();

        fileViewUtil = new FileViewUtil(this);

        amapLocationHelper = new AmapLocationHelper(this);
        amapLocationHelper.startLocating();

        getDeviceTypes();

        if (isUpdate) {
            if (mRouteHistory != null) {
                editReportNote.setText(mRouteHistory.getNote());
            }
            getPhotoAudios();
        }
    }

    @Override
    public void initListener() {
        super.initListener();

        amapLocationHelper.setMapLocationListener((location, addr, projLoc) -> {
            mTappedCoordinate = new LocationUtil_xu.CoordinateClass(projLoc.getX(), projLoc.getY(), addr);
            amapLocationHelper.reserveLocation(location.getX(), location.getY());
        });

        amapLocationHelper.setReserveLocListener((isSuccess, addr) -> {
            if (isSuccess) {
                mTappedCoordinate.addr = addr;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commit, menu);
        menuCommit = menu.findItem(R.id.action_commit);
        if (!isUpdate) {
            menuCommit.setTitle(R.string.upload);
        }else {
            menuCommit.setTitle(R.string.update);
        }
        return super.onCreateOptionsMenu(menu);
    }

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

    private void getPhotoAudios() {
        String routeId = mRouteHistory.getId();
        List<AuditFileBean> photos = mRouteHistory.getPhotos();
        for (AuditFileBean photo : photos) {
            getUploadPhoto(photo, routeId);
        }

        List<AuditFileBean> audios = mRouteHistory.getAudios();
        for (AuditFileBean audio : audios) {
            getUploadAudio(audio, routeId);
        }
    }

    private void getUploadPhoto(AuditFileBean photo, String routeId) {
        String fileName = photo.getFileName();
        String fileUrl = photo.getPath();
        fileViewUtil.getImageFileView(routeId, fileUrl, fileName, (view, picture) -> {
            photoGallery.removeView(view);
            mPicturesUpload.remove(picture);
        }, (isSuccess, view, picture) -> {
            if (isSuccess) {
                if (view != null && picture != null) {
                    photoGallery.addView(view);
                    mPicturesUpload.add(picture);
                }
            }
        });
    }

    private void getUploadAudio(AuditFileBean audio, String routeId) {
        String fileUrl = audio.getPath();
        String fileNote = "附件";
        fileViewUtil.getAudioFileView(routeId, fileUrl, 1, fileNote, mAudiosRecords, (view, record) -> {
            photoGallery.removeView(view);
            mAudiosRecords.remove(record);
        }, (isSuccess, view) -> {
            if (isSuccess) {
                if (view != null) {
                    photoGallery.addView(view);
                    Record record = (Record) view.getTag();
                    if (record != null) {
                        mAudiosRecords.add(record);
                    }
                }
            }
        });
    }

    private void getDeviceTypes() {
        String typeIds = mPlan.getCheckContent();
        if (isUpdate && mRouteHistory != null) {
            int typeId = mRouteHistory.getTypeId();
            typeIds = typeId + "";
        }
        pointRepairTool.getRouteDeviceTypeList(this, typeIds, new PointRepairCallBack(){
            @Override
            public void onGetDatas(boolean isSuccess, int errorCode, String errMsg, List deviceList, int total) {
                super.onGetDatas(isSuccess, errorCode, errMsg, deviceList, total);
                if (isSuccess) {
                    mDeviceTypeList = deviceList;
                    setDeviceTypeAdapter();
                }else {
                    SnackBarUtil.showSnackAlways(mainRoot, "加载巡检设备类型失败", "重试", view -> getDeviceTypes());
                }
            }
        });
    }

    private void setDeviceTypeAdapter(){
        List<String> nameList = new ArrayList<>();
        for (RouteDeviceType deviceType : mDeviceTypeList) {
            nameList.add(deviceType.getName());
        }
        SpinnerUtils.setAdapter(this, spinnerDeviceType, nameList);
    }

    protected void getDeviceRouteParams() {
        layoutOptions.removeAllViews();
        layoutEditData.removeAllViews();
        RouteDeviceType deviceType = mDeviceTypeList.get(indexDeviceType);
        if (deviceType != null) {
            pointRepairTool.getDeviceRouteParamList(this, deviceType.getId() + "", new PointRepairCallBack() {
                @Override
                public void onGetDatas(boolean isSuccess, int errorCode, String errMsg, List dataList, int total) {
                    super.onGetDatas(isSuccess, errorCode, errMsg, dataList, total);
                    if (isSuccess) {
                        mRouteParamList = dataList;
                        onRouteParamsSetUI();
                    }else {
                        SnackBarUtil.showSnackAlways(mainRoot, "加载设备检修参数列表失败", "重试", view -> getDeviceRouteParams());
                    }
                }
            });
        }
    }

    private void onRouteParamsSetUI() {
        mCheckedIds.clear();
        mEditViews.clear();

        boolean hasCheckNone = true;
        RouteDeviceType deviceType = mDeviceTypeList.get(indexDeviceType);
        RouteDeviceType.ROUTE_DEVICE_TYPE device = RouteDeviceType.ROUTE_DEVICE_TYPE.TypeID(deviceType.getId());
        if (device == RouteDeviceType.ROUTE_DEVICE_TYPE.ROUTE_DEVICE_YJBH) {
            hasCheckNone = false;
        }

        if (mRouteParamList != null) {
            for (DeviceRouteParam routeParam : mRouteParamList) {
                int id = routeParam.getId();
                mCheckedIds.put(id, "1");
                View view = getViewFromRoutParam(routeParam, hasCheckNone);
                layoutOptions.addView(view);
            }
        }

        View view = getEditViewFromDeviceType(device);
        if (view != null) {
            layoutEditData.addView(view);
        }
    }

    private View getEditViewFromDeviceType(RouteDeviceType.ROUTE_DEVICE_TYPE device_type) {
        View rootView = null;
        switch (device_type) {
            case ROUTE_DEVICE_TYG:
                rootView = LayoutInflater.from(this).inflate(R.layout.layout_tyg_route_edit_data, null);
                EditText editRunPress = rootView.findViewById(R.id.edit_run_press);
                editRunPress.setTag("runPressure");
                TextUtil.setTextInputDigitNum(editRunPress, 2);
                mEditViews.add(editRunPress);
                EditText editDiffusePress = rootView.findViewById(R.id.edit_diffuse_press);
                editDiffusePress.setTag("diffusePressure");
                TextUtil.setTextInputDigitNum(editDiffusePress, 2);
                mEditViews.add(editDiffusePress);
                EditText editFlowPress = rootView.findViewById(R.id.edit_flow_press);
                editFlowPress.setTag("workPressure");
                TextUtil.setTextInputDigitNum(editFlowPress, 2);
                mEditViews.add(editFlowPress);
                if (isUpdate && mRouteHistory != null) {
                    String runPressure = mRouteHistory.getRunPressure();
                    editRunPress.setText(runPressure);
                    String diffusePressure = mRouteHistory.getDiffusePressure();
                    editDiffusePress.setText(diffusePressure);
                    String workPressure = mRouteHistory.getWorkPressure();
                    editFlowPress.setText(workPressure);
                }
                break;
            case ROUTE_DEVICE_TYX:
                rootView = LayoutInflater.from(this).inflate(R.layout.layout_tyx_route_edit_data, null);
                EditText editRunPressTyx = rootView.findViewById(R.id.edit_run_press);
                editRunPressTyx.setTag("runPressure");
                TextUtil.setTextInputDigitNum(editRunPressTyx, 2);
                mEditViews.add(editRunPressTyx);
                EditText editCutPress = rootView.findViewById(R.id.edit_cut_press);
                editCutPress.setTag("truncationPressure");
                TextUtil.setTextInputDigitNum(editCutPress, 2);
                mEditViews.add(editCutPress);
                if (isUpdate && mRouteHistory != null) {
                    String runPressure = mRouteHistory.getRunPressure();
                    editRunPressTyx.setText(runPressure);
                    String truncationPressure = mRouteHistory.getTruncationPressure();
                    editCutPress.setText(truncationPressure);
                }
                break;
            case ROUTE_DEVICE_FAJING:
                indexMaterial = 0;
                rootView = LayoutInflater.from(this).inflate(R.layout.layout_fajing_route_edit_data, null);
                AppCompatSpinner spinnerMaterial = rootView.findViewById(R.id.spinner_material);
                SpinnerUtils.setAdapter(this, spinnerMaterial, arrayMaterials);
                spinnerMaterial.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                        indexMaterial = i;
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> adapterView) {

                    }
                });
                EditText editSpecification = rootView.findViewById(R.id.edit_specification);
                editSpecification.setTag("specification");
                mEditViews.add(editSpecification);
                if (isUpdate && mRouteHistory != null) {
                    String material = mRouteHistory.getMaterial();
                    for (int i = 0; i < arrayMaterials.length; i++) {
                        String material1 = arrayMaterials[i];
                        if (material.equals(material1)) {
                            indexMaterial = i;
                            break;
                        }
                    }
                    spinnerMaterial.setSelection(indexMaterial);
                    String specification = mRouteHistory.getSpecification();
                    editSpecification.setText(specification);
                }
                break;
            case ROUTE_DEVICE_YJBH:
                rootView = LayoutInflater.from(this).inflate(R.layout.layout_yjbh_route_edit_data, null);
                EditText editJCZCode = rootView.findViewById(R.id.edit_jdz_code);
                editJCZCode.setTag("deviceId");
                mEditViews.add(editJCZCode);
                EditText editStandardVol = rootView.findViewById(R.id.edit_standard_voltage);
                editStandardVol.setTag("standardPotential");
                TextUtil.setTextInputDigitNum(editStandardVol, 2);
                mEditViews.add(editStandardVol);
                EditText editDetectVol = rootView.findViewById(R.id.edit_detect_voltage);
                editDetectVol.setTag("detectionPotential");
                TextUtil.setTextInputDigitNum(editDetectVol, 2);
                mEditViews.add(editDetectVol);
                if (isUpdate && mRouteHistory != null) {
                    String deviceId = mRouteHistory.getDeviceId();
                    editJCZCode.setText(deviceId);
                    String standardPotential = mRouteHistory.getStandardPotential();
                    editStandardVol.setText(standardPotential);
                    String detectionPotential = mRouteHistory.getDetectionPotential();
                    editDetectVol.setText(detectionPotential);
                }
                break;
        }
        return rootView;
    }

    private View getViewFromRoutParam(DeviceRouteParam routeParam, boolean hasCheckNone) {
        View rootView = LayoutInflater.from(this).inflate(R.layout.item_radio_yes_no, null);
        TextView textName = rootView.findViewById(R.id.text_title);
        textName.setText(routeParam.getName());
        RadioGroup radioGroup = rootView.findViewById(R.id.radio_group);
        radioGroup.setTag(routeParam);
        RadioButton radioCheckNone = rootView.findViewById(R.id.check_none);
        radioCheckNone.setVisibility(hasCheckNone ? View.VISIBLE : View.INVISIBLE);
        radioGroup.setOnCheckedChangeListener((radioGroup1, checkedId) -> {
            int check_type = 1;
            if (checkedId == R.id.check_yes) {
                check_type = 1;
                textName.setPaintFlags(textName.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
            }else if (checkedId == R.id.check_no) {
                check_type = 0;
                textName.setPaintFlags(textName.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
            }else if (checkedId == R.id.check_none) {
                check_type = 2;
                textName.setPaintFlags(textName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            }
            DeviceRouteParam param = (DeviceRouteParam) radioGroup1.getTag();
            int id = -1;
            if (param != null)
                id = param.getId();
            setSelectedItem(id, check_type);
        });
        if (isUpdate && mRouteHistory != null) {
            int id = routeParam.getId();
            DeviceRouteData.ContentOBJ contentOBJ = getContentCheckValue(id);
            if (contentOBJ != null) {
                int check_type = contentOBJ.getChoose();
                switch (check_type) {
                    case 0:
                        radioGroup.check(R.id.check_no);
                        textName.setPaintFlags(textName.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
                        break;
                    case 1:
                        radioGroup.check(R.id.check_yes);
                        textName.setPaintFlags(textName.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
                        break;
                    case 2:
                        radioGroup.check(R.id.check_none);
                        textName.setPaintFlags(textName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                        break;
                }
            }
        }
        return rootView;
    }

    private DeviceRouteData.ContentOBJ getContentCheckValue(int id) {
        DeviceRouteData.ContentOBJ checkContent = null;
        List<DeviceRouteData.ContentOBJ> contentIds = mRouteHistory.getXjConList();
        for (DeviceRouteData.ContentOBJ contentOBJ : contentIds) {
            if (contentOBJ.getMenuId() == id) {
                checkContent = contentOBJ;
                break;
            }
        }
        return checkContent;
    }

    private void setSelectedItem(int id, int check_type) {
        if (id != -1) {
            mCheckedIds.put(id, check_type + "");
        }
    }

    @OnItemSelected({R.id.spinner_device_type})
    public void onItemSelected(AdapterView<?> parent, int position){
        switch (parent.getId()) {
            case R.id.spinner_device_type:
                indexDeviceType = position;
                getDeviceRouteParams();
                break;
        }
    }


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

        if (!mEditViews.isEmpty()) {
            for (EditText editView : mEditViews) {
                String input = editView.getText().toString();
                if (input.isEmpty()) {
                    editView.requestFocus();
                    toast(editView.getHint().toString());
                    return false;
                }
            }
        }

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

        if (mPicturesUpload.isEmpty() && mAudiosRecords.isEmpty() && mDocumentsUpload.isEmpty()) {
            toast(R.string.report_empty_file);
            return false;
        }

        return true;
    }

    private JSONObject collectData() {
        JSONObject jsonObject = new JSONObject();

        int index = 0;
        if (isUpdate) {
            for (Map.Entry<Integer, String> entry : mCheckedIds.entrySet()) {
                String menuId = entry.getKey().toString();
                String check_value = entry.getValue();

                String key = String.format(Locale.CHINA, "content[%d].menuId", index);
                String value = menuId;
                jsonObject.put(key, value);

                key = String.format(Locale.CHINA, "content[%d].choose", index);
                value = check_value;
                jsonObject.put(key, value);

                DeviceRouteData.ContentOBJ contentOBJ = getContentCheckValue(Integer.parseInt(menuId));
                if (contentOBJ != null) {
                    String id = contentOBJ.getId();
                    key = String.format(Locale.CHINA, "content[%d].id", index);
                    jsonObject.put(key, id);

                    String recordId = contentOBJ.getRecordId();
                    key = String.format(Locale.CHINA, "content[%d].recordId", index);
                    jsonObject.put(key, recordId);

                    String typeId = contentOBJ.getTypeId();
                    key = String.format(Locale.CHINA, "content[%d].typeId", index);
                    jsonObject.put(key, typeId);

                    String typeName = contentOBJ.getTypeName();
                    if (typeName != null) {
                        key = String.format(Locale.CHINA, "content[%d].typeName", index);
                        jsonObject.put(key, typeName);
                    }

                    int delFlag = contentOBJ.getDelFlag();
                    key = String.format(Locale.CHINA, "content[%d].delFlag", index);
                    jsonObject.put(key, delFlag + "");
                }
                index++;
            }
        }else {
            for (Map.Entry<Integer, String> entry : mCheckedIds.entrySet()) {
                String id = entry.getKey().toString();
                String check_value = entry.getValue();

                String key = String.format(Locale.CHINA, "content[%d].menuId", index);
                String value = id;
                jsonObject.put(key, value);

                key = String.format(Locale.CHINA, "content[%d].choose", index);
                value = check_value;
                jsonObject.put(key, value);
                index++;
            }
        }

        /*地址*/
        String lng = LocationUtil.formatLocation(mTappedCoordinate.Longtitude);
        jsonObject.put("x", lng);
        String lat = LocationUtil.formatLocation(mTappedCoordinate.Latitude);
        jsonObject.put("y", lat);
        String addr = mTappedCoordinate.addr;
        if (addr != null && !addr.isEmpty())
            jsonObject.put("address", addr);

        /*设备类型id*/
        RouteDeviceType deviceType = mDeviceTypeList.get(indexDeviceType);
        if (deviceType != null) {
            int typeId = deviceType.getId();
            jsonObject.put("typeId", typeId);
        }

        /*计划id*/
        if (mPlanPoint != null) {
            String plan_id = mPlanPoint.getPlan_id();
            jsonObject.put("childPlanId", plan_id);

            String pointId = mPlanPoint.getPoint_id();
            jsonObject.put("planTempPointId", pointId);
        }

        /*输入框填写数据*/
        if (!mEditViews.isEmpty()) {
            for (EditText editView : mEditViews) {
                String tag = (String) editView.getTag();
                String value = editView.getText().toString();
                jsonObject.put(tag, value);
            }
        }

        /*阀门材质*/
        RouteDeviceType.ROUTE_DEVICE_TYPE device = RouteDeviceType.ROUTE_DEVICE_TYPE.TypeID(deviceType.getId());
        if (device == RouteDeviceType.ROUTE_DEVICE_TYPE.ROUTE_DEVICE_FAJING) {
            if (indexMaterial != -1) {
                String material = arrayMaterials[indexMaterial];
                jsonObject.put("material", material);
            }
        }

        /*详情*/
        String notes = editReportNote.getText().toString();
        if (notes != null && !notes.isEmpty())
            jsonObject.put("note", notes);

        /*检查时间*/
        jsonObject.put("checkDate", DateUtils.getDate());

        if (isUpdate && mRouteHistory != null) {
            jsonObject.put("id", mRouteHistory.getId());
        }

        return jsonObject;
    }

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

    private void uploadDeviceRouteRecord() {
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);

        JSONObject jsonObject = collectData();
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(mAudiosRecords);
        pointRepairTool.uploadDeviceRouteRecord(this, jsonObject, mPicturesUpload, audioBeans, isUpdate, new PointRepairCallBack() {
            @Override
            public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                super.onSetData(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    onUploadFinish();
                }
            }
        });
    }

    private void onUploadFinish(){
        menuCommit.setEnabled(false);
        String msg = PointRepairEvent.REPAIR_ROUTE_UPLOADED;
        EventBus.getDefault().post(new PointRepairEvent(msg, mPlanPoint));
        showUploadFinishedDialog();
    }

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

    @Override
    public Button getAddPhotoBtn() {
        return btnAddPhoto;
    }

    @Override
    public LinearLayout getPhotoGallery() {
        return photoGallery;
    }

    @Override
    public MyAudioRecordButton getAudioRecordBtn() {
        return btnAddAudio;
    }

    @Override
    public LocationUtil_xu.CoordinateClass getLocation() {
        return mTappedCoordinate;
    }
}
