package com.ahau.againstpestinfo.activity;

import android.app.Activity;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ahau.againstpestinfo.R;
import com.ahau.againstpestinfo.domain.MyMarkerCluster;
import com.ahau.againstpestinfo.domain.PestEnitityList;
import com.ahau.againstpestinfo.domain.PestEntity;
import com.ahau.againstpestinfo.presenter.ISearchPresenter;
import com.ahau.againstpestinfo.utils.ImageLoaderUtils;
import com.ahau.againstpestinfo.utils.URLUtils;
import com.ahau.againstpestinfo.view.BaseActivity;
import com.ahau.againstpestinfo.view.ISearchView;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.Projection;
import com.amap.api.maps2d.SupportMapFragment;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

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

import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.OptionPicker;


/**
 * @author
 */


public class SearchActivity extends BaseActivity<ISearchView, ISearchPresenter<ISearchView>> implements ISearchView, AMap.OnCameraChangeListener {

    private TextView sp_peoplesearch;
    private TextView tv_dates;
    private TextView tv_areaids;
    boolean first = true;
    private Activity mActivity;


    private Button searchbtn;
    private RelativeLayout rl_marker;
    private ImageView iv_img, iv_img2;
    private ImageLoaderUtils imageLoader;
    private TextView tv_pestname, tv_pestgrade, tv_date, tv_areaid, tv_researchpeople, tv_remark, closemaker;
    private List<PestEntity> pestlist = new ArrayList<PestEntity>();
    private String pestgetUrl, pestdescribeUrl;

    private ArrayList<MarkerOptions> markerOptionsList = new ArrayList<MarkerOptions>();// 所有的marker
    private ArrayList<MarkerOptions> markerOptionsListInView = new ArrayList<MarkerOptions>();// 视野内的marker
    private AMap aMap;
    private UiSettings mUiSettings;
    private int height;// 屏幕高度(px)
    private int width;// 屏幕宽度(px)
    Handler timeHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    // 更新markers
                    resetMarks();
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels; // 获取屏幕高度 宽度等信息 为点聚合做准备
        height = dm.heightPixels;
        init();

        initView();
        initOverlay();
        isearchPresenter.fetch();

        mActivity = this;

