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

import android.content.ActivityNotFoundException;
import android.content.Intent;
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.mapping.view.MapView;
import com.mgq.base.utils.progressdialog.ProgressManager;
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.adapter.BuildFileAdapte;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
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.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.latte_core.base.IPresenter;

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

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author YCHK
 */
public class UiRepairFound 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.text_x)
    EditText textX;
    @BindView(R.id.text_y)
    EditText textY;
    @BindView(R.id.tv_document_name)
    NoListView tvDocumentName;

    private RushRepairTool buildTool;

    private RushRepairBean mBuildManage;

    private BuildFileAdapte adapte;

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

    @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 (isValid()) {
                alertAddBuildManage();
            }
        }
        return super.onOptionsItemSelected(item);
    }

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

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

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            RushRepairBean buildManage = (RushRepairBean) bundle.getSerializable("rush_repair");
            if (buildManage != null) {
                mBuildManage = buildManage;
            }
        }

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

        buildTool = RushRepairTool.getInstance();

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

        initListener();
    }


    private void initListener() {

    }

    @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) {
            mBuildManage.setX(mLastLocation.getX());
            mBuildManage.setY(mLastLocation.getY());
        }

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

    private boolean isValid() {
        collectData();

        if (TextUtils.isEmpty(mBuildManage.getAddress())) {
            ToastUtil.showToast(this, "地址不能为空");
            textMyAddress.requestFocus();
            return false;
        }

        if (Double.isNaN(mBuildManage.getX()) || Double.isNaN(mBuildManage.getY())) {
            ToastUtil.showToast(this, "坐标不能为空");
            return false;
        }

        return true;
    }

    private void alertAddBuildManage() {
        String title = "上传数据";
        String content = "是否上传数据?";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title)
                .setMessage(content)
                .setPositiveButton(android.R.string.ok, (dialog, which) -> uploadBuildManageInfo())
                .setNegativeButton(android.R.string.cancel, null)
                .setCancelable(false)
                .create()
                .show();
    }

    private void uploadBuildManageInfo() {
        if (mBuildManage != null) {
            String strUploading = getString(R.string.rush_repair_uploading_info);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            buildTool.addJobManage(this, mBuildManage, 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);
            UiRepairFound.this.finish();
        });
    }

    public boolean checkHasData() {
        if (mPicturesUpload != null && mPicturesUpload.size() > 0) {
            return true;
        }

        return (mAudiosRecords != null && mAudiosRecords.size() > 0);
    }

    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_found;
    }

    @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
    protected void onDestroy() {
        super.onDestroy();
        BaseApp.cancelAllRequest(getClass().getName());

    }
}
