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.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.esri.arcgisruntime.mapping.view.MapView;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.mgq.base.utils.string.StringUtil;
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.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.common.util.SnackBarUtil;
import com.tofly.ghrq_route.common.util.dialog.DialogUtil;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.uploadPhoto.UploadPhotoTool;
import com.tofly.ghrq_route.module.uploadPhoto.controller.UploadPhotoCallBack;
import com.tofly.ghrq_route.module.uploadPhoto.domain.UploadPhotoBean;
import com.tofly.ghrq_route.module.uploadPhoto.domain.UploadPhotoEvent;
import com.tofly.latte_core.base.IPresenter;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;

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

public class UiPhotoReportNext extends BaseMapFileActivity {
    @BindView(R.id.layout_main_root)
    CoordinatorLayout layoutMainRoot;
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.text_photo_addr)
    TextView textMyAddress;
    @BindView(R.id.dangerreport1_gallery)
    LinearLayout layoutGallery;
    @BindView(R.id.layout_addpic_area)
    LinearLayout layoutAddPicArea;
    @BindView(R.id.dangerreport1_addaudio)
    MyAudioRecordButton btnAddAudio;
    @BindView(R.id.audio_record_gallery)
    LinearLayout layoutAudioGallery;
    @BindView(R.id.dangerreport1_addpic)
    Button btnAddPhoto;

    private UploadPhotoTool uploadPhotoTool;

    private UploadPhotoBean mPhotoUpload = new UploadPhotoBean();

    private MenuItem menuCommit;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_reported_detail, menu);
        menuCommit = menu.findItem(R.id.action_commit);
        menu.findItem(R.id.action_clear).setVisible(false);
        return super.onCreateOptionsMenu(menu);
    }

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

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

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

        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mPhotoUpload = (UploadPhotoBean) bundle.getSerializable(UploadPhotoBean.UPLOAD_PHOTO_BEAN_KEY);
        }

        uploadPhotoTool = UploadPhotoTool.getInstance();

        textMyAddress.setText("正在定位...");

        initListener();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {

    }

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

    private void collectData() {
        if (mLastLocation != null) {
            mPhotoUpload.setLng(StringUtil.formatDigit6(mLastLocation.getX()));
            mPhotoUpload.setLat(StringUtil.formatDigit6(mLastLocation.getY()));
            mPhotoUpload.setGpsFlag(mGpsFlag);
        }

        if (mAddress != null) {
            mPhotoUpload.setAddr(mAddress);
        }
    }

    private boolean isValid() {
        boolean isPhotoTypeValid = false;
        boolean isPictureValid = false;
        boolean isTroubleValid = false;

        collectData();

        if (mPhotoUpload != null) {
            if (mPhotoUpload.getLng() != null && mPhotoUpload.getLat() != null) {
                isTroubleValid = true;
            }
        }

        if (!isTroubleValid) {
            ToastUtil.showToast(this,"当前位置不可用");
            return false;
        }

        if (mPhotoUpload.getPicTypeId() != null && !mPhotoUpload.getPicTypeId().isEmpty()) {
            isPhotoTypeValid = true;
        }

        if (!isPhotoTypeValid) {
            String strWarn = getString(R.string.photoreport_phototype_empty_err);
            SnackBarUtil.showSnack(layoutMainRoot, strWarn);
            return false;
        }

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

        if (!isPictureValid) {
            String strWarn = getString(R.string.photoreport_photo_empty_err);
            SnackBarUtil.showSnack(layoutMainRoot, strWarn);
            return false;
        }
        return true;
    }

    private void uploadPhotoAlert() {
        String title = "上传数据";
        String content = "是否上传数据?";
        DialogUtil.showAlertWithConfirmCancelButton(this, title, content, true,
                (dialog, which) -> uploadPhotoReport());
    }

    private void uploadPhotoReport() {
        String strUploading = getString(R.string.photoreport_uploading_info);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(mAudiosRecords);
        uploadPhotoTool.uploadNewPhotoNoSave(this, mPhotoUpload, mPicturesUpload, audioBeans, new UploadPhotoCallBack(){
            @Override
            public void onAddUploadPhotoInfo(boolean isSuccess, int errorCode, String errMsg, String photoId) {
                super.onAddUploadPhotoInfo(isSuccess, errorCode, errMsg, photoId);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    onUploadFinish();
                }
            }
        });
    }

    private void onUploadFinish(){
        menuCommit.setEnabled(false);
        bRemoveCacheFile = false;
        String msg = UploadPhotoEvent.UPLOAD_PHOTO_UPLOADED;
        EventBus.getDefault().post(new UploadPhotoEvent(msg));
        showUploadFinishedDialog();
    }

    private void showUploadFinishedDialog() {
        int message = R.string.photoreport_upload_ok;
        DialogUtil.showAlertWithConfirmButton(this, R.string.photoreport_title, message, false, (dialogInterface, i) -> {
                    UiPhotoReport.uiPhotoReport.finish();
                    this.finish();
                });
    }

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

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

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

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

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

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

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

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

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

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

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

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

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