package com.sipai.jspatrol.PointAnalysis;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.Bean.Nodes;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.Statement.StatementListActivity;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.ui.EmptyLayout;

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

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;

public class SolutionListActivity extends AppCompatActivity {
    private String mServer;
    private String mBizid;
    private List<Nodes> nodes = new ArrayList<>();
    private SwipeRefreshLayout refresh;
    private RecyclerView rc_view;
    private EmptyLayout emptyLayout;
    private NodesAdapter nodesAdapter;
    private LinearLayoutManager manager;
    private List<Measuringpoint> seledPoints = new ArrayList<>();

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

    @Override
    protected void onResume() {
        super.onResume();
    }

    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 View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
        emptyLayout = findViewById(R.id.moudle_statement_type_ui_empty);
        refresh = findViewById(R.id.moudle_statement_type_refresh);
        refresh.setColorSchemeResources(R.color.blue);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getSolutionList();
            }
        });
        rc_view = findViewById(R.id.moudle_statement_type_rc);
        manager = new LinearLayoutManager(SolutionListActivity.this);
        rc_view.setLayoutManager(manager);
    }

    private void getSolutionList() {
        HashMap<String,String> map = new HashMap<>();
        map.put("unitId", mBizid);
        map.put("search_name","");
        OKHttpUtils.OKCall(map, mServer, MethodURL.getSolutionList_Method).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                errorResponse();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("nodes")&&res.contains("id")){
                    nodes = parseNodes(res);
                    updateList();
                }else {
                    showEmpty();
                }
            }
        });
    }

    private void updateList() {
        if (!SolutionListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refresh.setRefreshing(false);
                    manager = new LinearLayoutManager(SolutionListActivity.this);
                    rc_view.setLayoutManager(manager);
                    nodesAdapter = new NodesAdapter(SolutionListActivity.this,nodes);
                    rc_view.setAdapter(nodesAdapter);
                }
            });
        }
    }

    private List<Nodes> parseNodes(String result) {
        List<Nodes> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(result);
            for (int i=0;i<array.length();i++){
                Nodes item = new Nodes();
                item.setId(array.getJSONObject(i).optString("id"));
                item.setText(array.getJSONObject(i).optString("text"));
                item.setType(array.getJSONObject(i).optString("type"));
                item.setMpid(array.getJSONObject(i).optString("mpid"));
                List<Nodes> areas = new ArrayList<>();
                if (!array.getJSONObject(i).optString("nodes").isEmpty()&&!array.getJSONObject(i).optString("nodes").equals("null")) {
                    areas = parseNodes(array.getJSONObject(i).optString("nodes"));
                }
                item.setNodes(areas);
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return list;
        }
        return list;
    }

    private void showEmpty() {
        if (!SolutionListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    rc_view.setVisibility(View.GONE);
                    emptyLayout.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    private void errorResponse() {
        if (!SolutionListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refresh.setRefreshing(false);
                    Toast.makeText(SolutionListActivity.this, "列表获取失败！", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void init() {
        SharedPreferences sharedPre=this.getSharedPreferences("config", 0);
        mServer=sharedPre.getString("server", "");
        mBizid=sharedPre.getString("bizid", "");
    }

    class NodesAdapter extends RecyclerView.Adapter<NodesAdapter.ViewHolder> {
        private Context context;
        private List<Nodes> list;

        public NodesAdapter(Context context, List<Nodes> list) {
            this.context = context;
            this.list = list;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_nodes,parent,false);
            ViewHolder viewHolder = new ViewHolder(view);
            viewHolder.iv_arrow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = viewHolder.getAdapterPosition();
                    Nodes item = list.get(position);
                    if (item.getNodes()!=null&&item.getNodes().size()>0){
                        if (viewHolder.rc.getVisibility()==View.GONE) {
                            viewHolder.rc.setVisibility(View.VISIBLE);
                            viewHolder.iv_arrow.setImageResource(R.mipmap.arrow_down);
                        }else {
                            viewHolder.iv_arrow.setImageResource(R.mipmap.arrow_right);
                            viewHolder.rc.setVisibility(View.GONE);
                        }
                    }
                }
            });
            viewHolder.tv_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = viewHolder.getAdapterPosition();
                    seledPoints = new ArrayList<>();
                    Nodes item = list.get(position);
                    if (item.getType().equals("4")||item.getType().equals("6")) {
                        if (item.getNodes() != null && item.getNodes().size() > 0) {
                            for (int i = 0; i < item.getNodes().size();i++){
                                    Measuringpoint measuringpoint = new Measuringpoint();
                                    measuringpoint.setSid(item.getNodes().get(i).getMpid());
                                    measuringpoint.setName(item.getNodes().get(i).getText());
                                    seledPoints.add(measuringpoint);
                            }
                                PointAnalysisActivity.actionStart(SolutionListActivity.this, seledPoints);
                        } else {
                            Measuringpoint point = new Measuringpoint();
                            point.setSid(item.getMpid());
                            point.setName(item.getText());
                            seledPoints.add(point);
                            PointAnalysisActivity.actionStart(SolutionListActivity.this, seledPoints);
                        }
                    }else {
                        if (item.getNodes()!=null&&item.getNodes().size()>0){
                            if (viewHolder.rc.getVisibility()==View.GONE) {
                                viewHolder.rc.setVisibility(View.VISIBLE);
                                viewHolder.iv_arrow.setImageResource(R.mipmap.arrow_down);
                            }else {
                                viewHolder.iv_arrow.setImageResource(R.mipmap.arrow_right);
                                viewHolder.rc.setVisibility(View.GONE);
                            }
                        }
                    }
                }
            });
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Nodes item = list.get(position);
            holder.tv_title.setText(item.getText());
            if (item.getNodes()!=null&&item.getNodes().size()>0){
                holder.rc.setLayoutManager(new LinearLayoutManager(context));
                NodesAdapter nodesAdapter = new NodesAdapter(context,item.getNodes());
                holder.rc.setAdapter(nodesAdapter);
            }else {
                holder.rc.setVisibility(View.GONE);
                holder.iv_arrow.setImageResource(R.mipmap.moudle_bizpop_biz);
            }
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder{
            ImageView iv_arrow;
            TextView tv_title;
            RecyclerView rc;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                iv_arrow = itemView.findViewById(R.id.iv_arrow);
                tv_title = itemView.findViewById(R.id.tv_title);
                rc = itemView.findViewById(R.id.rc_children);
            }
        }

    }
}