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.appcompat.widget.Toolbar;

import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.view.MapView;
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.ui.BaseMapFileActivity;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.common.util.dialog.DialogUtil;
import com.tofly.ghrq_route.module.buildManage.BuildTool;
import com.tofly.ghrq_route.module.buildManage.controller.BuildManageCallback;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildReportBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildReportEvent;
import com.tofly.latte_core.base.IPresenter;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindArray;
import butterknife.BindView;

/**
 * Created by Amu on 2017/5/26.
 */

public class UiBuildReportEnroll extends BaseMapFileActivity {
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.text_addr)
    TextView textMyAddr;
    @BindView(R.id.btn_add_photo)
    Button btnAddPhoto;
    @BindView(R.id.build_photo_area)
    LinearLayout layoutPhotoArea;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindView(R.id.audioRecordBtn_addaudio)
    MyAudioRecordButton audioRecordBtn;
    @BindView(R.id.audio_record_gallery)
    LinearLayout audioGallery;
    @BindView(R.id.layout_addaudio_area)
    LinearLayout layoutAddaudioArea;
    @BindArray(R.array.handle_project_state)
    String[] buildStates;

    private ArcGISMap arcMap = null;

    private BuildTool buildTool;

    private BuildManageBean mBuildManage = null;

    private BuildReportBean mReportUpload = null;

    private int mReportState = 0;

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

        textMyAddr.setText("正在定位...");
    }

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

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            BuildReportBean buildReport = (BuildReportBean) bundle.getSerializable("report_upload");
            BuildManageBean buildManage = (BuildManageBean) bundle.getSerializable("build_manage");
            if (buildReport != null) {
                mReportUpload = buildReport;
                mReportState = mReportUpload.getReport_state();
            }

            if (buildManage != null)
                mBuildManage = buildManage;
        }

        buildTool = BuildTool.getInstance();

        initListener();
    }

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

    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_reported_detail, menu);
        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 (checkValid()) {
                showCommitAlert();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private void showCommitAlert() {
        String title = "提交回报";
        String content = "是否提交当前回报记录?";
        DialogUtil.showAlertWithConfirmCancelButton(this, title, content,
                true, (dialog, which) -> uploadBuildReport());
    }

    private boolean checkValid() {
        boolean isTroubleValid = false;
        boolean isPictureValid = false;
        if (mLastLocation != null) {
            if (!Double.isNaN(mLastLocation.getX()) && !Double.isNaN(mLastLocation.getY()) && mAddress != null) {
                isTroubleValid = true;
            }
        }

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

        if (!isTroubleValid) {
            showToast("未获取到当前的位置信息，请稍后重试");
            return false;
        }

        if (!isPictureValid) {
            showToast("请选择图片");
            return false;
        }

        return true;
    }

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

        if (mAddress != null) {
            mReportUpload.setAddress(mAddress);
        }
    }

    private void uploadBuildReport() {
        if (mReportUpload != null) {
            collectData();
            String strUploading = getString(R.string.build_report_uploading);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            buildTool.addBuildReport(this, mReportUpload, mPicturesUpload, mAudiosRecords, new BuildManageCallback(){
                @Override
                public void onUploadBuildReport(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUploadBuildReport(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (mBuildManage != null && mReportUpload.getReport_state() >= 1) {
                        //buildTool.saveBuildManageState(mBuildManage, BuildManageBean.BUILD_STATE_OVER);
                        buildTool.deleteLocalBuildManage(mBuildManage);
                    }
                    String message = isSuccess ? BuildReportEvent.BUILD_REPORT_UPLOADED : BuildReportEvent.BUILD_REPORT_SAVED;
                    EventBus.getDefault().post(new BuildReportEvent(message, mReportState));
                    showUploadFinishedDialog(isSuccess);
                }
            });
        }
    }


    private void showUploadFinishedDialog(boolean isSuccess) {
        String title = getTitle().toString();
        String content = isSuccess ?
                getString(R.string.build_report_upload_ok) : getString(R.string.upload_fail_saved1);
        DialogUtil.showAlertWithConfirmButton(this, title, content, false, (dialog, which) -> {
            finish();
        });
    }

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

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

    @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 textMyAddr;
    }

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

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

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

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