package com.sipai.jspatrol.PointAnalysis;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
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.sipai.jspatrol.Bean.ChartData;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.Bean.PointLongValue;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.DateFormatUtils;
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.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PointAnalysisActivity extends AppCompatActivity {
    private String token;
    private String mServer;
    private String mBizid;
    private List<Measuringpoint> points = new ArrayList<>();
    private List<ChartData> chartDataList = new ArrayList<>();
    private List<String> chartNames = new ArrayList<>();
    private List<Object[]> yAxisList = new ArrayList<>();
    private EchartView echartView;
    private int total,now;
    private TextView tv_sdt,tv_edt;
    private TimePickerView pvTime;
    private String mark = "start";

    public static void actionStart(Context context,List<Measuringpoint> list){
        Intent intent = new Intent(context,PointAnalysisActivity.class);
        intent.putExtra("points", (Serializable) list);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_point_analysis);
        init();
        initView();
        initTimePicker();
    }

    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(v -> finish());
        tv_sdt = findViewById(R.id.moudle_point_analysis_tv_startdate);
        tv_sdt.setText(DateFormatUtils.DateFormatMinStringPL(System.currentTimeMillis()-24*60*60*1000));
        tv_sdt.setOnClickListener(v->{
            mark = "start";
            pvTime.show();
        });
        tv_edt = findViewById(R.id.moudle_point_analysis_tv_enddate);
        tv_edt.setText(DateFormatUtils.DateFormatMinStringPL(System.currentTimeMillis()));
        tv_edt.setOnClickListener(v->{
            mark = "end";
            pvTime.show();
        });
        echartView = findViewById(R.id.moudle_point_analysis_ev);
        analysisData();
    }

    private void analysisData() {
        if (points!=null&&points.size()>0){
            ProgressForAll.showProgress(PointAnalysisActivity.this,"","数据获取中...");
            total = points.size();
            for (int i=0;i<points.size();i++){
                getHistory(points.get(i));
            }
        }
    }

    private void getHistory(Measuringpoint point) {
        HashMap<String,String> map = new HashMap<>();
        map.put("unitId", mBizid);
        map.put("mpids", point.getSid());
        map.put("func", "-");
        map.put("mpname",point.getName());
        map.put("sdt", tv_sdt.getText().toString());
        map.put("edt", tv_edt.getText().toString());
        map.put("slope", "");
        OKHttpUtils.OKCall(map, mServer, MethodURL.GETPointFormatHistory_Method).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showToast("数据获取失败："+e.toString());
                now+=1;
                if (total==now&&chartDataList.size()>0) {
                    ProgressForAll.cancelProgress();
                    runOnUiThread(()->refreshLineChart());
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                now+=1;
                if (total==now) {
                    ProgressForAll.cancelProgress();
                }
                if(res.contains("data")){
                    ChartData chartData = parseHistory(res,point);
                    chartDataList.add(chartData);
                    if (total==now&&chartDataList.size()>0) {
                        runOnUiThread(()->refreshLineChart());
                    }
                }else{
                    showToast("暂无该日数据！");
                }
            }
        });
    }

    private void refreshLineChart(){
        chartNames = new ArrayList<>();
        yAxisList = new ArrayList<>();
        for (int i=0;i<chartDataList.size();i++){
            chartNames.add(chartDataList.get(i).getName());
            yAxisList.add(chartDataList.get(i).getY());
        }
        echartView.refreshEchartsWithOption(EchartsOptionUtil.getListLinesChartOptions(chartNames,chartDataList.get(0).getX(), yAxisList));
    }

    private ChartData parseHistory(String res,Measuringpoint point) {
        ChartData item = new ChartData();
        try {
            JSONArray ra = new JSONArray(res);
           if (ra.length()>0){
               JSONObject jsonObject = ra.getJSONObject(0);
               JSONArray arrayItem = jsonObject.optJSONArray("data");
               List<PointLongValue> longValueList = new ArrayList<>();
               for (int a=0;a<arrayItem.length();a++){
                   PointLongValue longv = new PointLongValue();
                   if (!arrayItem.getJSONArray(a).optString(1).equals("-")){
                       longv.setName(point.getName());
                       longv.setDate(arrayItem.getJSONArray(a).optLong(0));
                       longv.setValue(arrayItem.getJSONArray(a).optString(1));
                       if (point.getUnit()!=null&&!point.getUnit().isEmpty()) {
                           longv.setUnit(point.getUnit());
                       }else {
                           longv.setUnit(arrayItem.getJSONArray(a).optString(3));
                           point.setUnit(longv.getUnit());
                       }
                       longValueList.add(longv);
                   }
               }
               item.setName(point.getName()+"("+point.getUnit()+")");
               Object[] x = new Object[longValueList.size()];
               Object[] y = new Object[longValueList.size()];
               for (int i=0;i<longValueList.size();i++){
                   x[i] = DateFormatUtils.DateFormatMinStringPL(longValueList.get(i).getDate());
                   y[i] = longValueList.get(i).getValue();
               }
               item.setX(x);
               item.setY(y);
           }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return item;
    }

    private void showToast(String s) {
        if (!PointAnalysisActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(PointAnalysisActivity.this, s, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void initTimePicker() {
        //正确设置方式 原因：注意事项有说明
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (mark.equals("start")) {
                    tv_sdt.setText(getTime(date));
                }else if (mark.equals("end")){
                    tv_edt.setText(getTime(date));
                }
                analysisData();
            }
        })
                .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);
    }

    public void init(){
        SharedPreferences sharedPre=this.getSharedPreferences("config", 0);
        mServer=sharedPre.getString("server", "");
        mBizid=sharedPre.getString("bizid", "");
        token = sharedPre.getString("token","");
        points = (List<Measuringpoint>) getIntent().getSerializableExtra("points");
    }
}