package com.casic.dcms.view.toilet;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.amap.api.location.AMapLocation;
import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityToiletBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.ToiletListModel;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.DataBaseManager;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.PictureSelectorHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.utils.callback.ILocationListener;
import com.casic.dcms.utils.callback.ISelectorListener;
import com.casic.dcms.view.BigImageActivity;
import com.casic.dcms.vm.ToiletViewModel;
import com.casic.dcms.vm.UploadViewModel;
import com.casic.dcms.widgets.SignInDialog;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
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.entity.LocalMedia;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.kit.ContextKit;
import com.pengxh.androidx.lite.kit.IntKit;
import com.pengxh.androidx.lite.kit.LongKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.widget.TitleBarView;
import com.pengxh.androidx.lite.widget.dialog.AlertInputDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

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

public class PublicToiletActivity extends AndroidxBaseActivity<ActivityToiletBinding> {

    private static final String TAG = "PublicToiletActivity";
    private final Context context = this;
    private UploadViewModel uploadViewModel;
    private String imagePath = "";//服务器返回的拍照数据
    private ToiletViewModel toiletViewModel;

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);
        binding.titleView.setOnClickListener(new TitleBarView.OnClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
                startActivity(new Intent(context, CleaningRecordsActivity.class));
            }
        });
    }

    @Override
    protected void observeRequestState() {
        uploadViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    StringKit.show(PublicToiletActivity.this, "上传中，请稍后...");
                } else {
                    TextPaint textPaint = binding.showPictureView.getPaint();
                    textPaint.setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
                    textPaint.setAntiAlias(true);//抗锯齿
                }
            }
        });

        toiletViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    LoadingDialog.show(PublicToiletActivity.this, "处理中，请稍后");
                } else {
                    LoadingDialog.dismiss();
                }
            }
        });
    }

    @Override
    public void initOnCreate(@Nullable Bundle savedInstanceState) {
        ArcGISMap arcGISMap = new ArcGISMap(BasemapStyle.ARCGIS_STREETS);
        //创建底图、并设置底图图层
        Basemap basemap = new Basemap(ArcGisMapCreator.createBaseLayer());
        arcGISMap.setBasemap(basemap);
        binding.mapView.setMap(arcGISMap);

        //公厕图层
        ServiceFeatureTable featureTable = ArcGisMapCreator.createOtherFeatureTable("公共厕所");
        featureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.ON_INTERACTION_NO_CACHE);
        FeatureLayer toiletLayer = new FeatureLayer(featureTable);
        arcGISMap.getOperationalLayers().add(toiletLayer);
        binding.mapView.setMap(arcGISMap);
        binding.mapView.setAttributionTextVisible(false);//去掉左下角属性标识
        binding.mapView.setViewpointScaleAsync(8000);

        uploadViewModel = new ViewModelProvider(this).get(UploadViewModel.class);
        uploadViewModel.imageModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    String url = resultBean.getData();
                    imagePath = url;
                    String realPath = StringHelper.appendCompleteURL(url);

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

                    binding.showPictureView.setVisibility(View.VISIBLE);
                    binding.showPictureView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (urls.get(0).isEmpty()) {
                                StringKit.show(context, "图片加载失败，无法查看大图");
                            } else {
                                ContextKit.navigatePageTo(context, BigImageActivity.class, 0, urls);
                            }
                        }
                    });
                }
            }
        });

        toiletViewModel = new ViewModelProvider(this).get(ToiletViewModel.class);
        toiletViewModel.cleanToiletModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    new SignInDialog.Builder()
                            .setContext(context)
                            .setTitle("保洁保卡成功")
                            .setAddress(binding.locationStreetView.getText().toString())
                            .setOnDialogClickListener(new SignInDialog.OnDialogClickListener() {
                                @Override
                                public void onViewClick() {
                                    ContextKit.navigatePageTo(context, CleaningRecordsActivity.class);
                                    finish();
                                }
                            }).build().show();
                }
            }
        });

        String systemTime = LongKit.timestampToCompleteDate(System.currentTimeMillis());
        //默认显示结束时间
        binding.endTimeView.setText(systemTime);
        LocationHelper.get().getCurrentLocation(this, new ILocationListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onAMapLocationGet(AMapLocation aMapLocation) {
                if (aMapLocation == null) {
                    binding.locationStreetView.setText("定位失败");
                    binding.locationStreetView.setTextColor(Color.RED);
                } else {
                    double[] gcjToWgs = LocationHelper.get().gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                    Point point = new Point(gcjToWgs[0], gcjToWgs[1], SpatialReferences.getWgs84());
                    binding.mapView.setViewpointCenterAsync(point, 1200);//标注到指定经纬度并放大地图显示
                    //添加图片Marker
                    addPictureMarker(point);

                    String address = aMapLocation.getAddress();
                    if (TextUtils.isEmpty(address)) {
                        binding.locationStreetView.setText(aMapLocation.getProvince()
                                + aMapLocation.getCity() + aMapLocation.getDistrict()
                                + aMapLocation.getStreet() + aMapLocation.getStreetNum());
                    } else {
                        binding.locationStreetView.setText(address);
                    }
                    binding.locationStreetView.setTextColor(Color.BLUE);
                }
            }
        }, false);
    }

    @Override
    public void initEvent() {
        binding.expandMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.mapView.setViewpointScaleAsync(binding.mapView.getMapScale() * 0.5);
            }
        });

        binding.minusMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.mapView.setViewpointScaleAsync(binding.mapView.getMapScale() * 2);
            }
        });

        binding.obtainToiletIdLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<ToiletListModel.DataBean> toiletBeanList = DataBaseManager.get().getToilets();
                if (toiletBeanList.size() == 0) {
                    StringKit.show(context, "获取公厕数据失败，请联系管理员");
                    return;
                }
                QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                sheetBuilder.setTitle("请选择您要打卡的公厕");
                for (ToiletListModel.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();

                        binding.toiletIdView.setText(toiletBeanList.get(position).getId());
                        //TODO 是否需要将地图移到相应的公厕，待定
                    }
                }).build().show();
            }
        });

        binding.startTimeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TimePickerDialog.Builder().setThemeColor(IntKit.convertColor(context, R.color.mainThemeColor))
                        .setTitleStringId("请选择开始时间")
                        .setWheelItemTextSize(16)
                        .setCyclic(false)
                        .setMinMillseconds(System.currentTimeMillis() - LocaleConstant.HALF_YEAR)
                        .setMaxMillseconds(System.currentTimeMillis())
                        .setType(Type.ALL)
                        .setCallBack((timePickerView, millSeconds) -> {
                            binding.startTimeView.setText(LongKit.timestampToCompleteDate(millSeconds));
                        }).build().show(getSupportFragmentManager(), "all");
            }
        });

        binding.endTimeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TimePickerDialog.Builder().setThemeColor(IntKit.convertColor(context, R.color.mainThemeColor))
                        .setTitleStringId("请选择结束时间")
                        .setWheelItemTextSize(16)
                        .setCyclic(false)
                        .setMinMillseconds(System.currentTimeMillis() - LocaleConstant.HALF_YEAR)
                        .setMaxMillseconds(System.currentTimeMillis())
                        .setType(Type.ALL)
                        .setCallBack((timePickerView, millSeconds) -> {
                            binding.endTimeView.setText(LongKit.timestampToCompleteDate(millSeconds));
                        }).build().show(getSupportFragmentManager(), "all");
            }
        });

        binding.selectWorkLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new QMUIBottomSheet.BottomListSheetBuilder(context)
                        .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();
            }
        });

        binding.takePictureView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelectorHelper.takePicture(context, new ISelectorListener() {
                    @Override
                    public void onSuccess(ArrayList<LocalMedia> result) {
                        LocalMedia localMedia = result.get(0);
                        uploadViewModel.uploadImage(context, new File(localMedia.getCompressPath()));
                    }
                });
            }
        });

        binding.signInButton.setChangeAlphaWhenPress(true);
        binding.signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LocationHelper.get().getCurrentLocation(context, new ILocationListener() {

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

                            //打扫卫生签到
                            String toiletId = binding.toiletIdView.getText().toString();
                            if (TextUtils.isEmpty(toiletId)) {
                                StringKit.show(context, "公厕标识不能为空");
                                return;
                            }
                            String startTime = binding.startTimeView.getText().toString();
                            if (startTime.equals("")) {
                                StringKit.show(context, "保洁开始时间不能为空");
                                return;
                            }
                            toiletViewModel.cleanToilet(context, toiletId, StringHelper.getUserBean().getId(),
                                    String.valueOf(gcjToWgs[0]), String.valueOf(gcjToWgs[1]), startTime,
                                    binding.endTimeView.getText().toString(),
                                    imagePath, binding.workContentView.getText().toString());
                        }
                    }
                }, true);
            }
        });
    }

    private void addPictureMarker(Point point) {
        BitmapDrawable symbolDrawable = (BitmapDrawable) IntKit.convertDrawable(this, R.mipmap.on_line);
        if (symbolDrawable != null) {
            PictureMarkerSymbol symbolMarker = new PictureMarkerSymbol(symbolDrawable);
            symbolMarker.setWidth(64);
            symbolMarker.setHeight(42);
            symbolMarker.loadAsync();

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

    private void showEditDialog(String tag) {
        if (tag.equals("自定义")) {
            new AlertInputDialog.Builder()
                    .setContext(this)
                    .setTitle("工作内容")
                    .setHintMessage("请输入工作内容")
                    .setNegativeButton("取消")
                    .setPositiveButton("确定")
                    .setOnDialogButtonClickListener(new AlertInputDialog.OnDialogButtonClickListener() {
                        @Override
                        public void onConfirmClick(String value) {
                            binding.workContentView.setText(value);
                        }

                        @Override
                        public void onCancelClick() {

                        }
                    })
                    .build().show();
        } else {
            binding.workContentView.setText(tag);
        }
    }
}
