package com.sjkj.appthreefloor_tsgz.fragment.viewModel;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.databinding.ObservableField;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.sjkj.appthreefloor_tsgz.R;
import com.sjkj.appthreefloor_tsgz.bean.MapBean;
import com.sjkj.appthreefloor_tsgz.map.MapMarkBean;
import com.sjkj.base_lib.utils.LocationUtils;
import com.sjkj.base_lib.vm.BaseViewModel;

import java.util.ArrayList;
import java.util.List;

public class MapViewModel extends BaseViewModel {
    public ObservableField<List<MapMarkBean>> markListBean = new ObservableField<>();

    /**
     * 地图参数
     */
    private AMap aMap;
    private String popTab = "company";
    //    public String address = "";
    public ObservableField<Double> userLat = new ObservableField<>(0.00);
    public ObservableField<Double> userLog = new ObservableField<>(0.00);
    private List<MapBean> enterpriseList = new ArrayList<>();//公司点标记
    private List<MapBean> patrolList = new ArrayList<>();//巡更点标记
    private Context mapContext;
//    private ScanningSuccessPopup successPopup;
//    private ScanningFailurePopup failurePopup;

    /**
     * 设置搜索切换按钮
     *
     * @param tab
     */
    public void setPopTab(String tab) {
        popTab = tab;
        changeMapMarker();
    }

    /**
     * ViewModel初始化aMap
     *
     * @param aMap
     */
    public void setAMap(AMap aMap, Context context) {
        this.aMap = aMap;
        this.mapContext = context;
    }

    /**
     * 切换图片层集合
     */
    public void changeMapMarker() {
        if (TextUtils.equals(popTab, "company"))
            isMapMarker("enterprise", enterpriseList);
        else
            isMapMarker("name", patrolList);
    }

//    /**
//     * 展示搜索pop
//     *
//     * @param activity
//     * @param view
//     */
//    public void searchPopup(Activity activity, View view) {
//        if (null == popup) {
//            popup = new SearchCompanyPopup(activity, null);
//            popup.setListener(bean -> {
//                if (bean == null) return;
//                Intent intent = new Intent(activity, EmergencyInspectionDetailsActivity.class);
//                intent.putExtra("id", bean.getPkId());
//                intent.putExtra("name", bean.getEnterpriseName());
//                intent.putExtra("address", bean.getEnterpriseAddress());
//                intent.putExtra("longitude", bean.getLongitude());
//                intent.putExtra("latitude", bean.getLatitude());
//                intent.putExtra("time", bean.getTime());
//                activity.startActivity(intent);
//            });
//        }
//        popup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 250);
//    }

