package com.sipai.jspatrol.Equ;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.sipai.jspatrol.Bean.EquList;
import com.sipai.jspatrol.R;

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

import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class PertainToEquSelActivity extends AppCompatActivity {
    private EditText edt_equname;
    private Button btn_search;
    private RecyclerView rc_view;
    private SwipeRefreshLayout refresh;
    private LinearLayoutManager manager;
    private PertainToEquSelAdapter equAdapter;
    private List<EquList> equs = new ArrayList<>();
    private EquList sel_item;
    private String st_pSectionId = "";

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

    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();
            }
        });
        edt_equname = findViewById(R.id.moudle_pertain_to_equ_sel_edt_equname);
        btn_search = findViewById(R.id.moudle_pertain_to_equ_sel_btn_search);
        rc_view = findViewById(R.id.moudle_pertain_to_equ_sel_rc);
        manager = new LinearLayoutManager(PertainToEquSelActivity.this);
        rc_view.setLayoutManager(manager);
        equAdapter = new PertainToEquSelAdapter(equs, PertainToEquSelActivity.this, new PertainToEquSelAdapter.onRecyclerViewItemClick() {
            @Override
            public void onItemClick(View v, int position) {
                sel_item = equs.get(position);
                Intent intent = new Intent();
                intent.putExtra("sel",sel_item);
                setResult(RESULT_OK,intent);
                finish();
            }
        });
        rc_view.setAdapter(equAdapter);
        refresh = findViewById(R.id.moudle_pertain_to_equ_sel_refresh);
        refresh.setColorSchemeResources(R.color.blue);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getEquList();
            }
        });
    }

    private void getEquList() {
        showRefresh();
        String getsearch = "";
        if (edt_equname.getText()!=null&&!edt_equname.getText().toString().isEmpty()){
            getsearch = edt_equname.getText().toString();
        }
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        RequestParams params = new RequestParams();
        params.put("page", "1");
        params.put("rows", "100");
        params.put("companyId",mBizid);
        params.put("pSectionId",st_pSectionId);
        params.put("search_name", getsearch);
        AsyncHttpClient client = new AsyncHttpClient();
        client.setCookieStore(myCookieStore);
        client.post(mServer + "equipment/getList4APP.do?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                String res = response;
                equs=getData(response);
                UpDateUI();
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                String a = error.toString();
                if(!PertainToEquSelActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (refresh.isRefreshing()){
                                refresh.setRefreshing(false);
                            }
                            new SweetAlertDialog(PertainToEquSelActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("设备列表获取失败请重试！")
                                    .setConfirmText("确认")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getEquList();
                                        }
                                    }).setCancelText("取消")
                                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            finish();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

        });
    }

    private void showRefresh() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!refresh.isRefreshing()){
                    refresh.setRefreshing(true);
                }
            }
        });
    }

    private void UpDateUI() {
        if (!PertainToEquSelActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (refresh.isRefreshing()){
                        refresh.setRefreshing(false);
                    }
                    if(equs!=null){
                        manager = new LinearLayoutManager(PertainToEquSelActivity.this);
                        rc_view.setLayoutManager(manager);
                        equAdapter = new PertainToEquSelAdapter(equs, PertainToEquSelActivity.this, new PertainToEquSelAdapter.onRecyclerViewItemClick() {
                            @Override
                            public void onItemClick(View v, int position) {
                                sel_item = equs.get(position);
                                Intent intent = new Intent();
                                intent.putExtra("sel",sel_item);
                                setResult(RESULT_OK,intent);
                                finish();
                            }
                        });
                        rc_view.setAdapter(equAdapter);
                    }
                }
            });

        }
    }

    private List<EquList> getData(String response) {
        List<EquList> list = new ArrayList<EquList>();
        try{
            JSONObject jsonObject = new JSONObject(response);
            JSONArray array = new JSONArray(jsonObject.optString("rows"));
            for (int i=0;i<array.length();i++){
                EquList item = new EquList();
                item.setAreaid(array.getJSONObject(i).optString("areaid"));
                item.setAssetclassid(array.getJSONObject(i).optString(""));
                item.setBizid(array.getJSONObject(i).optString(""));
                if (array.getJSONObject(i).get("company")!=null&&!array.getJSONObject(i).get("company").toString().equals("null")) {
                    JSONObject company = new JSONObject(array.getJSONObject(i).optString("company"));
                    item.setCompany(company.optString("name"));
                }else {
                    item.setCompany("");
                }
                if (array.getJSONObject(i).get("equipmentClass")!=null&&!array.getJSONObject(i).get("equipmentClass").toString().equals("null")) {
                    JSONObject equClass = new JSONObject(array.getJSONObject(i).optString("equipmentClass"));
                    item.setEquipmentClass(equClass.optString("name"));
                }else {
                    item.setEquipmentClass("");
                }
                if (array.getJSONObject(i).get("equipmentLevel")!=null&&!array.getJSONObject(i).get("equipmentLevel").toString().equals("null")) {
                    JSONObject equLevel = new JSONObject(array.getJSONObject(i).optString("equipmentLevel"));
                    item.setEquipmentLevel(equLevel.optString("levelname"));
                }else {
                    item.setEquipmentLevel("");
                }
                if (array.getJSONObject(i).get("equipmentSpecification")!=null&&!array.getJSONObject(i).get("equipmentSpecification").toString().equals("null")) {
                    JSONObject equipmentSpecification = new JSONObject(array.getJSONObject(i).optString("equipmentSpecification"));
                    item.setEquipmentSpecification(equipmentSpecification.optString("name"));
                }else {
                    item.setEquipmentSpecification("");

                }
                if (array.getJSONObject(i).get("equipmentTypeNumber")!=null&&!array.getJSONObject(i).get("equipmentTypeNumber").toString().equals("null")) {
                    JSONObject equipmentTypeNumber = new JSONObject(array.getJSONObject(i).optString("equipmentTypeNumber"));
                    item.setEquipmentTypeNumber(equipmentTypeNumber.optString("name"));
                }else {
                    item.setEquipmentTypeNumber("");

                }
                item.setEquipmentcardid(array.getJSONObject(i).optString("equipmentcardid"));
                item.setEquipmentclassid(array.getJSONObject(i).optString("equipmentclassid"));
                item.setEquipmentlevelid(array.getJSONObject(i).optString("equipmentlevelid"));
                item.setEquipmentmanufacturer(array.getJSONObject(i).optString("equipmentmanufacturer"));
                item.setEquipmentname(array.getJSONObject(i).optString("equipmentname"));
                item.setEquipmentstatus(array.getJSONObject(i).optString("equipmentstatus"));
                item.setId(array.getJSONObject(i).optString("id"));
                item.setLeavefactorynumber(array.getJSONObject(i).optString("leavefactorynumber"));
                item.setMajorparameter(array.getJSONObject(i).optString("majorparameter"));
                item.setProductiondate(array.getJSONObject(i).optString("productiondate"));
                item.setTotaltime(array.getJSONObject(i).opt("totaltime").toString());
                if (array.getJSONObject(i).optString("equipmentstatus").equals("0")) {
                    item.setEquipmentstatus("禁用");
                }else if (array.getJSONObject(i).optString("equipmentstatus").equals("1")){
                    item.setEquipmentstatus("启用");
                }
                list.add(item);
            }
        }catch(JSONException ex){
            Log.e("JSON Error: ", ex.toString());
        }

        return list;
    }

    /**
     * 初始化
     */
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid;
    private String mBizName;

    public void init(){
        SharedPreferences sharedPre=getSharedPreferences("config", MODE_PRIVATE);
        mServer=sharedPre.getString("server", "");
        mUsername=sharedPre.getString("username", "");
        mPassword=sharedPre.getString("password", "");
        mUserid=sharedPre.getString("userid", "");
        mCaption=sharedPre.getString("caption", "");
        mBizid=sharedPre.getString("bizid", "");
        mBizName=sharedPre.getString("bizname", "");
        st_pSectionId = getIntent().getStringExtra("psectionId");
    }

}
