package com.sipai.jspatrol.ProMonitoring;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.Bean.WaterQualityList;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.DateFormatUtils;
import com.sipai.jspatrol.utils.MyMarkerView;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.ProgressForAll;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.github.mikephil.charting.components.Legend.LegendPosition.RIGHT_OF_CHART_INSIDE;


public class PointHistoryActivity extends AppCompatActivity implements OnChartValueSelectedListener {
	private View mMainView;
	private List<WaterQualityList> mData;

	private String mServer;
	private String mBizid;
	private String mUsername;
	private String mPassword;
	private String mUserid;
	private String mCaption;
	private String pointid;
	private Measuringpoint point;
	private String unit = "值";//单位
	private TextView tvstartdate,tvenddate;
	private TimePickerView pvTime;
	private String mark = "start";
	private TextView tv_avg;
	
	/**
	 * Deep copy of data.
	 */
	private final int errorflag=0;
	private final int passflag=1;
	private LineChart lineChart;
	private List<Measuringpoint> mpList;
	private String s_max,s_min,s_avg;
	private ArrayList<String> xValueList;
	private ArrayList<String> yValueList;
	private ArrayList<String> maxValueList;
	private ArrayList<String> minValueList;
	//下拉刷新更新页面handler
	private Handler mHandler = new Handler(){    
        
        public void handleMessage(Message msg) {
			switch (msg.what){
				case passflag:
					unit = "";
					if (s_max!=null){
						unit = "最大值:"+s_max;
					}
					if (s_min!=null){
						unit = unit+"   "+"最小值:"+s_min;
					}
					if (s_avg!=null){
						unit = unit+"   "+"平均值:"+s_avg;
					}
					tv_avg.setText(unit);
					if (point.getAlarmmax()!=null&&!point.getAlarmmax().isEmpty()){
						setChartDataAndMaxMin(xValueList,yValueList,maxValueList,minValueList,0);
					}else {
						setChartData(xValueList, yValueList, 0);
					}
					lineChart.invalidate();
					break;
				case errorflag:
					cancelProgress();
					Toast.makeText(PointHistoryActivity.this,"查询失败",Toast.LENGTH_SHORT).show();
					break;
			}

        }
};
	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pointhistory);
		init();
		initView();
		initTimePicker();
		if (tvstartdate.getText()!=null&&tvenddate.getText()!=null) {
			showProgress(null, "数据加载中，请稍后...");
			new getResThread().start();
		}
	}

	private void initView() {
		TextView tv_title = (TextView) findViewById(R.id.moudle_back_title_tv_title);
		tv_title.setText("历史曲线");
		ImageView btn_back = (ImageView) findViewById(R.id.moudle_back_title_iv_back);
		btn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		lineChart = (LineChart) findViewById(R.id.moudle_point_history_linechart);
		//对折线图初始化
		initChartView();
		tvstartdate=findViewById(R.id.et_startdate);
		tvstartdate.setText(DateFormatUtils.DateFormatMinStringPL(System.currentTimeMillis()-24*60*60*1000));
		tvstartdate.setOnClickListener(v->{
			mark = "start";
			pvTime.show();
		});
		tv_avg = findViewById(R.id.moudle_avg);
		tvenddate=findViewById(R.id.et_enddate);
		tvenddate.setText(DateFormatUtils.DateFormatMinStringPL(System.currentTimeMillis()));
		tvenddate.setOnClickListener(v->{
			mark = "end";
			pvTime.show();
		});
		Button butserch=(Button)findViewById(R.id.but_search);
		butserch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showProgress(null, "数据加载中，请稍后...");
				new getResThread().start();
			}
		});
		Button butlast=(Button)findViewById(R.id.but_last);
		butlast.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				tvstartdate.setText(DateFormatUtils.DateFormatMinStringPL(DateFormatUtils.pareSec(tvstartdate.getText().toString()+":00")-24*60*60*1000));
				tvenddate.setText(DateFormatUtils.DateFormatMinStringPL(DateFormatUtils.pareSec(tvenddate.getText().toString()+":00")-24*60*60*1000));
				showProgress(null, "数据加载中，请稍后...");
				new getResThread().start();
			}
		});
		Button butnext=(Button)findViewById(R.id.but_next);
		butnext.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				tvstartdate.setText(DateFormatUtils.DateFormatMinStringPL(DateFormatUtils.pareSec(tvstartdate.getText().toString()+":00")+24*60*60*1000));
				tvenddate.setText(DateFormatUtils.DateFormatMinStringPL(DateFormatUtils.pareSec(tvenddate.getText().toString()+":00")+24*60*60*1000));

			}
		});
	}

	private void initTimePicker() {
		//正确设置方式 原因：注意事项有说明
		pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
			@Override
			public void onTimeSelect(Date date,View v) {//选中事件回调
				if (mark.equals("start")) {
					tvstartdate.setText(getTime(date));
				}else if (mark.equals("end")){
					tvenddate.setText(getTime(date));
				}
			}
		})
				.setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
				.setCancelText("取消")//取消按钮文字
				.setSubmitText("确认")//确认按钮文字
				.setTitleSize(20)//标题文字大小
				.setTitleText("选择时间")//标题文字
				.setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
				.isCyclic(true)//是否循环滚动
				.setTitleColor(Color.BLACK)//标题文字颜色
				.isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
				.build();
	}

	private String getTime(Date date) {//可根据需要自行截取数据显示
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return format.format(date);
	}

	/**
	 * 初始化折线图
	 */
	private void initChartView() {

		//在点击高亮值时回调
		lineChart.setOnChartValueSelectedListener(this);

		//设置整个图表的颜色
		lineChart.setBackgroundResource(R.drawable.bg_line_chart);

		Description description = lineChart.getDescription();
		description.setYOffset(10);
		description.setEnabled(true);
		description.setText("时间");

		lineChart.getLegend().setPosition(RIGHT_OF_CHART_INSIDE);

		//是否可以缩放、移动、触摸
		lineChart.setTouchEnabled(true);
		lineChart.setDragEnabled(true);

		//不能让缩放，不然有bug，所以接口也没实现
		lineChart.setScaleEnabled(true);
		lineChart.setPinchZoom(true);

		//设置图表距离上下左右的距离
		lineChart.setExtraOffsets(10, 10, 10, 0);

		//获取左侧侧坐标轴
		YAxis leftAxis = lineChart.getAxisLeft();

		//设置是否显示Y轴的值
		leftAxis.setDrawLabels(true);
		leftAxis.setTextColor(this.getResources().getColor(R.color.blue));

		//设置所有垂直Y轴的的网格线是否显示
		leftAxis.setDrawGridLines(true);

		//设置虚线
		leftAxis.enableGridDashedLine(10f, 10f, 0f);
		leftAxis.setDrawZeroLine(false);

		//设置Y极值，我这里没设置最大值，因为项目需要没有设置最大值
		leftAxis.setAxisMinimum(0f);

		//将右边那条线隐藏
		lineChart.getAxisRight().setEnabled(false);
		//获取X轴
		XAxis xAxis = lineChart.getXAxis();
		//设置X轴的位置，可上可下
		xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

		//将垂直于X轴的网格线隐藏，将X轴显示
		xAxis.setDrawGridLines(false);
		xAxis.setDrawAxisLine(true);

		//设置X轴上lable颜色和大小
		xAxis.setTextSize(8f);
		xAxis.setTextColor(Color.GRAY);

		//设置X轴高度
		xAxis.setAxisLineWidth(1);
	}
	/**
	 * @param xData
	 * @param yData
	 * @param flag
	 */
	private void setChartData(final List<String> xData , List<String> yData, int flag) {
		lineChart.getXAxis().setLabelCount(4);
		lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
			@Override
			public String getFormattedValue(float value, AxisBase axis) {

				//对X轴上的值进行Format格式化，转成相应的值
				int intValue = (int)value;

				//筛选出自己需要的值，一般都是这样写没问题，并且一定要加上这个判断，不然会出错
				if(xData.size()>intValue && intValue>=0){
					//这样显示在X轴上值就是 05:30  05:35，不然会是1.0  2.0
					return xData.get(intValue);
				}else{
					return "";
				}
			}
		});
		unit = "";
		if (s_max!=null){
			unit = "最大值:"+s_max;
		}
		if (s_min!=null){
			unit = unit+"  "+"最小值:"+s_min;
		}
		if (s_avg!=null){
			unit = unit+"  "+"平均值:"+s_avg;
		}
		lineChart.invalidate();

		MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view,xData);
		mv.setChartView(lineChart);
		lineChart.setMarker(mv);

		final ArrayList<Entry> values = new ArrayList<>();
		float min = Float.valueOf(yData.get(0));
		float max = Float.valueOf(yData.get(0));
		for (int i = 0; i < yData.size(); i++) {
			//注意这里的Entry（不一定需要）采用这种方式构造，采用其他的结果是一样的
				values.add(new Entry(i, Float.valueOf(yData.get(i)), xData.get(i)));
				if (min>Float.valueOf(yData.get(i))){
					min = Float.valueOf(yData.get(i));
				}
				if (max<Float.valueOf(yData.get(i))){
					max = Float.valueOf(yData.get(i));
				}

		}

		LineDataSet lineDataset ;
		if (min<0) {
			lineChart.getAxisLeft().setAxisMinimum(min * 2);
		}else {
			lineChart.getAxisLeft().setAxisMinimum(0);
		}
		if (max>0) {
			lineChart.getAxisLeft().setAxisMaximum(max*2);
		}else {
			lineChart.getAxisLeft().setAxisMaximum(0);
		}

		if (lineChart.getData() != null && lineChart.getData().getDataSetCount() > 0) {

			lineDataset = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
			lineDataset.setValues(values);
			if(flag==0){
				lineDataset.setLabel(unit);
				lineDataset.setDrawFilled(false);
			}else{
				lineDataset.setLabel("");
				lineDataset.setDrawFilled(false);
			}
			lineChart.getData().notifyDataChanged();
			lineChart.notifyDataSetChanged();

		}else{
			if(flag==0){
				lineDataset = new LineDataSet(values, unit);
				lineDataset.setDrawFilled(false);
			}else{
				lineDataset = new LineDataSet(values, unit);
				lineDataset.setDrawFilled(false);
			}

			lineDataset.setColor(this.getResources().getColor(R.color.green04));

			//设置是否显示圆点
			lineDataset.setDrawCircles(false);

			//是否显示每个点的Y值
			lineDataset.setDrawValues(false);
//			lineDataset.setFillColor(R.color.white);
			LineData lineData = new LineData(lineDataset);
			lineChart.setData(lineData);
			lineChart.animateX(1000);
		}
	}

	private void setChartDataAndMaxMin(final List<String> xData , List<String> yData, List<String> maxs,List<String> mins, int flag) {
		lineChart.getXAxis().setLabelCount(4);
		lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
			@Override
			public String getFormattedValue(float value, AxisBase axis) {

				//对X轴上的值进行Format格式化，转成相应的值
				int intValue = (int)value;

				//筛选出自己需要的值，一般都是这样写没问题，并且一定要加上这个判断，不然会出错
				if(xData.size()>intValue && intValue>=0){
					//这样显示在X轴上值就是 05:30  05:35，不然会是1.0  2.0
					return xData.get(intValue);
				}else{
					return "";
				}
			}
		});


		lineChart.invalidate();

		MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view,xData);
		mv.setChartView(lineChart);
		lineChart.setMarker(mv);

		final ArrayList<Entry> values1 = new ArrayList<>();
		final ArrayList<Entry> values2 = new ArrayList<>();
		final ArrayList<Entry> values3 = new ArrayList<>();
		float min = Float.valueOf(yData.get(0));
		float max = Float.valueOf(yData.get(0));
		for (int i = 0; i < yData.size(); i++) {
			//注意这里的Entry（不一定需要）采用这种方式构造，采用其他的结果是一样的
			values1.add(new Entry(i, Float.valueOf(yData.get(i)), xData.get(i)));
			values2.add(new Entry(i, Float.valueOf(maxs.get(i)), xData.get(i)));
			values3.add(new Entry(i, Float.valueOf(mins.get(i)), xData.get(i)));
			if (min>Float.valueOf(yData.get(i))){
				min = Float.valueOf(yData.get(i));
			}
			if (max<Float.valueOf(yData.get(i))){
				max = Float.valueOf(yData.get(i));
			}
		}

		if (point.getAlarmmax()!=null&&!point.getAlarmmax().isEmpty()){
			if (max<Float.valueOf(point.getAlarmmax())){
				max = Float.valueOf(point.getAlarmmax());
			}
		}
		if (point.getAlarmmin()!=null&&!point.getAlarmmin().isEmpty()){
			if (min>Float.valueOf(point.getAlarmmin())){
				min = Float.valueOf(point.getAlarmmin());
			}
		}

		LineDataSet lineDataset ;
		LineDataSet lineDataset2 ;
		LineDataSet lineDataset3 ;
		if (min<0) {
			lineChart.getAxisLeft().setAxisMinimum(min * 2);
		}else {
			lineChart.getAxisLeft().setAxisMinimum(0);
		}
		if (max>0) {
			lineChart.getAxisLeft().setAxisMaximum(max*2);
		}else {
			lineChart.getAxisLeft().setAxisMaximum(0);
		}

		if (lineChart.getData() != null && lineChart.getData().getDataSetCount() > 0) {

			lineDataset = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
			lineDataset.setValues(values1);
			lineDataset2 = (LineDataSet) lineChart.getData().getDataSetByIndex(1);
			lineDataset2.setValues(values2);
			lineDataset3 = (LineDataSet) lineChart.getData().getDataSetByIndex(2);
			lineDataset3.setValues(values3);

			if(flag==0){
				lineDataset.setDrawFilled(false);
				lineDataset2.setDrawFilled(false);
			}else{
				lineDataset.setDrawFilled(false);
				lineDataset2.setDrawFilled(false);
			}
			lineChart.getData().notifyDataChanged();
			lineChart.notifyDataSetChanged();

		}else{
			if(flag==0){
				lineDataset = new LineDataSet(values1, "实际值");
				lineDataset.setDrawFilled(false);
				lineDataset2 = new LineDataSet(values2,"报警上限:"+point.getAlarmmax());
				lineDataset2.setDrawFilled(false);
				lineDataset3 = new LineDataSet(values3, "报警下限:"+point.getAlarmmin());
				lineDataset3.setDrawFilled(false);
			}else{
				lineDataset = new LineDataSet(values1, "实际值");
				lineDataset.setDrawFilled(false);
				lineDataset2 = new LineDataSet(values2, "报警上限:"+point.getAlarmmax());
				lineDataset2.setDrawFilled(false);
				lineDataset3 = new LineDataSet(values3, "报警下限:"+point.getAlarmmin());
				lineDataset3.setDrawFilled(false);
			}

			lineDataset.setColor(this.getResources().getColor(R.color.green04));
			lineDataset2.setColor(this.getResources().getColor(R.color.red));
			lineDataset3.setColor(this.getResources().getColor(R.color.red01));

			//设置是否显示圆点
			lineDataset.setDrawCircles(false);
			lineDataset2.setDrawCircles(false);
			lineDataset3.setDrawCircles(false);

			//是否显示每个点的Y值
			lineDataset.setDrawValues(false);
			lineDataset2.setDrawValues(false);
			lineDataset3.setDrawValues(false);
//			lineDataset.setFillColor(R.color.white);
			LineData lineData = new LineData(lineDataset,lineDataset2,lineDataset3);
			lineChart.setData(lineData);
			lineChart.animateX(1000);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			//切换用户
			case android.R.id.home:
				finish();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onValueSelected(Entry entry, Highlight highlight) {

	}

	@Override
	public void onNothingSelected() {

	}

	/**
	 * 初始化
	 */
	public void init(){
		SharedPreferences sharedPre=this.getSharedPreferences("config", 0);
		mServer=sharedPre.getString("server", "");
		mUsername=sharedPre.getString("username", "");
		mPassword=sharedPre.getString("password", "");
		mUserid=sharedPre.getString("userid", "");
		mCaption=sharedPre.getString("caption", "");

        Intent intent=getIntent();
		point = (Measuringpoint) intent.getSerializableExtra("point");
        pointid=point.getSid();
		if (point.getUnitId()!=null&&!point.getUnitId().isEmpty()){
			mBizid = point.getUnitId();
		}else {
			mBizid=sharedPre.getString("bizid", "");
		}
        
        TextView tvname =(TextView)findViewById(R.id.tv_name);
        tvname.setText(intent.getStringExtra("name"));

        
	}


	private class getResThread extends Thread{
		public void run() {
			
			getRes();
		}
	}
	private void getRes(){
		HashMap<String,String> map = new HashMap<>();
		map.put("bizId", mBizid);
		map.put("ids", pointid);
		map.put("sdt", tvstartdate.getText().toString());
		map.put("edt", tvenddate.getText().toString());
		OKHttpUtils.OKCallGet(map, mServer, MethodURL.GETPointHistory_Method).enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
				Message message = Message.obtain();
				message.what=errorflag;
				mHandler.sendMessage(message);
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String res = response.body().string();
				cancelProgress();
				if(res.contains("measuredt")){
					getData(res);
					Message message = Message.obtain();
					message.what=passflag;
					mHandler.sendMessage(message);
				}else{
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(PointHistoryActivity.this, "暂无该日数据！", Toast.LENGTH_SHORT).show();
						}
					});
				}
			}
		});
	}

	private void getData(String response) {
		xValueList = new ArrayList<>();
		yValueList = new ArrayList<>();
		maxValueList = new ArrayList<>();
		minValueList = new ArrayList<>();
		try{

			JSONArray all =  new JSONArray(response);
			JSONObject jsonObject = all.getJSONObject(0);
			s_max = jsonObject.optString("max");
			s_min = jsonObject.optString("min");
			DecimalFormat df = new DecimalFormat("#.##");
			s_avg = df.format(jsonObject.optDouble("avg"));
			JSONArray aNews = jsonObject.optJSONArray("data");
			for(int i=0;i<aNews.length();i++){
				Measuringpoint item = new Measuringpoint();
				if (aNews.getJSONObject(i).get("parmvalue")!=null&&aNews.getJSONObject(i).get("measuredt")!=null){
					item.setTime(aNews.getJSONObject(i).get("measuredt").toString().substring(5,16));
					item.setValue(aNews.getJSONObject(i).get("parmvalue").toString());
					xValueList.add(item.getTime());
					yValueList.add(item.getValue());
					if (point.getAlarmmax()!=null&&!point.getAlarmmax().isEmpty()){
						maxValueList.add(point.getAlarmmax());
					}
					if (point.getAlarmmin()!=null&&!point.getAlarmmin().isEmpty()){
						minValueList.add(point.getAlarmmin());
					}
				}
			}
		}catch(JSONException ex){
			Log.e("JSON Error: ", ex.toString());
		}
	}

	//显示进度提示
	public void showProgress(String title, String msg) {
		if(!PointHistoryActivity.this.isFinishing()) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					ProgressForAll.showProgress(PointHistoryActivity.this,"",msg);
				}
			});
		}
	}

	//取消进度提示
	public void cancelProgress(){
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				ProgressForAll.cancelProgress();
			}
		});
	}
}