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

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.file.FileUtil;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.mgq.base.utils.string.StringUtil;
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.sketch.SketchTool;
import com.tofly.ghrq_route.module.sketch.controller.SketchCallback;
import com.tofly.ghrq_route.module.sketch.domain.MySketchEvent;
import com.tofly.ghrq_route.module.sketch.domain.SketchBean;
import com.tofly.ghrq_route.module.sketch.domain.SketchBean.SKETCH_TASK_STATUS;
import com.tofly.ghrq_route.common.util.EventBusUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;

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

/**
 * Created by Amu on 2017/4/11.
 */

@SuppressLint("NonConstantResourceId")
public class UiSketchUpload extends BaseUi {
    @BindView(R.id.text_map_scale)
    TextView textMapScale;
    @BindView(R.id.text_map_center)
    TextView textMapCenter;
    @BindView(R.id.text_sketch_time)
    TextView textSketchTime;
    @BindView(R.id.layout_sketch_time)
    LinearLayout layoutSketchTime;
    @BindView(R.id.text_sketch_status)
    TextView textSketchStatus;
    @BindView(R.id.layout_sketch_status)
    LinearLayout layoutSketchStatus;
    @BindView(R.id.edit_sketch_title)
    EditText editSketchTitle;
    @BindView(R.id.edit_sketch_note)
    EditText editSketchNote;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindArray(R.array.sketch_handle_state)
    String[] handleStates;

    private SketchTool sketchTool;

    private PhotoHelper photoHelper;

    private SketchBean mSketchBean = null;

/*    private Point mLocation = null;

    private String mAddress = null;*/

    private MenuItem menuSave, menuRemove, menuUpload;

    private boolean bRemoveCacheFile = true;

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

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

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

    private void initView() {

    }

