haijiang
2018-04-18 1b6d4163ff60828aa6e5043ad29d2167801caac7
app/src/main/java/com/moral/yunfushao/activity/ChartActivity.java
@@ -1,16 +1,43 @@
package com.moral.yunfushao.activity;
import android.app.AlertDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.lzy.okgo.cache.CacheMode;
import com.moral.andbrickslib.utils.FastJsonTools;
import com.moral.andbrickslib.utils.NumberUtils;
import com.moral.andbrickslib.utils.TimeUtil;
import com.moral.yunfushao.MainApp;
import com.moral.yunfushao.R;
import com.moral.yunfushao.base.BaseActivity;
import com.moral.yunfushao.common.API;
import com.moral.yunfushao.httputils.HttpCallBack;
import com.moral.yunfushao.httputils.HttpUtils;
import com.moral.yunfushao.imageload.ImageLoader;
import com.moral.yunfushao.model.UserData;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import lecho.lib.hellocharts.formatter.AxisValueFormatter;
import lecho.lib.hellocharts.formatter.LineChartValueFormatter;
import lecho.lib.hellocharts.formatter.SimpleAxisValueFormatter;
import lecho.lib.hellocharts.formatter.SimpleLineChartValueFormatter;
import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
@@ -34,6 +61,11 @@
    Axis axisY;
    private List<PointValue> mPointValues = new ArrayList<>();
    private List<AxisValue> mAxisXValues = new ArrayList<>();
    private RadioGroup rg_time;
    private TextView tv_starttime,tv_endtime,tv_value,tv_status;
    private ImageView iv_pre,iv_next;
    private int type=2;
    @Override
    protected void getBundleExtras(Bundle extras) {
@@ -47,19 +79,66 @@
    @Override
    protected void initViews() {
        initTopBar();
        tv_title.setText("历史记录");
        tv_title.setText("辐射报告");
        chartView = findView(R.id.chart);
        initLineChart();
        rg_time = findView(R.id.rg_time);
        tv_starttime = findView(R.id.tv_starttime);
        tv_endtime = findView(R.id.tv_endtime);
        tv_value = findView(R.id.tv_value);
        tv_status = findView(R.id.tv_status);
        iv_pre = findView(R.id.iv_pre);
        iv_next = findView(R.id.iv_next);
        rg_time.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i){
                    case R.id.rb_week:
                        type = 0;
                        axisX.setName("时间段(按周)");  //表格名称
                        data.setAxisXBottom(axisX); //x 轴在底部
                        chartView.setLineChartData(data);
                        tv_endtime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",TimeUtil.getCurrentDate("yyyy-MM-dd"),-1));
                        tv_starttime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_endtime.getText().toString(),-6));
                        getData(tv_starttime.getText().toString(),tv_endtime.getText().toString());
                        break;
                    case R.id.rb_month:
                        type = 1;
                        axisX.setName("时间段(按月)");  //表格名称
                        data.setAxisXBottom(axisX); //x 轴在底部
                        chartView.setLineChartData(data);
                        tv_endtime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",TimeUtil.getCurrentDate("yyyy-MM-dd"),-1));
                        tv_starttime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_endtime.getText().toString(),-28));
                        getData(tv_starttime.getText().toString(),tv_endtime.getText().toString());
                        break;
                    case R.id.rb_day:
                        type = 2;
                        axisX.setName("时间段(按日)");  //表格名称
                        data.setAxisXBottom(axisX); //x 轴在底部
                        chartView.setLineChartData(data);
                        tv_endtime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",TimeUtil.getCurrentDate("yyyy-MM-dd"),-1));
                        tv_starttime.setText(tv_endtime.getText().toString());
                        getData(tv_starttime.getText().toString(),tv_endtime.getText().toString());
                        break;
                }
            }
        });
        tv_endtime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",TimeUtil.getCurrentDate("yyyy-MM-dd"),-1));
        tv_starttime.setText(tv_endtime.getText().toString());
        getData(tv_starttime.getText().toString(),tv_endtime.getText().toString());
    }
    @Override
    protected void initListener() {
        iv_pre.setOnClickListener(this);
        iv_next.setOnClickListener(this);
    }
    @Override
    protected void initData() {
        reshowChart();
        reshowChart(dataList);
        getAd();
    }
    @Override
