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

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.MarkerSymbol;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseMapFileActivity;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.common.util.ArcgisUtils.SizeMarkerSymbol;
import com.tofly.ghrq_route.common.util.EventBusUtil;
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.dialog.DialogUtil;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.module.job.JobTool;
import com.tofly.ghrq_route.module.job.controller.JobCallBack;
import com.tofly.ghrq_route.module.job.domain.JobBean;
import com.tofly.ghrq_route.module.job.domain.JobBean.JOB_TASK_STATUS;
import com.tofly.ghrq_route.module.job.domain.MyJobEvent;
import com.tofly.ghrq_route.module.notifyManage.NotifyManageBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.latte_core.base.IPresenter;

import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;

public class UiJobDetail extends BaseMapFileActivity {
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.text_job_title)
    TextView textJobTitle;
    @BindView(R.id.text_job_create_time)
    TextView textJobCreateTime;
    @BindView(R.id.layout_finish_time)
    LinearLayout layoutFinishTime;
    @BindView(R.id.text_job_finish_time)
    TextView textJobFinishTIme;
    @BindView(R.id.text_job_content)
    TextView textJobContent;
    @BindView(R.id.edit_job_note)
    EditText editJobNote;
    @BindView(R.id.text_add_photo)
    TextView textAddPhoto;
    @BindView(R.id.btn_add_photo)
    Button btnAddPhoto;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindView(R.id.layout_addpic_area)
    LinearLayout layoutAddPicArea;

    private JobBean mJobBean;

    private int gpsFlag = 0; //0:自动定位 1：手动定位

    private JobTool jobTool = JobTool.getInstance();

    private MenuItem menuSave, menuUpload;

    private GraphicsOverlay jobGraphicOverlay;

    private Graphic jobGraphic;

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

        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            if (bundle.containsKey(JobBean.JOB_BEAN_KEY)) {
                mJobBean = (JobBean) bundle.getSerializable(JobBean.JOB_BEAN_KEY);

                if (mJobBean != null) {
                    textJobTitle.setText(mJobBean.getCaption());
                    textJobContent.setText(mJobBean.getContent());
                    String create_time = mJobBean.getDispatchDate();
                    if (create_time != null) {
                        textJobCreateTime.setText(create_time);
                    }

                    if (mJobBean.getTaskStatus() != JOB_TASK_STATUS.JOB_TASK_UNHANDLED.getStatus()) {
                        bRemoveCacheFile = false;
                        setJobView();
                    }

                    NotifyManageBean msgBean = jobTool.getNotifyMsgBean(mJobBean.getId());
                    if (msgBean != null) {
                        jobTool.setMsgBeanRead(msgBean);
                        if (bundle.containsKey(JobBean.JOB_POSITION_KEY)) {
                            int position = (int) bundle.getSerializable(JobBean.JOB_POSITION_KEY);
                            EventBusUtil.postEvent(new MyJobEvent(MyJobEvent.MY_JOB_LIST_JOB_HAS_READ, position));
                        }
                    }
                }
            }
        }
    }

    private void setJobView() {
        if (mJobBean != null) {
            if (mJobBean.getTaskStatus() == JOB_TASK_STATUS.JOB_TASK_COMMITED.getStatus()) {
                editJobNote.setEnabled(false);
                textAddPhoto.setText(getString(R.string.job_job_upload_pic));
                btnAddPhoto.setVisibility(View.GONE);
                layoutFinishTime.setVisibility(View.VISIBLE);
                getJobDataFromServer();
            }else if (mJobBean.getTaskStatus() == JOB_TASK_STATUS.JOB_TASK_UNCOMMIT.getStatus()) {
                editJobNote.setText(mJobBean.getHandleRecord());
                loadSavedJobPictures();
            }
        }
    }

    private void loadSavedJobPictures(){
        String job_id = mJobBean.getId();
        List<TroublePictureBean> pictures = jobTool.getLocalJobPictures(job_id);
        mPicturesUpload  = pictures;
        for (TroublePictureBean picture : pictures){
            if (picture != null){
                String filepath = picture.getFilepath();
                View view;
                if (FileUtil.isFileTypeVideo(filepath)) {
                    view = getVideoViewFromPath(picture);
                }else {
                    view = getPhotoViewFromPath(picture);
                }
                if (view != null) {
                    photoGallery.addView(view);
                }
            }
        }
    }

    private void getJobDataFromServer() {
        String job_id = mJobBean.getId();
        jobTool.getJobDataFromServer(this, job_id, new JobCallBack(){
            @Override
            public void onGetJobData(boolean isSuccess, int errorCode, String errMsg, JobBean jobBean) {
                super.onGetJobData(isSuccess, errorCode, errMsg, jobBean);
                if (isSuccess && jobBean != null) {
                    mJobBean = jobBean;
                    loadJobPictures();
                }else {
                    loadSavedJobPictures();
                }
                editJobNote.setText(mJobBean.getHandleRecord());
                textJobFinishTIme.setText(mJobBean.getFinishDate());
            }
        });
    }

    private void loadJobPictures() {
        String job_id = mJobBean.getId();
        List<TroublePictureBean> pictures = jobTool.getLocalJobPictures(job_id);
        mPicturesUpload  = pictures;
        for (TroublePictureBean picture : pictures){
            if (picture != null){
                String fileurl = picture.getFileurl();
                String filenote = picture.getFilenote();
                String realurl = NetRequestURL.newApi_dyrq.getFormattedPicture(fileurl);
                String fileName = com.mgq.base.utils.file.FileUtil.getFileName(fileurl);
                if (FileUtil.isFileTypeVideo(fileurl)){
                    fileViewUtil.getVideoFileView(job_id, realurl, fileName, filenote, (isSuccess, view) -> {
                        if (isSuccess && view != null) {
                            photoGallery.addView(view);
                        }
                    });
                }else {
                    View view = photoHelper.getPhotoViewFromUrl(realurl);
                    if (view != null) {
                        photoGallery.addView(view);
                    }
                }
            }
        }

    }

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

        initListener();
    }

    private void initListener() {
        if (mapView != null) {
            mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mapView) {
                @Override
                public boolean onSingleTapConfirmed(MotionEvent event) {
                    onMapTaped(event.getX(), event.getY());
                    return true;
                }
            });
        }
    }

    private void onMapTaped(float x, float y) {
        if (jobGraphicOverlay != null && jobGraphic != null) {
            android.graphics.Point screenPoint =
                    new android.graphics.Point(Math.round(x), Math.round(y));
            ListenableFuture<IdentifyGraphicsOverlayResult> future =
                    mapView.identifyGraphicsOverlayAsync(jobGraphicOverlay, screenPoint, 10, false, 10);
            future.addDoneListener(() -> {
                try {
                    IdentifyGraphicsOverlayResult result = future.get();
                    List<Graphic> graphics = result.getGraphics();
                    if (graphics != null && graphics.indexOf(jobGraphic) != -1) {
                        Point geometry = (Point) jobGraphic.getGeometry();
                        //Point toPoint = new Point(geometry.getX(), geometry.getY(), mapView.getSpatialReference());
                        showNavigation(geometry);
                    }
                } catch (ExecutionException | InterruptedException ex) {
                    ex.printStackTrace();
                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_danger_report_next, menu);
        menuSave = menu.findItem(R.id.action_save);
        menuUpload = menu.findItem(R.id.action_upload);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (mJobBean != null) {
            if (mJobBean.getTaskStatus() == JOB_TASK_STATUS.JOB_TASK_COMMITED.getStatus()) {
                menuSave.setVisible(false);
                menuUpload.setVisible(false);
            }
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save: {
                saveJob();
                break;
            }
            case R.id.action_upload: {
                uploadJob();
                break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        showExitAlertDialog();
    }

    public boolean checkHasData(){
        if (mJobBean != null) {
            if (mJobBean.getTaskStatus() == JOB_TASK_STATUS.JOB_TASK_COMMITED.getStatus()) {
                return false;
            }
        }

        String input = editJobNote.getText().toString();
        if (!input.isEmpty()) {
            return true;
        }

        return (mPicturesUpload != null && mPicturesUpload.size() > 0);
    }

    private void showExitAlertDialog(){
        boolean hasInput = checkHasData();
        if (hasInput){
            String title = "退出编辑";
            String content = "是否退出当前编辑?";
            DialogUtil.showAlertWithConfirmCancelButton(this, title, content, true, (dialog, which) -> {
                removeCacheFile();
                finish();
            });
        }else {
            finish();
        }
    }

    private void renderJobOnMap() {
        if (mJobBean != null && mapView != null) {
            if (!Double.isNaN(mJobBean.getX()) && !Double.isNaN(mJobBean.getY()) &&
            mJobBean.getX() != 0 && mJobBean.getY() != 0) {
                BitmapDrawable unsignedLoc = (BitmapDrawable) getResources().getDrawable(R.mipmap.danger_location);
                MarkerSymbol symbol = SizeMarkerSymbol.sizeSymbol(unsignedLoc, 18, 18);
                Point point = new Point(mJobBean.getX(), mJobBean.getY(), mapView.getSpatialReference());
                jobGraphic = new Graphic(point, symbol);
                jobGraphicOverlay = new GraphicsOverlay();
                jobGraphicOverlay.getGraphics().add(jobGraphic);
                mapView.getGraphicsOverlays().add(jobGraphicOverlay);
                ListenableFuture<Boolean> future = mapView.setViewpointScaleAsync(5000);
                future.addDoneListener(() -> {
                    try {
                        Boolean isSuccess = future.get();
                        if (isSuccess) {
                            mapView.setViewpointCenterAsync(point);
                        }
                    } catch (ExecutionException | InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    }

    private boolean isValid() {
        boolean isPictureValid = false;
        String input = editJobNote.getText().toString();
        if (input.isEmpty()) {
            ToastUtil.showToast(this, "请输入工单回报!");
            return false;
        }

        if (mPicturesUpload != null && mPicturesUpload.size() > 0) {
            isPictureValid = true;
        }

        if (!isPictureValid) {
            ToastUtil.showToast(this, "请添加工单图片!");
            return false;
        }
        mJobBean.setHandleRecord(input);
        mJobBean.setFinishDate(DateUtils.getDate());
        return true;
    }

    private void saveJob() {
        if (isValid()) {
            String title = "工单保存";
            String content = "是否保存当前工单信息?";
            DialogUtil.showAlertWithConfirmCancelButton(this, title, content, true, (dialog, which) -> saveJobData());
        }
    }

    private void saveJobData() {
        if (mJobBean != null) {
            jobTool.saveJobDataNoCommit(mJobBean, mPicturesUpload);
            int ACTION_SAVE = 0;
            showUploadFinishedDialog(true, 0, ACTION_SAVE);
        }
    }

    private void uploadJob() {
        if (isValid()) {
            String title = "工单上传";
            String content = "是否上传当前工单?";
            DialogUtil.showAlertWithConfirmCancelButton(this, title, content, true, (dialog, which) -> uploadJobData());
        }
    }

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

            jobTool.uploadJobData(this, mJobBean, mPicturesUpload, new JobCallBack() {
                        @Override
                        public void onUploadJobData(boolean isSuccess, int errorCode, String errMsg) {
                            super.onUploadJobData(isSuccess, errorCode, errMsg);
                            ProgressManager.getInstance().cancelProgress();
                            showUploadFinishedDialog(isSuccess, errorCode, ACTION_UPLOAD);
                        }
                    }
            );
        }
    }

    private static int ACTION_UPLOAD = 1;
    private void showUploadFinishedDialog(boolean isSuccess, int error_code, final int action) {
        bRemoveCacheFile = false;
        EventBusUtil.postEvent(new MyJobEvent(MyJobEvent.MY_JOB_LIST_NEED_REFRESH));

        String title = getString(R.string.job_list_title);
        String content = getString(R.string.job_job_save_ok);
        if (action == ACTION_UPLOAD) {
            content = isSuccess ? getString(R.string.job_job_upload_ok) :
                    getString(R.string.job_job_upload_save);
            if (error_code == URLResponseCode.ErrorCode.ALREADY_EXISTS) {
                content = getString(R.string.job_job_finished_no_commit);
            }
        }
        DialogUtil.showAlertWithConfirmButton(this, title, content, false, (dialog, which) -> this.finish());
    }


    @Override
    protected IPresenter createPresenter() {
        return null;
    }

    @Override
    public int setLayout() {
        return R.layout.ui_job_detail;
    }

    @Override
    public boolean enableLoadMap() {
        return true;
    }

    @Override
    public boolean enableMoveMapListener() {
        return false;
    }

    @Override
    public boolean enableArcgisLocating() {
        return false;
    }

    @Override
    public boolean enableAmapLocationListener() {
        return true;
    }

    @Override
    public boolean enableMapMoveToLocation() {
        return false;
    }

    @Override
    public TextView getTextAddrView() {
        return null;
    }

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

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

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

    @Override
    public LocationUtil_xu.CoordinateClass getLocation() {
        return new LocationUtil_xu.CoordinateClass(mProjLoc.getX(), mProjLoc.getY(), mAddress);
    }

    @Override
    public void onBaseMapLoaded() {
        renderJobOnMap();
    }

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

        BaseApp.cancelAllRequest(getClass().getName());
    }
}
