package com.casic.dcms.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.amap.api.location.AMapLocation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.casic.dcms.R;
import com.casic.dcms.base.BaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.mvp.presenter.CleanToiletPresenterImpl;
import com.casic.dcms.mvp.presenter.UploadImagePresenterImpl;
import com.casic.dcms.mvp.view.IPublicToiletView;
import com.casic.dcms.mvp.view.IUploadFileView;
import com.casic.dcms.utils.ColorHelper;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.FileUtils;
import com.casic.dcms.utils.GlideLoadEngine;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.TimeOrDateUtil;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.utils.callback.ILocationListener;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.BasemapStyle;
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.PictureMarkerSymbol;
import com.esri.arcgisruntime.util.ListenableList;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

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

import butterknife.BindView;
import butterknife.OnClick;
import cn.bertsir.zbar.Qr.ScanResult;
import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.QrManager;
import cn.bertsir.zbar.view.ScanLineView;

public class PublicToiletActivity extends BaseActivity implements View.OnClickListener,
        IUploadFileView, IPublicToiletView {

    private static final String TAG = "PublicToiletActivity";
    private Context context = this;
    @BindView(R.id.topLayout)
    QMUITopBarLayout topLayout;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.locationStreetView)
    TextView locationStreetView;
    @BindView(R.id.workContentView)
    TextView workContentView;
    @BindView(R.id.toiletIdView)
    TextView toiletIdView;
    @BindView(R.id.startScanView)
    ImageView startScanView;
    @BindView(R.id.pictureView)
    ImageView pictureView;
    @BindView(R.id.takePictureView)
    ImageView takePictureView;
    @BindView(R.id.signInButton)
    QMUIRoundButton signInButton;

    private UploadImagePresenterImpl uploadImagePresenter;
    private QMUITipDialog submitDialog;
    private String imagePath = "";//服务器返回的拍照数据
    private QMUITipDialog loadingDialog;
    private CleanToiletPresenterImpl cleanToiletPresenter;

    @Override
    public int initLayoutView() {
        return R.layout.activity_toilet;
    }

    @Override
    protected void setupTopBarLayout() {
        topLayout.setTitle("公厕保洁").setTextColor(ContextCompat.getColor(this, R.color.white));
        topLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.mainThemeColor));
        topLayout.addLeftImageButton(R.drawable.ic_left_white, 1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void initData() {
        LocationHelper.obtainCurrentLocationByGD(this, new ILocationListener() {
            @Override
            public void onLocationGet(Location location) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onAMapLocationGet(AMapLocation aMapLocation) {
                if (aMapLocation == null) {
                    locationStreetView.setText("定位失败");
                    locationStreetView.setTextColor(Color.RED);
                } else {
                    Point point = new Point(aMapLocation.getLongitude(), aMapLocation.getLatitude(), mapView.getSpatialReference());
                    mapView.setViewpointCenterAsync(point, 1200);//标注到指定经纬度并放大地图显示
                    //添加图片Marker
                    addPictureMarker(point);

                    String address = aMapLocation.getAddress();
                    if (TextUtils.isEmpty(address)) {
                        locationStreetView.setText(aMapLocation.getProvince()
                                + aMapLocation.getCity() + aMapLocation.getDistrict()
                                + aMapLocation.getStreet() + aMapLocation.getStreetNum());
                    } else {
                        locationStreetView.setText(address);
                    }
                    locationStreetView.setTextColor(Color.BLUE);
                }
            }
        }, false);
        mapView.setAttributionTextVisible(false);//去掉左下角属性标识
        mapView.setViewpointScaleAsync(12000);

        ArcGISMap arcGISMap = new ArcGISMap(BasemapStyle.ARCGIS_STREETS);
        //创建底图、并设置底图图层
        ArcGISTiledLayer baseLayer = new ArcGISTiledLayer(Constant.BASE_MAP_SERVICE_URL);
        Basemap basemap = new Basemap(baseLayer);
        arcGISMap.setBasemap(basemap);
        mapView.setMap(arcGISMap);

        uploadImagePresenter = new UploadImagePresenterImpl(this);
        cleanToiletPresenter = new CleanToiletPresenterImpl(this);
        submitDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("提交中，请稍后")
                .create();

        loadingDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("定位中，请稍后")
                .create();
    }

    @Override
    public void initEvent() {
        signInButton.setChangeAlphaWhenPress(true);
    }

    private void addPictureMarker(Point point) {
        Bitmap caseBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.on_line);
        BitmapDrawable caseDrawable = new BitmapDrawable(getResources(), caseBitmap);
        PictureMarkerSymbol pictureMarker = new PictureMarkerSymbol(caseDrawable);
        pictureMarker.setWidth(64);
        pictureMarker.setHeight(42);
        pictureMarker.loadAsync();

        Graphic graphic = new Graphic(point, pictureMarker);
        GraphicsOverlay mGraphicsOverlay = new GraphicsOverlay();
        ListenableList<Graphic> overlayGraphics = mGraphicsOverlay.getGraphics();
        ListenableList<GraphicsOverlay> graphicsOverlays = mapView.getGraphicsOverlays();
        overlayGraphics.add(graphic);
        graphicsOverlays.add(mGraphicsOverlay);
    }

    @OnClick({R.id.removeToLocalView, R.id.selectWorkLayout, R.id.startScanView, R.id.takePictureView, R.id.signInButton})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.removeToLocalView:
                loadingDialog.show();
                LocationHelper.obtainCurrentLocationByGD(this, new ILocationListener() {
                    @Override
                    public void onLocationGet(Location location) {

                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onAMapLocationGet(AMapLocation aMapLocation) {
                        if (aMapLocation == null) {
                            locationStreetView.setText("定位失败");
                            locationStreetView.setTextColor(Color.RED);
                        } else {
                            Point point = new Point(aMapLocation.getLongitude(), aMapLocation.getLatitude(), mapView.getSpatialReference());
                            mapView.setViewpointCenterAsync(point, 1200);//标注到指定经纬度并放大地图显示
                            //添加图片Marker
                            addPictureMarker(point);

                            String address = aMapLocation.getAddress();
                            if (TextUtils.isEmpty(address)) {
                                locationStreetView.setText(aMapLocation.getProvince()
                                        + aMapLocation.getCity() + aMapLocation.getDistrict()
                                        + aMapLocation.getStreet() + aMapLocation.getStreetNum());
                            } else {
                                locationStreetView.setText(address);
                            }
                            locationStreetView.setTextColor(Color.BLUE);
                        }
                        loadingDialog.dismiss();
                    }
                }, true);
                break;
            case R.id.selectWorkLayout:
                new QMUIBottomSheet.BottomListSheetBuilder(this)
                        .setTitle("请填写您此次工作的内容")
                        .addItem("日常保洁")
                        .addItem("自定义")
                        .setGravityCenter(true)
                        .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                            @Override
                            public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                                dialog.dismiss();

                                showEditDialog(tag);
                            }
                        }).build().show();
                break;
            case R.id.startScanView:
                QrConfig qrConfig = new QrConfig.Builder().setTitleText("扫一扫") //设置Title文字
                        .setShowLight(true) //显示手电筒按钮
                        .setShowTitle(true) //显示Title
                        .setScanType(QrConfig.TYPE_ALL)//识别二维码和条形码
                        .setShowAlbum(false) //显示从相册选择按钮
                        .setCornerColor(ColorHelper.getResourcesColor(this, R.color.mainThemeColor)) //设置扫描框颜色
                        .setLineColor(ColorHelper.getResourcesColor(this, R.color.mainThemeColor)) //设置扫描线颜色
                        .setLineSpeed(QrConfig.LINE_MEDIUM) //设置扫描线速度
                        .setDesText(null) //扫描框下文字
                        .setShowDes(true) //是否显示扫描框下面文字
                        .setPlaySound(true) //是否扫描成功后bi~的声音
                        .setIsOnlyCenter(true) //是否只识别框中内容(默认为全屏识别)
                        .setTitleBackgroudColor(ColorHelper.getResourcesColor(this, R.color.mainThemeColor))
                        .setTitleTextColor(Color.WHITE) //设置Title文字颜色
                        .setScreenOrientation(QrConfig.SCREEN_PORTRAIT) //设置屏幕方式
                        .setScanLineStyle(ScanLineView.style_hybrid) //扫描线样式
                        .setShowVibrator(true) //是否震动提醒
                        .create();
                QrManager.getInstance().init(qrConfig).startScan(this, new QrManager.OnScanResultCallback() {
                    @Override
                    public void onScanSuccess(ScanResult result) {
                        toiletIdView.setText(result.content);
                    }
                });
                break;
            case R.id.takePictureView:
                PictureSelector.create(this)
                        .openCamera(PictureMimeType.ofImage())
                        .imageEngine(GlideLoadEngine.createGlideEngine())
                        .maxSelectNum(1)
                        .isCompress(true)
                        .compressQuality(80)
                        .compressSavePath(FileUtils.getImageCompressPath())
                        .forResult(PictureConfig.REQUEST_CAMERA);
                break;
            case R.id.signInButton:
                LocationHelper.obtainCurrentLocationByGD(this, new ILocationListener() {
                    @Override
                    public void onLocationGet(Location location) {

                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onAMapLocationGet(AMapLocation aMapLocation) {
                        if (aMapLocation != null) {
                            Point point = new Point(aMapLocation.getLongitude(), aMapLocation.getLatitude(), mapView.getSpatialReference());
                            mapView.setViewpointCenterAsync(point, 1200);//标注到指定经纬度并放大地图显示
                            //添加图片Marker
                            addPictureMarker(point);

                            //打扫卫生签到
                            String toiletId = toiletIdView.getText().toString();
                            if (TextUtils.isEmpty(toiletId)) {
                                ToastHelper.showToast("公厕标识不能为空", ToastHelper.WARING);
                                return;
                            }
                            double longitude = aMapLocation.getLongitude();
                            double latitude = aMapLocation.getLatitude();
                            String cleanTime = TimeOrDateUtil.timestampToDate(System.currentTimeMillis());
                            cleanToiletPresenter.onReadyRetrofitRequest(toiletId, StringHelper.getUserId(),
                                    String.valueOf(longitude), String.valueOf(latitude), cleanTime, imagePath,
                                    StringHelper.filterString(workContentView.getText().toString()));
                        }
                        loadingDialog.dismiss();
                    }
                }, true);
                break;
        }
    }

    private void showEditDialog(String tag) {
        if (tag.equals("自定义")) {
            QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(context);
            builder.setTitle("工作内容")
                    .setPlaceholder("请输入您此次的工作内容")
                    .setInputType(InputType.TYPE_CLASS_TEXT)
                    .addAction("取消", (dialog, index) -> dialog.dismiss())
                    .addAction("确定", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            String inputStr = builder.getEditText().getText().toString();
                            if (!TextUtils.isEmpty(inputStr)) {
                                workContentView.setText(inputStr);
                                dialog.dismiss();
                            } else {
                                ToastHelper.showToast("自定义工作内容不能为空", ToastHelper.WARING);
                            }
                        }
                    });
            builder.create().show();
        } else {
            workContentView.setText(tag);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.REQUEST_CAMERA) {
                LocalMedia localMedia = PictureSelector.obtainMultipleResult(data).get(0);
                uploadImagePresenter.onReadyRetrofitRequest(new File(localMedia.getCompressPath()));
            }
        }
    }

    @Override
    public void showProgress() {
        submitDialog.show();
    }

    @Override
    public void hideProgress() {
        submitDialog.dismiss();
    }

    @Override
    public void obtainUploadAudioResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainUploadImageResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            /**
             * 系统路径static拼接图片返回路径
             * http://111.198.10.15:11409/static/2021-04/000bcf78345f4c1c86484efa3f9d68a2.jpeg
             */
            //2021-04\\000bcf78345f4c1c86484efa3f9d68a2.jpeg
            String url = resultBean.getData();
            this.imagePath = url;
            String realPath = StringHelper.appendCompleteURL(url);

            ArrayList<String> urls = new ArrayList<>();
            urls.add(realPath);

            Glide.with(context).load(realPath)
                    .apply(new RequestOptions().error(R.drawable.ic_load_error)).into(pictureView);
            pictureView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, BigImageActivity.class);
                    intent.putExtra("index", 0);
                    intent.putStringArrayListExtra("images", urls);
                    startActivity(intent);
                }
            });
        }
    }

    @Override
    public void obtainUploadVideoResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainDataFail() {
        ToastHelper.showToast("操作失败", ToastHelper.ERROR);
    }

    @Override
    public void obtainCleanResult(ActionResultBean resultBean) {
        Log.d(TAG, "obtainUploadAudioResult: " + new Gson().toJson(resultBean));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (uploadImagePresenter != null) {
            uploadImagePresenter.disposeRetrofitRequest();
        }
        if (cleanToiletPresenter != null) {
            cleanToiletPresenter.disposeRetrofitRequest();
        }
    }
}