@@ -67,6 +146,35 @@
        switch (view.getId()){
            case R.id.tv_left:
                finish();
                break;
            case R.id.iv_pre:
                if(type==0){
                    tv_endtime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_starttime.getText().toString(),-1));
                    tv_starttime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_endtime.getText().toString(),-6));
                }else if(type == 1){
                    tv_endtime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_starttime.getText().toString(),-1));
                    tv_starttime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_endtime.getText().toString(),-28));
                }else if(type == 2){
                    tv_endtime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_starttime.getText().toString(),-1));
                    tv_starttime.setText(tv_endtime.getText().toString());
                }
                getData(tv_starttime.getText().toString(),tv_endtime.getText().toString());
                break;
            case R.id.iv_next:
                if(TimeUtil.getCurrentDate("yyyy-MM-dd").equals(TimeUtil.getAfterDate("yyyy-MM-dd",tv_endtime.getText().toString(),1))){
                    return;
                }
                if(type==0){
                    tv_starttime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_endtime.getText().toString(),1));
                    tv_endtime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_starttime.getText().toString(),6));
                }else if(type == 1){
                    tv_starttime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_endtime.getText().toString(),1));
                    tv_endtime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_starttime.getText().toString(),28));
                }else if(type == 2){
                    tv_starttime.setText(TimeUtil.getAfterDate("yyyy-MM-dd",tv_endtime.getText().toString(),1));
                    tv_endtime.setText(tv_starttime.getText().toString());
                }
                getData(tv_starttime.getText().toString(),tv_endtime.getText().toString());
                break;
        }
@@ -82,12 +190,14 @@
        List<Line> lines = new ArrayList<>();
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 (有三种 :ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND)
        line.setPointColor(Color.parseColor("#20DAE5"));
        line.setCubic(true);//曲线是否平滑,即是曲线还是折线
        line.setCubic(false);//曲线是否平滑,即是曲线还是折线
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
//      line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据(设置了这个line.setHasLabels(true);就无效)
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示(每个数据点都是个大的圆点)
        LineChartValueFormatter chartValueFormatter = new SimpleLineChartValueFormatter(3);
        line.setFormatter(chartValueFormatter);//显示小数点
        lines.add(line);
        data = new LineChartData();
        data.setLines(lines);
@@ -97,27 +207,29 @@
        //坐标轴
        axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(false);  //X坐标轴字体是斜的显示还是直的,true是斜的显示
        axisX.setName("时间段");  //表格名称
        axisX.setTextSize(10);//设置字体大小
        axisX.setTextColor(getResources().getColor(R.color.red_txt));
        axisX.setHasTiltedLabels(true);  //X坐标轴字体是斜的显示还是直的,true是斜的显示
        axisX.setName("时间段(按日)");  //表格名称
        axisX.setTextSize(8);//设置字体大小
        axisX.setTextColor(getResources().getColor(R.color.blue_txt));