    /**
     * 对Map进行插点展示
     *
     * @param name
     * @param list
     */
    protected void isMapMarker(String name, List<MapBean> list) {
        aMap.clear(true);
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.isEmpty(list.get(i).getLatitude()) || TextUtils.isEmpty(list.get(i).getLongitude())
                    || TextUtils.equals("null", list.get(i).getLatitude()) || TextUtils.equals("null", list.get(i).getLongitude())) {
                continue;
            }
            LatLng latLng = new LatLng(Double.valueOf(list.get(i).getLatitude()), Double.valueOf(list.get(i).getLongitude()));
            MarkerOptions options = new MarkerOptions();
            options.icon(TextUtils.equals("enterprise", name) ? BitmapDescriptorFactory.fromResource(R.drawable.company_location_img) : BitmapDescriptorFactory.fromResource(R.drawable.company_location_img_1));
            options.position(latLng);
            options.title(TextUtils.equals("enterprise", name) ? list.get(i).getPkId() + "," + list.get(i).getEnterpriseName() + "," + list.get(i).getEnterpriseAddress() : list.get(i).getPkId() + "," + list.get(i).getPatrolpointName() + "," + list.get(i).getEnterpriseAddress());
            aMap.addMarker(options);
        }

        aMap.setOnMarkerClickListener(marker -> {
            singleMapMarker(marker, name);
            return true;
        });
    }

    /**
     * 点击对应marker点展示，带有详情框
     */
    public void singleMapMarker(Marker marker, String name) {
        if (TextUtils.equals("enterprise", name))
            marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.company_location_img));
        else
            marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.company_location_img_1));
        String[] array = marker.getTitle().split(",");
        aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            View infoWindow = null;//自定义marker布局

            @Override
            public View getInfoWindow(Marker marker) {
                if (infoWindow == null) {
                    infoWindow = LayoutInflater.from(mapContext).inflate(R.layout.custom_marker, null);
                    infoWindow.findViewById(R.id.parentLayout).setOnClickListener(v -> {
                        if (TextUtils.equals("enterprise", name)) {
//                            ARouter.getInstance().build(Constant.ACTIVITY_URL_DETAILS)
//                                    .withString("title", array[1])
//                                    .withString("id", array[0])
//                                    .navigation();
                        }
                    });
                }
                render(marker, infoWindow);
                return infoWindow;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });
        marker.showInfoWindow();
    }

    /**
     * 自定义infoWindow窗口
     */
    private void render(Marker marker, View view) {
        String[] array = marker.getTitle().split(",");
        TextView markerName = view.findViewById(R.id.markerName);
        TextView markerDistance = view.findViewById(R.id.markerDistance);
        markerName.setText(array[1]);
        markerDistance.setText(array[2]);
    }

    /**
     * 定位用户当前坐标
     *
     * @param activity
     */
    public void startLocation(Activity activity) {
        LocationUtils.getInstance().startLocation(true, new LocationUtils.OnLocationListener() {
            @Override
            public void onLocationChanged(double lat, double lng, String address, int code) {
                address = address;
//                if (TextUtils.isEmpty(aMapLocation.getAddress())) {
//                    DigitalEmergencyMainActivity.address = "定位失败";
//                } else {
//                    DigitalEmergencyMainActivity.address = aMapLocation.getAddress();
//                }
                Log.e("startLocation", "address" + address + "_log:" + lng + "_lat:" + lat);
                MyLocationStyle myLocationStyle;
                myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
                myLocationStyle.interval(5000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
                myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//定位一次，且将视角移动到地图中心点
                myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
                myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
                myLocationStyle.strokeWidth(0);
                myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromView(activity.getLayoutInflater().inflate(R.layout.map_location, null)));
                aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
                aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
                aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 16));

                requestMapData(activity);
            }
        });
    }

    public void requestMapData(Activity activity) {
//        ProgressHelper.show(activity);
//        HashMap<String, Object> params = new HashMap<>();
//        params.put("userId", AppTools.getUserId());
//        params.put("latitude", userLat);
//        params.put("longitude", userLog);
//
//
//        HttpTools.post(mapContext, URLConfig.getInstance().getPOINT_POSITION(), params, new JsonResponseListener() {
//            @Override
//            public void onSuccess(JSONObject response) {
//                ProgressHelper.hide();
//                if (null != response.optJSONObject("data")) {
//                    if (response.optJSONObject("data").optJSONArray("qiye").length() > 0) {
//                        enterpriseList.addAll(new Gson().fromJson(response.optJSONObject("data").optString("qiye"),
//                                new TypeToken<List<MapBean>>() {
//                                }.getType()));
//                    }
//
//                    if (response.optJSONObject("data").optJSONArray("xungengdian").length() > 0) {
//                        patrolList.addAll(new Gson().fromJson(response.optJSONObject("data").optString("xungengdian"),
//                                new TypeToken<List<MapBean>>() {
//                                }.getType()));
//                    }
//                    changeMapMarker();
//                }
//            }
//
//            @Override
//            public void onFailure(String result) {
//                ProgressHelper.hide();
//                ToastUtils.showToast(result);
//            }
//
//        });
    }
}
