package com.tofly.ghrq_route.common.ui.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.annotation.NonNull;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.Toolbar;

import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.nostra13.universalimageloader.core.ImageLoader;
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.base.url.NetRequestURL;
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.PlanPointRepair;
import com.tofly.ghrq_route.module.planPointRepair.domain.PointRepairEvent;
import com.tofly.ghrq_route.module.trouble.domain.PictureFileTypeSort;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.uploadFile.controller.UploadFileCallBack;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.common.util.image.ImageUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

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

/**
 * Created by Amu on 2017/6/8.
 */

public class UiRepairUpdateStep extends BaseUi {
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.text_repair_sid)
    TextView textRepairSid;
    @BindView(R.id.text_repair_subtype)
    TextView textRepairSubtype;
    @BindView(R.id.text_repair_addr)
    TextView textRepairAddr;
    @BindView(R.id.layout_main_press_on)
    LinearLayout layoutMainPressOn;
    @BindView(R.id.edit_repair_pressure_on)
    EditText editRepairPressureOn;
    @BindView(R.id.layout_sub_press_off)
    LinearLayout layoutSubPressOff;
    @BindView(R.id.edit_repair_sub_pressure_off)
    EditText editRepairSubPressureOff;
    @BindView(R.id.layout_main_press_off)
    LinearLayout layoutMainPressOff;
    @BindView(R.id.edit_repair_pressure_off)
    EditText editRepairPressureOff;
    @BindView(R.id.layout_main_press_cut)
    LinearLayout layoutMainPressCut;
    @BindView(R.id.edit_repair_pressure_cut)
    EditText editRepairPressureCut;
    @BindView(R.id.layout_normal)
    LinearLayout layoutNormal;
    @BindView(R.id.edit_repair_normal)
    EditText editRepairIsNormal;
    @BindView(R.id.layout_switch)
    LinearLayout layoutSwitch;
    @BindView(R.id.edit_repair_switch_flexible)
    EditText editRepairSwitchFlexible;
    @BindView(R.id.layout_leak_detect)
    LinearLayout layoutLeakDetect;
    @BindView(R.id.edit_repair_leak_detect)
    EditText editRepairLeakDetect;
    @BindView(R.id.edit_report_note)
    EditText editReportNote;
    @BindView(R.id.text_add_photo)
    TextView textAddPhoto;
    @BindView(R.id.text_type_popup)
    TextView textTypePopup;
    @BindView(R.id.layout_btn_add)
    LinearLayout layoutBtnAdd;
    @BindView(R.id.btn_add_photo)
    Button btnAddPhoto;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindView(R.id.layout_addpic_area)
    LinearLayout layoutAddpicArea;
    @BindView(R.id.layout_update)
    LinearLayout layoutUpdate;
    @BindView(R.id.btn_update)
    Button btnUpdate;
    @BindArray(R.array.repair_photo_type)
    String[] repairTypes;

    private MenuItem menuRemove;
    private MenuItem menuUpload;

    private PlanPointRepair mPointRepair;

    private OfflinePathBean mPlanPoint;

    private PlanBean mPlan;

    private boolean isUpdate = false;

    //private boolean isChildPlan = false;

    private boolean isEditable = false;

    private boolean isRemovable = false;

    private boolean isLocal = false;

    private boolean mbNeedRemoveCache = false;

    private PointRepairTool repairTool;

    private int mPhotoType = 0;

    private List<TroublePictureBean> mPicturesUpload = new ArrayList<>();
    private PhotoHelper photoHelper;
    private PermissionHelper permissionHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_repair_update_step);
        ButterKnife.bind(this);

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

    private void initView() {

    }

    private void initData() {
        repairTool = PointRepairTool.getInstance();
        permissionHelper = new PermissionHelper(this);
        photoHelper = new PhotoHelper(this, permissionHelper);

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mPointRepair = (PlanPointRepair) bundle.getSerializable(PlanPointRepair.POINT_REPAIR_BEAN_KEY);
            mPlanPoint = (OfflinePathBean) bundle.getSerializable(OfflinePathBean.PLAN_POINT_BEAN_KEY);
            mPlan = (PlanBean) bundle.getSerializable(PlanBean.PLAN_BEAN_KEY);
            isUpdate = bundle.getBoolean(PlanPointRepair.POINT_REPAIR_UPDATE_KEY, false);
            isEditable = bundle.getBoolean(PlanPointRepair.POINT_REPAIR_EDITABLE_KEY, true);
            isRemovable = bundle.getBoolean(PlanPointRepair.POINT_REPAIR_REMOVABLE_KEY, true);
            if (mPointRepair != null) {
                String sid = mPointRepair.getPoint_id();
                textRepairSid.setText(sid);

                String addr = mPointRepair.getAddress();
                textRepairAddr.setText(addr);

                textTypePopup.setText(repairTypes[mPhotoType]);

                if (isUpdate) {
                    boolean isCommonDevice = mPlan.isCommonDeviceType();
                    if (isCommonDevice){
                    }
                    String note = mPointRepair.getNotes();
                    editReportNote.setText(note);

                    int visible = isEditable ?  View.VISIBLE : View.GONE;
                    layoutBtnAdd.setVisibility(visible);
                    layoutUpdate.setVisibility(visible);

                    isLocal = mPointRepair.getState() == TroubleBean.SAVED_STATE;

                    if (isLocal){
                        String localId = mPointRepair.getTemp_id();
                        loadSavedTroublePictures(localId);
                    }else {
                        getUploadFiles();
                    }
                }
            }
        }
    }

    private void initListener() {
        setOnNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mbNeedRemoveCache)
                    removeCacheFile();
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (mbNeedRemoveCache)
            removeCacheFile();
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_remove_upload, menu);
        menuUpload = menu.findItem(R.id.action_commit);
        menuUpload.setVisible(isLocal);
        menuRemove = menu.findItem(R.id.action_remove);
        menuRemove.setVisible(isRemovable);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_remove: {
                showRemoveAlert();
            }
            break;
            case R.id.action_commit:{
                if (checkValid()){
                    showUploadAlertDialog();
                }
            }
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick({R.id.text_type_popup, R.id.btn_add_photo, R.id.btn_update})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.text_type_popup: {
                showPhotoTypePopupWindow();
            }
            break;
            case R.id.btn_add_photo: {
                showAddPictureDialog();
            }
            break;
            case R.id.btn_update: {
                if (checkValid()) {
                    updatePlanPointRepair();
                }
            }
            break;
        }
    }

    private void showPhotoTypePopupWindow() {
        final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setAdapter(new ArrayAdapter<>(this, R.layout.popup_content_item, repairTypes));
        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mPhotoType = position;
                listPopupWindow.dismiss();
                String state = repairTypes[position];
                textTypePopup.setText(state);
            }
        });
        listPopupWindow.setAnchorView(textTypePopup);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setModal(true);
        listPopupWindow.show();
    }

    private void showAddPictureDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(UiRepairUpdateStep.this).
                setItems(new String[]{"拍照", "从手机相册选择"},
                        (arg0, i) -> {
                            if (i == 0) {
                                getPicFromSysCamera();
                            } else if (i == 1) {
                                getPicFromSysAlbums();
                            }
                        });
        dialog.setCancelable(true);
        dialog.show();
    }

    @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 (photoHelper != null) {
            photoHelper.handleActivityResult(requestCode, resultCode, data);
        }
    }

    private WaterMarkParams getWaterMarkParams(){
        WaterMarkParams params = null;
        if (mPointRepair != null){
            params = new WaterMarkParams();
            params.mbNeedGps = 1;
            double lon = mPointRepair.getLng();
            double lat = mPointRepair.getLat();
            BigDecimal decimal = new BigDecimal(lon);
            lon = decimal.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
            decimal = new BigDecimal(lat);
            lat = decimal.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
            params.mLongitude = Double.toString(lon);
            params.mLatitude = Double.toString(lat);
            params.mGpsFlag = 0;
            params.mAddress = mPointRepair.getAddress();
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null){
                params.mUser = userBean.getRealName();
                params.mCompany = userBean.getCompany_name();
            }
            params.mReportTime = DateUtils.getDate(new Date().getTime());
        }
        return params;
    }

    /*private void getPicFromSysAlbums() {
        if (photoHelper == null)
            photoHelper = new PhotoHelper(this, permissionHelper);
        photoHelper.requestImagePhoto(true, new PhotoHelper.GetWatermarkParams() {
            @Override
            public WaterMarkParams onGetWatermarkParams() {
                return getWaterMarkParams();
            }
        }, new PhotoHelper.PhotoListener() {
            @Override
            public void getPhoto(boolean success, String errStr, TroublePictureBean pictureBean) {
                if (success) {
                    if (pictureBean != null) {
                        pictureBean.setFiletype(repairTypes[mPhotoType]);
                        pictureBean.setStatus(TroublePictureBean.PHOTO_LOCAL_STATE);
                        mPicturesUpload.add(pictureBean);//本地缓存
                        layoutAddpicArea.setVisibility(View.VISIBLE);
                        View view = getPhotoViewFromPath(pictureBean);
                        photoGallery.addView(view);
                    }
                } else {
                    toast(errStr);
                }
            }
        });
    }*/

    private void getPicFromSysCamera() {
        photoHelper.requestCameraPhoto(true, () -> getWaterMarkParams(), (success, errStr, pictureBean) -> {
            if (success) {
                if (pictureBean != null) {
                    pictureBean.setFiletype(repairTypes[mPhotoType]);
                    pictureBean.setStatus(TroublePictureBean.PHOTO_LOCAL_STATE);
                    mPicturesUpload.add(pictureBean);//本地缓存
                    layoutAddpicArea.setVisibility(View.VISIBLE);
                    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) {
                    pictureBean.setFiletype(repairTypes[mPhotoType]);
                    pictureBean.setStatus(TroublePictureBean.PHOTO_LOCAL_STATE);
                    mPicturesUpload.add(pictureBean);//本地缓存
                    layoutAddpicArea.setVisibility(View.VISIBLE);
                    View view = getPhotoViewFromPath(pictureBean);
                    photoGallery.addView(view);
                }
            } else {
                toast(errStr);
            }
        });
    }

    private ArrayList<String> getPicsPath(){
        ArrayList<String> pics = new ArrayList<>();
        for (TroublePictureBean pictureBean : mPicturesUpload){
            if (pictureBean != null)
                pics.add(pictureBean.getFilepath());
        }
        return pics;
    }


    @SuppressLint("InflateParams")
    public View getPhotoViewFromPath(final TroublePictureBean picture) {
        final View rootView = getLayoutInflater().inflate(R.layout.item_repair_photo, null);
        rootView.setTag(picture);

        TextView textPhotoType = rootView.findViewById(R.id.text_photo_type);
        ImageView imageUploadPhoto = rootView.findViewById(R.id.image_upload_photo);
        final ProgressBar progressUpload = rootView.findViewById(R.id.progress_upload);
        final TextView textUploadHint = rootView.findViewById(R.id.text_upload_hint);
        final ImageView imageOperation = rootView.findViewById(R.id.image_upload_operation);

        String photoType = picture.getFiletype();
        textPhotoType.setText(photoType);

        final String photoPath = picture.getFilepath();
        int state = picture.getStatus();
        if (state == TroublePictureBean.PHOTO_LOCAL_STATE) {
            Bitmap bitmap = ImageUtil.getimage(photoPath, 100, 100);
            imageUploadPhoto.setImageBitmap(bitmap);
            if (mPointRepair != null) {
                imageOperation.setVisibility(View.GONE);
                progressUpload.setVisibility(View.VISIBLE);
                textUploadHint.setText("正在上传");
                addUploadFile(picture, rootView);
            }
        } else if (state == TroublePictureBean.PHOTO_UPLOADED) {
            if (photoPath != null) {
                ImageLoader loader = ImageLoader.getInstance();
                loader.displayImage(photoPath, imageUploadPhoto);
                imageOperation.setVisibility(View.GONE);
                progressUpload.setVisibility(View.GONE);
                textUploadHint.setVisibility(View.GONE);
            }
        } else if (state == TroublePictureBean.PHOTO_SAVED_STATE){
            Bitmap bitmap = ImageUtil.getimage(photoPath, 100, 100);
            imageUploadPhoto.setImageBitmap(bitmap);
            imageOperation.setVisibility(View.GONE);
            progressUpload.setVisibility(View.GONE);
            textUploadHint.setVisibility(View.GONE);
        }

        rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 点击图片查看大图
                TroublePictureBean pictureBean = (TroublePictureBean) view.getTag();
                String PicAbsolutePath = pictureBean.getFilepath();
                Bundle mBundle = new Bundle();
                mBundle.putString(ImageUtil.CURRENT_PATH_KEY, PicAbsolutePath);
                mBundle.putStringArrayList(ImageUtil.PICS_PATH_KEY, getPicsPath());
                Intent intent = new Intent(UiRepairUpdateStep.this, UiBigImageList.class);
                intent.putExtras(mBundle);
                startActivity(intent);
            }
        });

        imageOperation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                picture.setStatus(TroublePictureBean.PHOTO_UPLOADING);
                imageOperation.setVisibility(View.GONE);
                progressUpload.setVisibility(View.VISIBLE);
                textUploadHint.setText("正在上传");
                addUploadFile(picture, rootView);
            }
        });

        rootView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(final View view) {
                if (isEditable){
                    String title = "删除图片";
                    String content = "是否删除图片?";
                    AlertDialog.Builder builder = new AlertDialog.Builder(UiRepairUpdateStep.this);
                    builder.setTitle(title);
                    builder.setMessage(content);
                    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            TroublePictureBean pictureBean = (TroublePictureBean) view.getTag();
                            if (pictureBean.getStatus() != TroublePictureBean.PHOTO_UPLOADED) {
                                FileUtil.deleteFile(pictureBean.getFilepath());
                                photoGallery.removeView(view);
                                mPicturesUpload.remove(picture);
                            } else {
                                String fileid = pictureBean.getId();
                                removeUploadFile(fileid, view, picture);
                            }
                        }
                    });
                    builder.setNegativeButton(android.R.string.cancel, null);
                    builder.show();
                }
                return true;
            }
        });

        return rootView;
    }

    private void addUploadFile(final TroublePictureBean picture, final View rootView) {
        final ImageView imageUploadPhoto = rootView.findViewById(R.id.image_upload_photo);
        final TextView textUploadHint = rootView.findViewById(R.id.text_upload_hint);
        final ImageView imageOperation = rootView.findViewById(R.id.image_upload_operation);
        final ProgressBar progressUpload = rootView.findViewById(R.id.progress_upload);
        repairTool.addRepairUploadFile(this, mPointRepair.getTemp_id(), picture, new PointRepairTool.AddRepairUploadFileCallback(){
            @Override
            public void onAddUploadPhoto(boolean isSuccess, TroublePictureBean photo) {
                if (isSuccess){
                    textUploadHint.setText("上传成功");
                    progressUpload.setVisibility(View.GONE);
                    imageOperation.setVisibility(View.GONE);
                    if (photo != null && photo.getFilepath() != null){
                        String filepath = photo.getFilepath();
                        String url = NetRequestURL.getHttpHead() + filepath;
                        ImageLoader loader = ImageLoader.getInstance();
                        loader.displayImage(url, imageUploadPhoto);
                        textUploadHint.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                textUploadHint.setVisibility(View.GONE);
                            }
                        }, 2000);
                    }
                }else {
                    textUploadHint.setText("上传失败");
                    progressUpload.setVisibility(View.GONE);
                    imageOperation.setVisibility(View.VISIBLE);
                    imageOperation.setImageResource(R.mipmap.ic_retry_white_24dp);
                }
            }
        });
    }

    private void removeUploadFile(String file_id, final View view, final TroublePictureBean picture) {
        String strUploading = getString(R.string.repair_update_deleting_photo);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);

        repairTool.removeRepairUploadFile(this, file_id, picture, new UploadFileCallBack(){
            @Override
            public void onRemoveUploadFile(boolean isSuccess, int errorCode, String errMsg) {
                super.onRemoveUploadFile(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    photoGallery.removeView(view);
                    mPicturesUpload.remove(picture);
                }
            }
        });
    }

    private void loadSavedTroublePictures(String repairId){
        List<TroublePictureBean> pictures = repairTool.getLocalRepairPhotos(repairId);
        Collections.sort(pictures, new PictureFileTypeSort(repairTypes));
        mPicturesUpload = new ArrayList<>();
        for (TroublePictureBean picture : pictures){
            if (picture != null){
                mPicturesUpload.add(picture);
                String path = picture.getFilepath();
                boolean isExists = FileUtil.fileExists(path);
                if (isExists){
                    View view = getPhotoViewFromPath(picture);
                    photoGallery.addView(view);
                }
            }
        }
    }

    private void getUploadFiles() {
        if (mPointRepair != null) {
            String strUploading = getString(R.string.repair_update_getting_photo);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);

            repairTool.getRepairUploadFiles(this, mPointRepair.getTemp_id(), 1, new PointRepairTool.GetRepairUploadFileCallback() {
                @Override
                public void onGetUploadPhotos(boolean isSuccess, List<TroublePictureBean> photos) {
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess && photos != null){
                        layoutAddpicArea.setVisibility(View.VISIBLE);
                        mPicturesUpload.addAll(photos);//本地缓存
                        for (TroublePictureBean pictureBean : photos){
                            View view = getPhotoViewFromPath(pictureBean);
                            photoGallery.addView(view);
                        }
                    }else {
                        layoutAddpicArea.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    private boolean checkValid() {
        boolean isCommonDevice = mPlan.isCommonDeviceType();
        if (isCommonDevice)
            return true;

        String onPressure = editRepairPressureOn.getText().toString();
        String offPressure = editRepairPressureOff.getText().toString();
        String cutPressure = editRepairPressureCut.getText().toString();
        String subPressure = editRepairSubPressureOff.getText().toString();
        String notes = editReportNote.getText().toString();

        if (onPressure.isEmpty()) {
            toast("请填写主路运行压力数据");
            return false;
        }

        if (offPressure.isEmpty()) {
            toast("请填写主路关闭压力数据");
            return false;
        }

        if (subPressure.isEmpty()) {
            toast("请填写副路关闭压力数据");
            return false;
        }


        if (cutPressure.isEmpty()) {
            toast("请填写切断压力数据");
            return false;
        }

        if (isLocal){
            if (repairTool.isUploadingRepairtRecord(mPointRepair.getTemp_id())){
                toast("后台数据正在上传中，不可重复提交！");
                return false;
            }
        }
                mPointRepair.setNotes(notes);
        return true;
    }

    private void updatePlanPointRepair() {
        if (mPointRepair != null) {
            String strUploading = getString(R.string.repair_update_updating_data);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);

            /*repairTool.updatePlanPointRepairRecord(this, mPointRepair, new PointRepairCallBack(){
                @Override
                public void onUpdatePointRepair(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUpdatePointRepair(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        EventBus.getDefault().post(new PointRepairEvent(PointRepairEvent.POINT_REPAIR_UPDATED, mPlanPoint));
                        showFinishedDialog(getString(R.string.repair_update_update_data_ok));
                    }
                }
            });*/
        }
    }

    private void showRemoveAlert() {
        String title = "删除登记";
        String content = "是否删除当前设备检修点数据?";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (isLocal){
                    removeLocalRouteRecord();
                    onRemoveFinished();
                }else {
                    removePlanPointRepair();
                }

            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void removePlanPointRepair() {
        if (mPointRepair != null) {
            String repair_id = mPointRepair.getTemp_id();
            String strUploading = getString(R.string.repair_update_deleting_data);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);

/*            repairTool.removePlanPointRepairRecord(this, repair_id, new PointRepairCallBack(){
                @Override
                public void onRemovePointRepair(boolean isSuccess, int errorCode, String errMsg) {
                    super.onRemovePointRepair(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        onRemoveFinished();
                    }
                }
            });*/
        }
    }

    private void removeLocalRouteRecord(){
        repairTool.deleteLocalRouteRecord(mPointRepair, mPicturesUpload);
    }

    private void onRemoveFinished(){
        menuUpload.setEnabled(false);
        menuRemove.setEnabled(false);
        String msg = PointRepairEvent.POINT_REPAIR_REMOVED;
        EventBus.getDefault().post(new PointRepairEvent(msg, mPlanPoint));
        String title = getResources().getString(R.string.repair_update_delete_data_ok);
        showFinishedDialog(title);
    }

    private void showFinishedDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message);
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
            if (!isUpdate) {
                Intent intent = new Intent();
                intent.setClass(UiRepairUpdateStep.this, HomeActivity.class);
                startActivity(intent);
            }
            UiRepairUpdateStep.this.finish();
        });
        builder.show();
    }

    private void showUploadAlertDialog() {
        String title = "上传数据";
        String content = "是否上传数据?";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                commitPlanPointRepair();
            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void commitPlanPointRepair() {
        if (mPointRepair != null && mPlanPoint != null) {
            String strUploading = getResources().getString(R.string.repair_update_updating_data);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);

            repairTool.uploadCommonDeviceRepairRecord(this, mPointRepair, mPicturesUpload, new PointRepairCallBack(){
                @Override
                public void onAddPointChildRepair(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddPointChildRepair(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        onUploadFinish();
                    }
                }
            });
        }
    }

    private void onUploadFinish(){
        menuRemove.setEnabled(false);
        menuUpload.setEnabled(false);
        removeLocalRouteRecord();
        mbNeedRemoveCache = true;
        String msg = PointRepairEvent.REPAIR_ROUTE_UPLOADED;
        EventBus.getDefault().post(new PointRepairEvent(msg, mPlanPoint));
        showUploadFinishedDialog();
    }

    private void showUploadFinishedDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.reported_clear_upload_ok);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                removeCacheFile();
                UiRepairUpdateStep.this.finish();
            }
        });
        builder.show();
    }

    private void removeCacheFile(){
        //删除临时文件
        if (mPicturesUpload != null && mPicturesUpload.size() > 0){
            for (TroublePictureBean pictureBean : mPicturesUpload){
                String file = pictureBean.getFilepath();
                com.mgq.base.utils.file.FileUtil.deleteFile(file);
            }
        }
        /*if (mAudiosUpload != null && mAudiosUpload.size() > 0){
            for (Record record: mAudiosUpload){
                String file = record.getPath();
                com.mgq.base.utils.file.FileUtil.deleteFile(file);
            }
        }*/
    }

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