package com.sipai.jspatrol.NFC;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.OKHttpUtils;

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;

public class PatrolPointActivity extends Activity {
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView rc_view;
    private LinearLayoutManager manager;
    private PatrolPointAdapter adapter;
    private List<PatrolPoint> list = new ArrayList<>();
    private String mServer;
    private String mBizid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patrol_point);
        inits();
        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();
            }
        });
        rc_view = (RecyclerView) findViewById(R.id.moudle_patrolpoint_rc);
        manager = new LinearLayoutManager(PatrolPointActivity.this);
        rc_view.setLayoutManager(manager);
        adapter = new PatrolPointAdapter(PatrolPointActivity.this, list, new PatrolPointAdapter.onRecyclerViewItemClick() {
            @Override
            public void onItemClick(View v, int position) {
                PatrolPoint item = list.get(position);
                Intent intent=new Intent();
                intent.putExtra("ppid",item.getId());
                intent.putExtra("class","PatrolPointActivity");
                setResult(PatrolPointActivity.this.RESULT_OK, intent);
                finish();
            }
        });
        rc_view.setAdapter(adapter);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.moudle_patrolpoint_refresh);
        refreshLayout.setColorSchemeResources(R.color.blue);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getPatrolPoints();
            }
        });
    }

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

    private void getPatrolPoints() {
        HashMap<String,String> map = new HashMap<>();
        map.put("type","P");
        map.put("unitId",mBizid);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer,MethodURL.GetALLPatrolPointList_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (!PatrolPointActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            refreshLayout.setRefreshing(false);
                            Toast.makeText(PatrolPointActivity.this,"获取巡更点信息失败！",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (!PatrolPointActivity.this.isFinishing()) {
                    if (res.isEmpty()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                refreshLayout.setRefreshing(false);
                                Toast.makeText(PatrolPointActivity.this, "未查询到厂区巡检点信息！", Toast.LENGTH_SHORT).show();
                            }
                        });

                    } else {
                        list = getData(res);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                refreshLayout.setRefreshing(false);
                                manager = new LinearLayoutManager(PatrolPointActivity.this);
                                rc_view.setLayoutManager(manager);
                                adapter = new PatrolPointAdapter(PatrolPointActivity.this, list, new PatrolPointAdapter.onRecyclerViewItemClick() {
                                    @Override
                                    public void onItemClick(View v, int position) {
                                        PatrolPoint item = list.get(position);
                                        Intent intent = new Intent();
                                        intent.putExtra("ppid", item.getId());
                                        intent.putExtra("class", "point");
                                        setResult(PatrolPointActivity.this.RESULT_OK, intent);
                                        finish();
                                    }
                                });
                                rc_view.setAdapter(adapter);
                            }
                        });
                    }
                }
            }
        });

//        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
//        RequestParams params = new RequestParams();
//        params.add("search_code",mBizid);
//        AsyncHttpClient client = new AsyncHttpClient();
//        client.setCookieStore(myCookieStore);
//        client.post(mServer+"timeEfficiency/patrolPoint/getList4APP.do",params ,new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(String response) {
//                if(response.isEmpty()){
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            refreshLayout.setRefreshing(false);
//                            Toast.makeText(PatrolPointActivity.this,"未查询到厂区信息！",Toast.LENGTH_SHORT).show();
//                        }
//                    });
//
//                }else{
//                    list=getData(response);
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            refreshLayout.setRefreshing(false);
//                            manager = new LinearLayoutManager(PatrolPointActivity.this);
//                            rc_view.setLayoutManager(manager);
//                            adapter = new PatrolPointAdapter(PatrolPointActivity.this, list, new PatrolPointAdapter.onRecyclerViewItemClick() {
//                                @Override
//                                public void onItemClick(View v, int position) {
//                                    PatrolPoint item = list.get(position);
//                                    Intent intent=new Intent();
//                                    intent.putExtra("ppid",item.getId());
//                                    intent.putExtra("class","point");
//                                    setResult(PatrolPointActivity.this.RESULT_OK, intent);
//                                    finish();
//                                }
//                            });
//                            rc_view.setAdapter(adapter);
//                        }
//                    });
//                }
//            }
//
//            @Override
//            public void onFailure(Throwable e) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        refreshLayout.setRefreshing(false);
//                        Toast.makeText(PatrolPointActivity.this,"获取巡更点信息失败！",Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//            }
//
//            @Override
//            public void onStart() {
//                super.onStart();
//            }
//
//            @Override
//            public void onFinish() {
//                super.onFinish();
//            }
//        });

    }

    private List<PatrolPoint> getData(String response) {
        List<PatrolPoint> listres = new ArrayList<>();
        try{
            JSONObject jsonObject = new JSONObject(response);
            JSONArray aNews =  new JSONArray(jsonObject.getString("result") );
            if(aNews!=null && aNews.length()>0){
                for(int i=0;i<aNews.length();i++){
                    PatrolPoint item = new PatrolPoint();
                    item.setId(aNews.getJSONObject(i).get("id").toString());
                    item.setName(aNews.getJSONObject(i).get("name").toString());
                    listres.add(item);
                }
            }
        }catch(JSONException ex){
            Log.e("JSON Error: ", ex.toString());
        }
        return listres;
    }

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