package com.sipai.jspatrol.MonitorScreen;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

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

import com.sipai.jspatrol.Bean.Nodes;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.GuideMenuUrl;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.Webv.MonitorScreenActivity;
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 cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MonitorScreenListActivity extends AppCompatActivity {
    private String mServer;
    private String mBizid;
    private List<Nodes> nodes;
    private RecyclerView rc_type;
    private RecyclerView rc_ps;
    private LinearLayoutManager orManager;
    private StaggeredGridLayoutManager manager;
    private MenuTypeAdapter typeAdapter;
    private MonitorScreenAdapter msAdapter;
    private int sel = 0;
    private EmptyLayout emptyLayout;

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

    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_monitor_screen_ui_empty);
        rc_type = findViewById(R.id.moudle_monitor_screen_rc_type);
        orManager = new LinearLayoutManager(this);
        orManager.setOrientation(RecyclerView.HORIZONTAL);
        rc_type.setLayoutManager(orManager);
        rc_ps = findViewById(R.id.moudle_monitor_screen_rc_ps);
        manager = new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL);
        rc_ps.setLayoutManager(manager);
    }

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

    private void getMonitorScreenList() {
        HashMap<String,String> map = new HashMap<>();
        map.put("menuType", "proVisual");
        map.put("unitId", mBizid);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetFrameTree_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();
                nodes = parseNodes(res);
                if (nodes.size()>0) {
                    nodes.get(0).setSel("sel");
                    setType();

//                    setPSAdapter();
                }else {
                    errorResponse();
                }
            }
        });
    }

    private void setType() {
        if (!MonitorScreenListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    typeAdapter = new MenuTypeAdapter(nodes,MonitorScreenListActivity.this, new MenuTypeAdapter.RecyclerViewOnItemClickListener(){
                        @Override
                        public void onItemClickListener(View view, int position) {
                            nodes.get(sel).setSel("unsel");
                            nodes.get(position).setSel("sel");
                            sel = position;
                            typeAdapter.notifyDataSetChanged();
                            if (nodes.get(sel).getNodes().size()>0) {
                                setPSAdapter();
                            }else {
                                MonitorScreenActivity.actionStart(MonitorScreenListActivity.this, GuideMenuUrl.url_monitor_screen+"?frameId="+nodes.get(sel).getId(),nodes.get(sel).getText());
                            }
                        }
                    });
                    rc_type.setAdapter(typeAdapter);
                    if (nodes.get(sel).getNodes().size()>0) {
                        setPSAdapter();
                    }else {
                        new SweetAlertDialog(MonitorScreenListActivity.this,SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("提示")
                                .setContentText("是否进入"+nodes.get(sel).getText()+"?")
                                .setConfirmText("进入")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismissWithAnimation();
                                        MonitorScreenActivity.actionStart(MonitorScreenListActivity.this, GuideMenuUrl.url_monitor_screen+"?frameId="+nodes.get(sel).getId(),nodes.get(sel).getText());
                                    }
                                }).setCancelText("取消")
                                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismissWithAnimation();
                                    }
                                }).show();
                    }
                }
            });
        }
    }

    private void setPSAdapter() {
        if (!MonitorScreenListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (nodes.get(sel).getNodes()!=null&&nodes.get(sel).getNodes().size()>0){
                        emptyLayout.setVisibility(View.GONE);
                        rc_ps.setVisibility(View.VISIBLE);
                        msAdapter = new MonitorScreenAdapter(MonitorScreenListActivity.this,nodes.get(sel).getNodes());
                        rc_ps.setAdapter(msAdapter);
                    }else {
                        emptyLayout.setVisibility(View.VISIBLE);
                        rc_ps.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    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.setSel("unsel");
                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 errorResponse() {
        if (!MonitorScreenListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MonitorScreenListActivity.this, "列表获取失败！", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

}