//        axisX.setMaxLabelChars(7); //最多几个X轴坐标,意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        axisX.setHasLines(true); //x 轴分割线
        axisX.setLineColor(getResources().getColor(R.color.red_txt));
        axisX.setLineColor(getResources().getColor(R.color.blue_txt));
        axisX.setHasSeparationLine(true);
        data.setAxisXBottom(axisX); //x 轴在底部
        //data.setAxisXTop(axisX);  //x 轴在顶部
        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        axisY = Axis.generateAxisFromRange(0,100,1);  //Y轴
        axisY = Axis.generateAxisFromRange((float)0.0,(float)4.0, (float) 0.25);  //Y轴
        axisY.setAutoGenerated(false);
        AxisValueFormatter yvalue = new SimpleAxisValueFormatter(1);
        axisY.setFormatter(yvalue);
        axisY.setHasLines(true);
        axisY.setHasSeparationLine(true);
        axisY.setName("辐射");//y轴标注
        axisY.setTextSize(10);//设置字体大小
        axisY.setTextColor(getResources().getColor(R.color.red_txt));
        axisY.setLineColor(getResources().getColor(R.color.red_txt));
        axisY.setTextColor(getResources().getColor(R.color.blue_txt));
        axisY.setLineColor(getResources().getColor(R.color.blue_txt));
        data.setAxisYLeft(axisY);  //Y轴设置在左边
        //设置行为属性,支持缩放、滑动以及平移
@@ -131,7 +243,15 @@
         * 当时是为了解决X轴固定数据个数。见(http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2);
         */
//        chartView.setCurrentViewport(initViewPort(0,7));
        chartView.startDataAnimation();
        final Viewport v = new Viewport(chartView.getMaximumViewport());
        v.bottom = (float) 0.0;
        v.top = (float) 4.0;
//                // You have to set max and current viewports separately.
        chartView.setMaximumViewport(v);
//                // I changing current viewport with animation in this case.
////                                        lineChartCO2.setCurrentViewportWithAnimation(v);
        chartView.setCurrentViewport(v);
