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

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.MarkerSymbol;
import com.mgq.base.utils.progressdialog.ProgressManager;
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.adapter.BuildFileAdapte;
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.NoListView;
import com.tofly.ghrq_route.common.util.dialog.DialogUtil;
import com.tofly.ghrq_route.common.util.file.FileUtil;
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.BuildFileBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildProcessManageBean;
import com.tofly.latte_core.base.IPresenter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author YCHK
 * 工地过程管理
 */
public class UiBuildProcessManage extends BaseMapFileActivity {
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.text_photo_addr)
    EditText textMyAddress;
    @BindView(R.id.build_found_addpic)
    Button btnAddPicture;
    @BindView(R.id.build_found_photo_gallery)
    LinearLayout photoGallery;
    @BindView(R.id.build_found_addaudio)
    MyAudioRecordButton btnAddAudio;
    @BindView(R.id.build_found_audio_gallery)
    LinearLayout audioGallery;
    @BindView(R.id.tv_describe)
    EditText tvDescribe;
    @BindView(R.id.tv_document_name)
    NoListView tvDocumentName;

    private BuildFileAdapte adapte;

    private List<BuildFileBean> buildFileBeanList = new ArrayList<>();

    private BuildTool buildTool;

    private BuildManageBean mBuildManage;

    private BuildProcessManageBean data;

    private MarkerSymbol buildMarker;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_build_process, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_commit) {
            if (isValid()) {
                alertAddBuildManage();
            }
        } else if (item.getItemId() == R.id.action_detail) {
            Intent intent = new Intent(this, UiBuildProcessDeatil.class);
            intent.putExtra("build_manage", mBuildManage);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void initView() {
        /*检测本地用户地图配置信息是否存在*/
        super.initView();

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

    /**
     * 添加已知经纬度的图标
     */
    private void initRenderSymbol() {
        if (mBuildManage.getX() != 0.0 && mBuildManage.getX() != 0.0) {
            Drawable drawable = getResources().getDrawable(R.drawable.buildsite);
            buildMarker = SizeMarkerSymbol.sizeSymbol((BitmapDrawable) drawable, 18, 18);
            Graphic graphic = new Graphic(new Point(mBuildManage.getX(), mBuildManage.getY()), buildMarker);
            GraphicsOverlay graphicsOverlay = new GraphicsOverlay();
            graphicsOverlay.getGraphics().add(graphic);
            mapView.getGraphicsOverlays().add(graphicsOverlay);
        }
    }

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

        data = new BuildProcessManageBean();
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            BuildManageBean buildManage = (BuildManageBean) bundle.getSerializable("build_manage");
            if (buildManage != null) {
                mBuildManage = buildManage;
                if (!TextUtils.isEmpty(mBuildManage.getId())) {
                    String id = UUID.randomUUID().toString();
                    data.setId(id);
                    data.setWorkOrderId(mBuildManage.getId());
                }
            }
        }

        buildTool = BuildTool.getInstance();

        adapte = new BuildFileAdapte(this, buildFileBeanList);
        tvDocumentName.setAdapter(adapte);

        initListener();
    }

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

    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == -1) {
            Uri uri = data.getData();
            assert uri != null;
            String filePath = FileUtil.getPath(this, uri);
            assert filePath != null;
            File file = new File(filePath);
            BuildFileBean fileBean = new BuildFileBean();
            fileBean.setFileName(file.getName());
            fileBean.setFilePath(file.getPath());
            buildFileBeanList.add(fileBean);
            adapte.notifyDataSetChanged();
        }
    }

    private boolean isValid() {
        if (mLastLocation == null || Double.isNaN(mLastLocation.getX()) || Double.isNaN(mLastLocation.getY())) {
            showToast("当前位置不可用");
            return false;
        }

        if (TextUtils.isEmpty(tvDescribe.getText())) {
            tvDescribe.requestFocus();
            showToast("请填写描述信息");
            return false;
        }

        return true;
    }

    private void collectData() {
        if (mLastLocation != null) {
            data.setX(mLastLocation.getX());
            data.setY(mLastLocation.getY());
        }

        data.setDescription(tvDescribe.getText().toString());
    }

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

    private void uploadBuildManageInfo() {
        if (data != null) {
            collectData();
            String strUploading = getString(R.string.build_process_uploading_info);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            buildTool.addBuildProcessManage(this, data, mPicturesUpload, mAudiosRecords, buildFileBeanList, new BuildManageCallback() {
                @Override
                public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddBuildManage(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    showUploadFinishedDialog(isSuccess);
                }
            });
        }
    }

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

    private void showExitAlertDialog() {
        boolean hasInput = checkHasData();
        if (hasInput) {
            String title = "退出编辑";
            String content = "退出编辑，当前输入将会丢失。是否继续?";
            DialogUtil.showAlertWithConfirmCancelButton(this, title, content, true, (dialog, which) -> {
                removeCacheFile();
                finish();
            });
        } else {
            finish();
        }
    }

    @OnClick({R.id.build_found_document})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.build_found_document:
                showFileChooser();
                break;
        }
    }

    /**
     * 打开文件夹
     */
    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "文件路径"), 1);
        } catch (ActivityNotFoundException ex) {
            ex.printStackTrace();
        }
    }

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

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

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

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

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

    @Override
    public void onBaseMapLoaded() {
        if (mBuildManage != null) {
            initRenderSymbol();
        }
    }

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

