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

import androidx.appcompat.app.AlertDialog;

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.dialog.DialogUtil;
import com.tofly.ghrq_route.module.buildManage.domain.BuildFileBean;
import com.tofly.ghrq_route.module.rushrepair.RushRepairTool;
import com.tofly.ghrq_route.module.rushrepair.controller.RushRepairCallback;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairBean;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairProcessBean;
import com.tofly.ghrq_route.common.util.ArcgisUtils.SizeMarkerSymbol;
import com.tofly.ghrq_route.common.util.NoListView;
import com.tofly.ghrq_route.common.util.file.FileUtil;
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 UiRepairProcess extends BaseMapFileActivity {
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.my_location)
    ImageView imvMyLocation;
    @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 RushRepairTool buildTool;

    private RushRepairBean repairBean;

    private RushRepairProcessBean data;

    private MarkerSymbol repairMarker;

    @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, UiRepairProcessDetail.class);
            intent.putExtra("rush_repair", repairBean);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

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

        //配置定位服务
        textMyAddress.setText("正在定位...");
    }

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

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

        data = new RushRepairProcessBean();
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            RushRepairBean repairBean1 = (RushRepairBean) bundle.getSerializable("rush_repair");
            if (repairBean1 != null) {
                repairBean = repairBean1;

                if (!TextUtils.isEmpty(repairBean.getId())) {
                    String id = UUID.randomUUID().toString();
                    data.setId(id);
                    data.setWorkOrderId(repairBean.getId());
                }
            }
        }

        buildTool = RushRepairTool.getInstance();

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

        initListener();
    }


    @SuppressLint("ClickableViewAccessibility")
    private 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 void collectData() {
        if (mLastLocation != null) {
            data.setX(mLastLocation.getX());
            data.setY(mLastLocation.getY());
        }
    }

    private boolean isValid() {
        boolean isAddressValid = true;

        if (TextUtils.isEmpty(textMyAddress.getText()) || textMyAddress.getText().toString().equals("正在定位...")) {
            showToast("当前位置不可用");
            isAddressValid = false;
        }

        if (TextUtils.isEmpty(tvDescribe.getText())) {
            showToast("填写描述信息");
            tvDescribe.requestFocus();
            isAddressValid = false;
        } else {
            data.setDescription(tvDescribe.getText().toString());
        }

        return isAddressValid;
    }

    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.rush_repair_process_uploading_info);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            buildTool.addRushProcessManage(this, data, mPicturesUpload, mAudiosRecords, buildFileBeanList, new RushRepairCallback() {
                @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);
            UiRepairProcess.this.finish();
        });
    }

    private void showExitAlertDialog() {
        boolean hasInput = checkHasData();
        if (hasInput) {
            String title = "退出编辑";
            String content = "退出编辑，当前输入将会丢失。是否继续?";
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(title)
                    .setMessage(content)
                    .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                        removeCacheFile();
                        finish();
                    })
                    .setNegativeButton(android.R.string.cancel, null)
                    .setCancelable(false)
                    .create()
                    .show();
        } 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_repair_process;
    }

    @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() {
        super.onBaseMapLoaded();

        initRenderSymbol();
    }

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