        tv_dates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                DatePicker picker = new DatePicker(mActivity);
                picker.setRange(2000, 2030);
                picker.setSelectedItem(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
                picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        //String sData = year + "-" + month + "-" + day;
                        tv_dates.setText(year + "-" + month + "-" + day);
                    }
                });
                picker.show();
            }
        });


        //地图
        AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
            // marker 对象被点击时回调的接口 // 返回 true则表示接口已响应事件，否则返回false

            @Override
            public boolean onMarkerClick(Marker marker) {

                int i = Integer.parseInt(marker.getTitle());


                PestEntity infoUtil = pestlist.get(i);
                getpestdescribe(infoUtil.getId()); // 将信息显示在界面上

                // 将布局显示出来
                rl_marker.setVisibility(View.VISIBLE);
                return false;

            }
        };
        // 绑定 Marker 被点击事件
        aMap.setOnMarkerClickListener(markerClickListener);


        searchbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initdata(sp_peoplesearch.getText().toString(), tv_dates.getText().toString(),tv_areaids.getText().toString());
            }
        });
        closemaker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl_marker.setVisibility(View.GONE);
            }
        });

    }


    private void initView() {
        rl_marker = findViewById(R.id.My_bottomLO);
        sp_peoplesearch = findViewById(R.id.sp_peoplesearch);
        tv_dates = findViewById(R.id.tv_dates);
        tv_areaids = findViewById(R.id.tv_areaids);
        searchbtn = findViewById(R.id.searchbtn);


        //显示详细信息
        iv_img = rl_marker.findViewById(R.id.iv_img);
        iv_img2 = rl_marker.findViewById(R.id.iv_img2);
        tv_pestname = rl_marker.findViewById(R.id.tv_pestname);
        tv_pestgrade = rl_marker.findViewById(R.id.tv_pestgrade);
        tv_date = rl_marker.findViewById(R.id.tv_date);
        tv_areaid = rl_marker.findViewById(R.id.tv_areaid);
        tv_researchpeople = rl_marker.findViewById(R.id.tv_researchpeople);
        tv_remark = rl_marker.findViewById(R.id.tv_remark);
        closemaker = rl_marker.findViewById(R.id.close);

    }

    @Override
    protected ISearchPresenter<ISearchView> createPresenter() {
        return new ISearchPresenter<>();
    }

    /**
     * 姓名模块
     *
     * @param researName
     */
    @Override
    public void setResearName(final List<String> researName) {

        sp_peoplesearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OptionPicker picker = new OptionPicker(SearchActivity.this, researName.toArray(new String[researName.size()]));
                picker.setOffset(2);
                picker.setSelectedIndex(1);
                picker.setTextSize(20);
                picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(String option) {
                        sp_peoplesearch.setText(option);
                    }
                });
                picker.show();
            }
        });


        /*researName.add("请选择");
        simpleArrayAdapter<String> adapter = new simpleArrayAdapter<String>(this, android.R.layout.simple_list_item_1, researName);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_peoplesearch.setAdapter(adapter);
        sp_peoplesearch.setSelection(researName.size() - 1, true);


        *//**选项选择监听*//*
        sp_peoplesearch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (first) {
                    view.setVisibility(View.INVISIBLE);

                }
                first = false;
                Toast.makeText(SearchActivity.this, "点击了" + researName.get(position), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });*/

    }

    @Override
    public void setAreaid(final List<String> areaid) {
        tv_areaids.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OptionPicker picker = new OptionPicker(SearchActivity.this, areaid.toArray(new String[areaid.size()]));
                picker.setOffset(2);
                picker.setSelectedIndex(1);
                picker.setTextSize(20);
                picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(String option) {
                        tv_areaids.setText(option);
                    }
                });
                picker.show();
            }
        });
    }


    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {

            aMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_view)).getMap();
            setUpMap();
            mUiSettings = aMap.getUiSettings();
            mUiSettings.setAllGesturesEnabled(true);
            //mUiSettings.setTiltGesturesEnabled(false);// 禁用倾斜手势。
            //mUiSettings.setRotateGesturesEnabled(false);// 禁用旋转手势。
        }

    }

    public void initOverlay() {
        initdata("", "","");
    }

    private void setUpMap() {
        //aMap.setOnCameraChangeListener(this);
        //addMarkers();// 聚合测试点添加
    }


    public void addOverlay(List<PestEntity> infos2) {
        // 清空地图
        aMap.clear();
        // 创建marker的显示图标
        // BitmapDescriptor bitmap =
        // BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
        LatLng latLng = null;
        Marker marker;
        markerOptionsList.clear();
        // OverlayOptions options;
        if ((infos2 != null) && infos2.size() > 0) {
            for (int i = 0; i < infos2.size(); i++) {

                PestEntity info = infos2.get(i);
                // 获取经纬度
                latLng = new LatLng(Double.valueOf(info.getLatitude()), Double.valueOf(info.getLongitude()));

			/*
             * CoordinateConverter converter = new CoordinateConverter(); //
			 * 将GPS设备采集的原始GPS坐标转换成百度坐标 converter.from(CoordType.GPS);
			 * converter.coord(latLng); // latLng待转换坐标 LatLng desLatLng =
			 * converter.convert();
			 */

                // 设置marker
                markerOptionsList.add(new MarkerOptions().position(latLng).title("" + i)
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));

			/*
             * options = new MarkerOptions().position(desLatLng)// 设置位置
			 * .icon(bitmap)// 设置图标样式 .zIndex(9); // 设置marker所在层级
			 *
			 * // 添加marker marker = (Marker) mBaiduMap.addOverlay(options); //
			 * 使用marker携带info信息，当点击事件的时候可以通过marker获得info信息
			 */
                // Bundle bundle = new Bundle();
                // info必须实现序列化接口
                // bundle.putSerializable("info",info);
                // marker.setExtraInfo(bundle);
            }
            if (markerOptionsList != null) {
                for (MarkerOptions mp : markerOptionsList) {
                    marker = aMap.addMarker(mp);

                }
            }

            aMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            aMap.moveCamera(CameraUpdateFactory.zoomTo(10));

        }


        // 将地图显示在最后一个marker的位置
        /*
		 * MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
		 * mBaiduMap.setMapStatus(msu);
		 */
    }


    public void initdata(String researchpeople, String date, String areaid) {

        getpestList(researchpeople, date, areaid);

    }

    private void getpestList(String researchpeople, String date, String areaid) {
        String pestgeturl = "";
        if (researchpeople.isEmpty() && date.isEmpty() && areaid.isEmpty()) {
            pestgeturl = URLUtils.AgainPestUrl + "/pestinfolist";
        }
        if (!researchpeople.isEmpty() && !date.isEmpty() &&areaid.isEmpty()) {
            pestgeturl = URLUtils.AgainPestUrl + "/pestinfolist?researchpeople=" + researchpeople + "&date=" + date;
        }


        if (!researchpeople.isEmpty() && date.isEmpty() && areaid.isEmpty()) {
            pestgeturl = URLUtils.AgainPestUrl + "/pestinfolist?researchpeople=" + researchpeople;
        }
        if (researchpeople.isEmpty() && !date.isEmpty() && areaid.isEmpty()) {
            pestgeturl = URLUtils.AgainPestUrl + "/pestinfolist?date=" + date;
        }
        if (researchpeople.isEmpty() && date.isEmpty() && !areaid.isEmpty()) {
            pestgeturl = URLUtils.AgainPestUrl + "/pestinfolist?adressid=" + areaid;
        }

        if (!researchpeople.isEmpty() && !date.isEmpty() && areaid.isEmpty()) {
            pestgeturl = URLUtils.AgainPestUrl + "/pestinfolist?researchpeople=" + researchpeople + "&date=" + date;
        }
        if (researchpeople.isEmpty() && !date.isEmpty() && !areaid.isEmpty()) {
            pestgeturl = URLUtils.AgainPestUrl + "/pestinfolist?date=" + date + "&adressid=" + areaid;
        }
        if (!researchpeople.isEmpty() && date.isEmpty() && !areaid.isEmpty()) {
            pestgeturl = URLUtils.AgainPestUrl + "/pestinfolist?adressid=" + areaid + "&researchpeople=" + researchpeople;
        }

        if (!TextUtils.isEmpty(pestgeturl)) {

            pestgetUrl = pestgeturl;
            AsyncHttpClient client = new AsyncHttpClient();
            client.get(pestgetUrl, pestlistgetAsyncHttpResponseHandler);
        }
    }

    AsyncHttpResponseHandler pestlistgetAsyncHttpResponseHandler = new AsyncHttpResponseHandler() {

        int getDataCount = 1;

        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {

            if (getDataCount > 3) {
            } else {
                AsyncHttpClient client = new AsyncHttpClient();
                client.get(pestgetUrl, pestlistgetAsyncHttpResponseHandler);
                ++getDataCount;
            }
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

            String content = new String(arg2);
            if (!TextUtils.isEmpty(content) && content.length() > 2) {
                try {

                    JSONObject jsonObject = new JSONObject(content);
                    if (jsonObject != null) {
                        PestEnitityList pestEntityList = new PestEnitityList(jsonObject);
                        if (pestEntityList != null) {
                            pestlist.clear();

                            pestlist.addAll(pestEntityList.getPestEntities());
                            addOverlay(pestlist);
                            Toast.makeText(SearchActivity.this, "更新数据完毕", Toast.LENGTH_SHORT).show();

                        }


                        if (pestlist.isEmpty()) {

                            Toast.makeText(SearchActivity.this, "当前没有符合条件的信息", Toast.LENGTH_SHORT).show();
                        }

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };


    private void getpestdescribe(String id) {
        String pestgeturl = URLUtils.AgainPestUrl + "/query?id=" + id;
        if (!TextUtils.isEmpty(pestgeturl)) {

            pestdescribeUrl = pestgeturl;

            AsyncHttpClient client = new AsyncHttpClient();
            client.get(pestdescribeUrl, pestdescribeAsyncHttpResponseHandler);
        }

    }

    AsyncHttpResponseHandler pestdescribeAsyncHttpResponseHandler = new AsyncHttpResponseHandler() {

        int getDataCount = 1;

        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {

            if (getDataCount > 3) {
            } else {
                AsyncHttpClient client = new AsyncHttpClient();
                client.get(pestgetUrl, pestdescribeAsyncHttpResponseHandler);
                ++getDataCount;
            }
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

            String content = new String(arg2);
            if (!TextUtils.isEmpty(content) && content.length() > 2) {
                try {

                    JSONObject jsonObject = new JSONObject(content);
                    if (jsonObject != null) {
                        if (!jsonObject.isNull("data")) {

                            JSONObject dataJsonObject = jsonObject.optJSONObject("data");
                            //System.out.println(dataJsonObject);
                            PestEntity pestdescribeEntity = new PestEntity(dataJsonObject);
                            iv_img2.setImageBitmap(null);
                            if (!pestdescribeEntity.getPurl().isEmpty()) {
                                imageLoader = new ImageLoaderUtils(SearchActivity.this);
                                imageLoader.DisplayImage(pestdescribeEntity.getPurl(), iv_img);

                            }
                            if (!pestdescribeEntity.getPurl2().isEmpty()) {
                                imageLoader = new ImageLoaderUtils(SearchActivity.this);

                                imageLoader.DisplayImage(pestdescribeEntity.getPurl2(), iv_img2);
                            }

                            if (!pestdescribeEntity.getAreaid().isEmpty()) {
                                tv_areaid.setText(pestdescribeEntity.getAreaid());
                            }
                            if (!pestdescribeEntity.getDate().isEmpty()) {
                                tv_date.setText(pestdescribeEntity.getDate());
                            }
                            if (!pestdescribeEntity.getPestfirstgrade().isEmpty()) {
                                tv_pestgrade.setText(pestdescribeEntity.getPestfirstgrade() + "," + pestdescribeEntity.getPestsecondgrade());
                            }
                            if (!pestdescribeEntity.getPestname().isEmpty()) {
                                tv_pestname.setText(pestdescribeEntity.getPestname());
                            }
                            if (!pestdescribeEntity.getResearchpeople().isEmpty()) {
                                tv_researchpeople.setText(pestdescribeEntity.getResearchpeople());
                            }
                            if (!pestdescribeEntity.getRemark().isEmpty()) {
                                tv_remark.setText(pestdescribeEntity.getRemark());
                            }


                        }

                    }

					/*
					 * tv_name.setText(infoUtil.getName());
					 *
					 * tv_description.setText(infoUtil.getDescription());
					 */
                    // 将布局显示出来
                    rl_marker.setVisibility(View.VISIBLE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };


    /**
     * 模拟添加多个marker
     */
	/*
	 * private void addMarkers() { for (int i = 0; i < 200; i++) { LatLng latLng
	 * = new LatLng(Math.random() * 6 + 35, Math.random() * 6 + 112);
	 * markerOptionsList.add(new MarkerOptions() .position(latLng)
	 * .title("Marker" + i) .icon(BitmapDescriptorFactory
	 * .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
	 *
	 * } for(MarkerOptions mp :markerOptionsList){ Marker marker =
	 * aMap.addMarker(mp); } }
	 */
    @Override
    public void onCameraChange(CameraPosition arg0) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) { // 监听地图缩放
        // TODO Auto-generated method stub
        // timeHandler.sendEmptyMessage(0);// 更新界面marker
    }

    /**
     * 获取视野内的marker 根据聚合算法合成自定义的marker 显示视野内的marker
     */
    private void resetMarks() {

        System.out.println("markerOptionsList.size():" + markerOptionsList.size());
        // 开始刷新车辆
        Projection projection = aMap.getProjection();
        Point p = null;
        markerOptionsListInView.clear();
        // 获取在当前视野内的marker;提高效率
        for (MarkerOptions mp : markerOptionsList) {
            p = projection.toScreenLocation(mp.getPosition());
            if (p.x < 0 || p.y < 0 || p.x > width || p.y > height) {
                // 不添加到计算的列表中
            } else {
                markerOptionsListInView.add(mp);
            }
        }
        // 自定义的聚合类MyMarkerCluster
        ArrayList<MyMarkerCluster> clustersMarker = new ArrayList<MyMarkerCluster>();
        for (MarkerOptions mp : markerOptionsListInView) {
            if (clustersMarker.size() == 0) {
                clustersMarker.add(new MyMarkerCluster(SearchActivity.this, mp, projection, 60));// 100根据自己需求调整
            } else {
                boolean isIn = false;
                for (MyMarkerCluster cluster : clustersMarker) {
                    if (cluster.getBounds().contains(mp.getPosition())) {
                        cluster.addMarker(mp);
                        isIn = true;
                        break;
                    }
                }
                if (!isIn) {
                    clustersMarker.add(new MyMarkerCluster(SearchActivity.this, mp, projection, 60));
                }
            }
        }
        // 设置聚合点的位置和icon
        for (MyMarkerCluster mmc : clustersMarker) {
            mmc.setpositionAndIcon();
        }
        aMap.clear();
        // 重新添加
        for (MyMarkerCluster cluster : clustersMarker) {
            aMap.addMarker(cluster.getOptions());
        }
    }
}