    private void initData() {
        sketchTool = SketchTool.getInstance();

        PermissionHelper permissionHelper = new PermissionHelper(this);
        photoHelper = new PhotoHelper(this, permissionHelper);

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mSketchBean = (SketchBean) bundle.getSerializable(SketchBean.SKETCH_BEAN_KEY);
            setSketchView();
        }
    }

    private void setSketchView() {
        if (mSketchBean != null) {
            double scale = mSketchBean.getScale();
            textMapScale.setText(StringUtil.formatDigit(scale, 2));
            String strCenter = StringUtil.format("%.6f , %.6f", mSketchBean.getX(), mSketchBean.getY());
            textMapCenter.setText(strCenter);
            editSketchTitle.setText(mSketchBean.getCaption());
            editSketchNote.setText(mSketchBean.getContent());

            SKETCH_TASK_STATUS task_status = SKETCH_TASK_STATUS.Status(mSketchBean.getStatus());
            if (task_status != SKETCH_TASK_STATUS.SKETCH_TASK_UNEDIT) {
                bRemoveCacheFile = false;
            }
            if (task_status == SKETCH_TASK_STATUS.SKETCH_TASK_UNEDIT ||
                    task_status == SKETCH_TASK_STATUS.SKETCH_TASK_UNCOMMIT) {
                loadSavedSketchPictures();
            } else {
                editSketchNote.setEnabled(false);
                editSketchTitle.setEnabled(false);
                layoutSketchTime.setVisibility(View.VISIBLE);
                layoutSketchStatus.setVisibility(View.VISIBLE);
                getSketchDataFromServer();
            }
        }
    }

    private void loadSavedSketchPictures(){
        if (mSketchBean != null && mSketchBean.getFilepath() != null){
            View view = photoHelper.getPhotoViewFromPath(mSketchBean.getFilepath());
            if (view != null) {
                photoGallery.addView(view);
            }
        }
    }

    private void getSketchDataFromServer() {
        String sketch_id = mSketchBean.getId();
        sketchTool.getSketchDataFromServer(this, sketch_id, new SketchCallback(){
            @Override
            public void onGetSketchData(boolean isSuccess, int errorCode, String errMsg, SketchBean sketchBean) {
                super.onGetSketchData(isSuccess, errorCode, errMsg, sketchBean);
                if (isSuccess && sketchBean != null) {
                    mSketchBean = sketchBean;
                    loadSketchPictures();
                }else {
                    loadSavedSketchPictures();
                }
                textSketchTime.setText(mSketchBean.getCreatedate());
                textSketchStatus.setText(handleStates[mSketchBean.getStatus()]);
            }
        });
    }

    private void loadSketchPictures() {
        if (mSketchBean != null && mSketchBean.getFileid() != null){
            String fileurl = mSketchBean.getFileid();
            String realurl = NetRequestURL.newApi_dyrq.getFormattedPicture(fileurl);
            View view = photoHelper.getPhotoViewFromUrl(realurl);
            if (view != null) {
                photoGallery.addView(view);
            }
        }
    }

    private void initListener() {
        setOnNavigationClickListener(v -> showExitAlertDialog());
    }

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

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (mSketchBean != null) {
            SKETCH_TASK_STATUS task_status = SKETCH_TASK_STATUS.Status(mSketchBean.getStatus());
            if (task_status == SKETCH_TASK_STATUS.SKETCH_TASK_UNEDIT) {
                menuRemove.setVisible(false);
            }else if (task_status != SKETCH_TASK_STATUS.SKETCH_TASK_UNCOMMIT) {
                menuSave.setVisible(false);
                menuUpload.setVisible(false);
                menuRemove.setVisible(false);
            }
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:
                if (isValid()) {
                    saveSketchAlert();
                }
                break;
            case R.id.action_upload:
                if (isValid()) {
                    uploadSketchAlert();
                }
                break;
            case R.id.action_remove:
                deleteSketchAlert();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


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

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

    public boolean checkHasData(){
        if (mSketchBean == null) {
            return false;
        }

        if (mSketchBean.getStatus() == SKETCH_TASK_STATUS.SKETCH_TASK_COMMITED.getStatus()
                || mSketchBean.getStatus() == SKETCH_TASK_STATUS.SKETCH_TASK_HANDLED.getStatus()) {
            return false;
        }

        if (mSketchBean.getFilepath() != null && FileUtil.isFileExist(mSketchBean.getFilepath()))
            return true;

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

        input = editSketchNote.getText().toString();
        return !input.isEmpty();
    }

    private boolean isValid() {
        boolean isPictureValid = false;

        String title = editSketchTitle.getText().toString();
        if (title.isEmpty()){
            toast("请输入疑问标识的标题");
            editSketchTitle.requestFocus();
            return false;
        }

        String content = editSketchNote.getText().toString();
        if (content.isEmpty()){
            toast("请输入疑问标识的详细描述");
            editSketchNote.requestFocus();
            return false;
        }

        if (mSketchBean != null && mSketchBean.getFilepath() != null) {
            if (FileUtil.isFileExist(mSketchBean.getFilepath())) {
                isPictureValid = true;
            }
        }

        if (!isPictureValid) {
            toast("草图的图片文件不存在");
            return false;
        }

        mSketchBean.setCaption(title);
        mSketchBean.setContent(content);

        return true;
    }

    private void saveSketchAlert() {
        String title = getString(R.string.sketch_list_title);
        String content = "是否保存疑问标识?";
        showAlertDialog(title, content, (dialog, which) -> saveSketchData());
    }

    private void saveSketchData() {
        if (mSketchBean != null) {
            sketchTool.saveSketchDataNoCommit(mSketchBean);
            int ACTION_SAVE = 0;
            showUploadFinishedDialog(true, ACTION_SAVE);
        }
    }

    private void uploadSketchAlert() {
        String title = getString(R.string.sketch_list_title);
        String content = "是否上传疑问标识?";
        showAlertDialog(title, content, (dialog, which) -> uploadSketchData());
    }

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

        sketchTool.uploadSketchData(this, mSketchBean, new SketchCallback() {
            @Override
            public void onUploadSketchData(boolean isSuccess, int errorCode, String errMsg) {
                super.onUploadSketchData(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                showUploadFinishedDialog(isSuccess, ACTION_UPLOAD);
            }
        });
    }

    private void deleteSketchAlert() {
        String title = getString(R.string.sketch_list_title);
        String content = "是否删除疑问标识?";
        showAlertDialog(title, content, (dialog, which) -> deleteSketchData());
    }

    private void deleteSketchData() {
        if (mSketchBean != null) {
            sketchTool.deleteSketchData(mSketchBean);
            showUploadFinishedDialog(true, ACTION_REMOVE);
        }
    }

    private static final int ACTION_UPLOAD = 1;
    private static final int ACTION_REMOVE = 2;
    private void showUploadFinishedDialog(boolean isSuccess, int action) {
        bRemoveCacheFile = false;
        EventBusUtil.postEvent(new MySketchEvent(MySketchEvent.MY_SKETCH_LIST_NEED_REFRESH));

        String title = getString(R.string.sketch_list_title);
        String content = getString(R.string.sketch_sketch_save_ok);
        if (action == ACTION_UPLOAD) {
            content = isSuccess ? getString(R.string.sketch_sketch_upload_ok)
             : getString(R.string.sketch_sketch_upload_save) ;
        } else if (action == ACTION_REMOVE) {
            content = getString(R.string.sketch_sketch_delete_ok);
        }
        showAlertWithConfirmButton(title, content, false,
                (dialog, which) -> this.forward(UiSketchList.class));
    }

    private void removeCacheFile() {
        if (!bRemoveCacheFile)
            return;

        //删除临时文件
        if (mSketchBean != null && mSketchBean.getFilepath() != null) {
            String file = mSketchBean.getFilepath();
            FileUtil.deleteFile(file);
        }
    }


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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApp.cancelAllRequest(getClass().getName());
    }
}
