package com.sipai.jspatrol.Equ.Equfrgment;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sipai.jspatrol.Bean.EquList;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.Equ.EquCardActivity;
import com.sipai.jspatrol.ProMonitoring.MeasurePointsAdapter;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.SharedPreferencesData;
import com.sipai.ui.EmptyLayout;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

/**
 * created by lvliming on 2020/10/22
 */
public class EquDocumentFragment extends Fragment {
    private SharedPreferencesData sharedpre;
    private HashMap<String, String> map_base = new HashMap<>();
    private String mServer;
    private EquList equ;
    private String mBizid;
    private int page = 1;
    private EmptyLayout emptyLayout;
    private SwipeRefreshLayout refresh;
    private RecyclerView rc_view;
    private LinearLayoutManager manager;
    private MeasurePointsAdapter pointsAdapter;
    private List<Measuringpoint> measuringpoints = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_equ_document,container,false);
        init();
        initView(view);
//        getDocuments();
        return view;
    }

    private void init() {
        EquCardActivity equcard = (EquCardActivity) getActivity();
        equ = equcard.getEquList();
        sharedpre = new SharedPreferencesData(getActivity());
        map_base = sharedpre.getAll();
        mServer = map_base.get("mServer");
        SharedPreferences sharedPre = getActivity().getSharedPreferences("config", 0);
        mBizid = sharedPre.getString("bizid", "");
    }

    @Override
    public void onResume() {
        super.onResume();
        getEquPoints();
//        getDocuments();
    }

    private void initView(View view) {
        emptyLayout = view.findViewById(R.id.moudle_equ_doc_ui_empty);
        rc_view = view.findViewById(R.id.moudle_equ_doc_rc_point);
        manager = new LinearLayoutManager(getActivity());
        rc_view.setLayoutManager(manager);
        refresh = view.findViewById(R.id.moudle_equ_doc_refresh);
        refresh.setColorSchemeResources(R.color.blue);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getEquPoints();
            }
        });
    }


    private void getEquPoints() {
        HashMap<String,String> map = new HashMap<>();
        map.put("equipmentId",equ.getId());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GETEquPoints_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                measuringpoints = parseMeasuringPoints(res);
                if (measuringpoints.size()>0){
                    updatePoints();
                }else {
                    showEmpty();
                }
            }
        });
    }

    private void showEmpty() {
        if (isAdded()) {
            if (!getActivity().isFinishing()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refresh.setRefreshing(false);
                        rc_view.setVisibility(View.GONE);
                        emptyLayout.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    }

    private void updatePoints() {
        if (isAdded()) {
            if (!getActivity().isFinishing()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refresh.setRefreshing(false);
                        rc_view.setVisibility(View.VISIBLE);
                        emptyLayout.setVisibility(View.GONE);
                        pointsAdapter = new MeasurePointsAdapter(getActivity(), measuringpoints);
                        rc_view.setAdapter(pointsAdapter);
                    }
                });
            }
        }
    }

    private List<Measuringpoint> parseMeasuringPoints(String res) {
        List<Measuringpoint> points = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(res);
            JSONArray arrayPoint = jsonObject.getJSONArray("mPoint4APP");
            for (int a=0;a<arrayPoint.length();a++){
                Measuringpoint point = new Measuringpoint();
                point.setSid(arrayPoint.getJSONObject(a).opt("id").toString());
                point.setName(arrayPoint.getJSONObject(a).opt("parmname").toString());
                point.setUnit(arrayPoint.getJSONObject(a).opt("unit").toString());
                point.setCvalue(arrayPoint.getJSONObject(a).opt("parmvalue").toString());
                point.setType(arrayPoint.getJSONObject(a).opt("signalType").toString());
                point.setScadacode(arrayPoint.getJSONObject(a).opt("id").toString());
                point.setAlarmmax(arrayPoint.getJSONObject(a).opt("alarmmax").toString());
                point.setAlarmmin(arrayPoint.getJSONObject(a).opt("alarmmin").toString());
                points.add(point);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return points;
    }

}
