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.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.text.InputType;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;

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

import com.amap.api.location.AMapLocation;
import com.casic.dcms.R;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.ToiletListBean;
import com.casic.dcms.databinding.ActivityToiletBinding;
import com.casic.dcms.mvp.presenter.impl.CleanToiletPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.UploadImagePresenterImpl;
import com.casic.dcms.mvp.view.IPublicToiletView;
import com.casic.dcms.mvp.view.IUploadFileView;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.OtherUtils;
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.casic.dcms.widgets.SignInDialog;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.layers.FeatureLayer;
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.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.util.ListenableList;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

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

public class PublicToiletActivity extends AndroidxBaseActivity<ActivityToiletBinding> implements View.OnClickListener, IUploadFileView, IPublicToiletView {

    private static final String TAG = "PublicToiletActivity";
    private final Context context = this;
    private UploadImagePresenterImpl uploadImagePresenter;
    private String imagePath = "";//服务器返回的拍照数据
    private CleanToiletPresenterImpl cleanToiletPresenter;

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText("公厕保洁");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
        viewBinding.titleBarLayout.rightImageView.setOnClickListener(v -> startActivity(new Intent(context, CleanResultListActivity.class)));
    }

    @Override
    public void initData() {
        String systemTime = TimeOrDateUtil.timestampToCompleteDate(System.currentTimeMillis());
        //默认显示结束时间
        viewBinding.endTimeView.setText(systemTime);
        LocationHelper.obtainCurrentLocationByGD(this, new ILocationListener() {
            @Override
            public void onLocationGet(Location location) {

            }

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

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

        ArcGISMap arcGISMap = new ArcGISMap(BasemapStyle.ARCGIS_STREETS);
        //创建底图、并设置底图图层
        Basemap basemap = new Basemap(ArcGisMapCreator.createBaseLayer());
        arcGISMap.setBasemap(basemap);
        viewBinding.mapView.setMap(arcGISMap);

        //公厕图层
        ServiceFeatureTable featureTable = ArcGisMapCreator.createOtherFeatureTable("公共厕所");
        featureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.ON_INTERACTION_NO_CACHE);
        FeatureLayer toiletLayer = new FeatureLayer(featureTable);
        arcGISMap.getOperationalLayers().add(toiletLayer);
        viewBinding.mapView.setMap(arcGISMap);

        uploadImagePresenter = new UploadImagePresenterImpl(this);
        cleanToiletPresenter = new CleanToiletPresenterImpl(this);
    }

    @Override
    public void initEvent() {
        TextPaint textPaint = viewBinding.showPictureView.getPaint();
        textPaint.setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        textPaint.setAntiAlias(true);//抗锯齿

        viewBinding.expandMapView.setOnClickListener(this);
        viewBinding.minusMapView.setOnClickListener(this);
        viewBinding.obtainToiletIdLayout.setOnClickListener(this);
        viewBinding.startTimeLayout.setOnClickListener(this);
        viewBinding.endTimeLayout.setOnClickListener(this);
        viewBinding.selectWorkLayout.setOnClickListener(this);
        viewBinding.takePictureView.setOnClickListener(this);
        viewBinding.signInButton.setOnClickListener(this);

        viewBinding.signInButton.setChangeAlphaWhenPress(true);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.expandMapView) {
            viewBinding.mapView.setViewpointScaleAsync(viewBinding.mapView.getMapScale() * 0.5);
        } else if (id == R.id.minusMapView) {
            viewBinding.mapView.setViewpointScaleAsync(viewBinding.mapView.getMapScale() * 2);
        } else if (id == R.id.obtainToiletIdLayout) {
            List<ToiletListBean.DataBean> toiletBeanList = StringHelper.getToiletBeanList();
            if (toiletBeanList.size() == 0) {
                ToastHelper.showToast("获取公厕数据失败，请联系管理员", ToastHelper.ERROR);
                return;
            }
            QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
            sheetBuilder.setTitle("请选择您要打卡的公厕");
            for (ToiletListBean.DataBean it : toiletBeanList) {
                sheetBuilder.addItem(it.getName());
            }
            sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                @Override
                public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                    dialog.dismiss();

                    viewBinding.toiletIdView.setText(toiletBeanList.get(position).getId());
                    //TODO 是否需要将地图移到相应的公厕，待定
                }
            }).build().show();
        } else if (id == R.id.startTimeLayout) {
            new TimePickerDialog.Builder().setThemeColor(ContextCompat.getColor(this, R.color.mainThemeColor))
                    .setTitleStringId("请选择开始时间")
                    .setWheelItemTextSize(16)
                    .setCyclic(false)
                    .setMinMillseconds(System.currentTimeMillis() - Constant.HALF_YEAR)
                    .setMaxMillseconds(System.currentTimeMillis())
                    .setType(Type.ALL)
                    .setCallBack((timePickerView, millSeconds) -> {
                        viewBinding.startTimeView.setText(TimeOrDateUtil.timestampToCompleteDate(millSeconds));
                    }).build().show(getSupportFragmentManager(), "all");
        } else if (id == R.id.endTimeLayout) {
            new TimePickerDialog.Builder().setThemeColor(ContextCompat.getColor(this, R.color.mainThemeColor))
                    .setTitleStringId("请选择结束时间")
                    .setWheelItemTextSize(16)
                    .setCyclic(false)
                    .setMinMillseconds(System.currentTimeMillis() - Constant.HALF_YEAR)
                    .setMaxMillseconds(System.currentTimeMillis())
                    .setType(Type.ALL)
                    .setCallBack((timePickerView, millSeconds) -> {
                        viewBinding.endTimeView.setText(TimeOrDateUtil.timestampToCompleteDate(millSeconds));
                    }).build().show(getSupportFragmentManager(), "all");
        } else if (id == 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();
        } else if (id == R.id.takePictureView) {
            OtherUtils.takePicture(this);
        } else if (id == 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) {
                        double[] gcjToWgs = LocationHelper.gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                        Point point = new Point(gcjToWgs[0], gcjToWgs[1], SpatialReference.create(4326));
                        viewBinding.mapView.setViewpointCenterAsync(point, 1200);//标注到指定经纬度并放大地图显示
                        //添加图片Marker
                        addPictureMarker(point);

                        //打扫卫生签到
                        String toiletId = viewBinding.toiletIdView.getText().toString();
                        if (TextUtils.isEmpty(toiletId)) {
                            ToastHelper.showToast("公厕标识不能为空", ToastHelper.WARING);
                            return;
                        }
                        String startTime = viewBinding.startTimeView.getText().toString();
                        if (startTime.equals("")) {
                            ToastHelper.showToast("保洁开始时间不能为空", ToastHelper.WARING);
                            return;
                        }
                        cleanToiletPresenter.onReadyRetrofitRequest(toiletId, StringHelper.getUserBean().getId(),
                                String.valueOf(gcjToWgs[0]), String.valueOf(gcjToWgs[1]), startTime,
                                viewBinding.endTimeView.getText().toString(),
                                imagePath, StringHelper.filterString(viewBinding.workContentView.getText().toString()));
                    }
                }
            }, 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 = viewBinding.mapView.getGraphicsOverlays();
        overlayGraphics.add(graphic);
        graphicsOverlays.add(mGraphicsOverlay);
    }

    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)) {
                                viewBinding.workContentView.setText(inputStr);
                                dialog.dismiss();
                            } else {
                                ToastHelper.showToast("自定义工作内容不能为空", ToastHelper.WARING);
                            }
                        }
                    });
            builder.create().show();
        } else {
            viewBinding.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() {
        OtherUtils.showLoadingDialog(this, "处理中，请稍后");
    }

    @Override
    public void hideProgress() {
        OtherUtils.dismissLoadingDialog();
    }

    @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);

            viewBinding.showPictureView.setVisibility(View.VISIBLE);
            viewBinding.showPictureView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OtherUtils.showBigImage(context, 0, urls);
                }
            });
        }
    }

    @Override
    public void obtainUploadVideoResult(ActionResultBean resultBean) {

    }

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

    @Override
    public void obtainCleanResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            new SignInDialog.Builder()
                    .setContext(this)
                    .setTitle("保洁保卡成功")
                    .setAddress(viewBinding.locationStreetView.getText().toString())
                    .setOnDialogClickListener(new SignInDialog.OnDialogClickListener() {
                        @Override
                        public void onViewClick() {
                            startActivity(new Intent(context, CleanResultListActivity.class));
                            PublicToiletActivity.this.finish();
                        }
                    }).build().show();
        }
    }

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