//        chartView.startDataAnimation();
    }
    private Viewport initViewPort(float left, float right) {
@@ -141,15 +261,23 @@
        return port;
    }
    Random random = new Random();
    private void reshowChart() {
    private void reshowChart(final ArrayList<UserData> dataList) {
        chartView.post(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<10;i++){
                    mPointValues.add(new PointValue(i,random.nextInt(100)%(100-0+1) + 0));
                    mAxisXValues.add(new AxisValue(i).setLabel(i + ""));
                mPointValues.clear();
                mAxisXValues.clear();
                for (int i=0;i<dataList.size();i++){
                    if(type == 2){
                        mPointValues.add(new PointValue(i,dataList.get(i).getHour_avg()));
                        mAxisXValues.add(new AxisValue(i).setLabel((dataList.get(i).getTime_level()-1)*3+"时"));
                    }else{
                        mPointValues.add(new PointValue(i,dataList.get(i).getDay_avg()));
                        mAxisXValues.add(new AxisValue(i).setLabel(dataList.get(i).getDate().substring(5,10)));
                    }
//                    mAxisXValues.add(new AxisValue(i).setLabel(i+""));
                }
                axisX.setValues(mAxisXValues);
@@ -160,14 +288,171 @@
                data.setLines(lines);
                chartView.setLineChartData(data);
                final Viewport v = new Viewport(chartView.getMaximumViewport());
                v.bottom = -5;
                v.top = 100 + 5;
                // You have to set max and current viewports separately.
                v.bottom = (float) 0.0;
                v.top = (float) 4.0;
////                // You have to set max and current viewports separately.
                chartView.setMaximumViewport(v);
                // I changing current viewport with animation in this case.
//                                        lineChartCO2.setCurrentViewportWithAnimation(v);
//                // I changing current viewport with animation in this case.
////                                        lineChartCO2.setCurrentViewportWithAnimation(v);
                chartView.setCurrentViewport(v);
            }
        });
    }
    private ArrayList<UserData> dataList = new ArrayList<>();
    private void getData(String startTime,String endTime){
        HashMap<String,String> params = new HashMap<>();
        params.put("user_id", MainApp.userId);
        params.put("start_time", startTime);
        params.put("end_time", endTime);
        HttpUtils.doPost(API.GETUSERDATALIST, params, CacheMode.DEFAULT, true, new HttpCallBack() {
            @Override
            public void onSuccess(String res, String msg) {
                if(progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                try {
                    JSONObject jsonObject = new JSONObject(res);
                    String data = jsonObject.optString("data");
                    ArrayList<UserData> temp = (ArrayList<UserData>) FastJsonTools.getArrayJson(data,UserData.class);
                    dataList.clear();
                    dataList.addAll(resetData(temp));
                    //重绘
                    reshowChart(dataList);
                    tv_value.setText(NumberUtils.getBigDecimalValue(jsonObject.optDouble("avg"),3)+"uSv");
                    tv_status.setText(jsonObject.optString("status"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void showLoadingDialog() {
                progressDialog.show();
            }
            @Override
            public void onFail(int errno, String s) {
                if(progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                dataList.clear();
                dataList.addAll(resetData(new ArrayList<UserData>()));
                //重绘
                reshowChart(dataList);
            }
        });
    }
    private ArrayList<UserData> resetData(ArrayList<UserData> tempList){
        ArrayList<UserData> newList = new ArrayList<>();
        if(type == 0){//周
            for (int i=0;i<7;i++){
                UserData data = new UserData();
                data.setDate(TimeUtil.getAfterDate("yyyy-MM-dd",tv_starttime.getText().toString(),i));
                data.setDay_avg(0);
                newList.add(data);
            }
        }else if(type == 1){//月
            for (int i=0;i<7;i++){
                UserData data = new UserData();
                data.setDate(TimeUtil.getAfterDate("yyyy-MM-dd",tv_starttime.getText().toString(),i*4));
                data.setDay_avg(0);
                newList.add(data);
            }
        }else if(type == 2){//日
            for (int i=0;i<8;i++){
                UserData data = new UserData();
                data.setTime_level(i+1);
                data.setHour_avg(0);
                newList.add(data);
            }
        }
        //重构数据
        float totalValues = 0;
        if(tempList!=null&&tempList.size()>0){
            for (UserData data : tempList){
                totalValues+= data.getDay_avg();
                for(UserData data1 : newList){
                    if(type == 2){
                        if(data.getTime_level() == data1.getTime_level()){
                            data1.setHour_avg(data.getHour_avg());
                        }
                    }else{
                        if(data.getDate().equals(data1.getDate())){
                            data1.setDay_avg(data.getDay_avg());
                        }
                    }
                }
            }
//            tv_value.setText(totalValues/tempList.size()+"uSv");
        }else{
//            tv_value.setText(0+"uSv");
        }
        return newList;
    }
    private AlertDialog adDialog;
    private View adView;
    private TextView tv_content,tv_name;
    private ImageView iv_logo;
    private Button bt_cancel,bt_ok;
    private void showAd(String content,String logo,String name){
        adView = LayoutInflater.from(this).inflate(R.layout.dialog_ad_layout,null);
        tv_content = (TextView) adView.findViewById(R.id.tv_content);
        tv_name = (TextView) adView.findViewById(R.id.tv_name);
        bt_cancel = (Button) adView.findViewById(R.id.bt_cancel);
        bt_ok = (Button) adView.findViewById(R.id.bt_ok);
        iv_logo = (ImageView) adView.findViewById(R.id.iv_logo);
        tv_content.setText(content);
        tv_name.setText(name);
        ImageLoader.setCircleImageView(this,logo,iv_logo,R.mipmap.circle);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adDialog.dismiss();
            }
        });
        adDialog = new AlertDialog.Builder(this).setView(adView).create();
        Window window=adDialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        adDialog.show();
    }
    private void getAd(){
        HttpUtils.doPost(API.GETAD, null, CacheMode.DEFAULT, false, new HttpCallBack() {
            @Override
            public void onSuccess(String res, String msg) {
                if(TextUtils.isEmpty(res)){
                    return;
                }
                try {
                    JSONObject json = new JSONObject(res);
                    showAd(json.optString("content"),json.optString("logo"),json.optString("name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void showLoadingDialog() {
            }
            @Override
            public void onFail(int errno, String s) {
            }
        });
    }
}