package com.sipai.jspatrol.NFC;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
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 android.widget.Toast;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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 cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class NFCEquListActivity extends Activity {
    private EditText edt_equ;
    private Button btn_search;
    private RecyclerView rc_view;
    private LinearLayoutManager manager;
    private List<EquList> equs = new ArrayList<>();
    private EquNFCAdapter adapter;
    private SweetAlertDialog pDialog;

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

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

    public void init() {
        SharedPreferences sharedPre = getSharedPreferences("config", MODE_PRIVATE);
        mServer = sharedPre.getString("server", "");
        mUserid = sharedPre.getString("userid", "");
        mCaption = sharedPre.getString("caption", "");
        mBizid = sharedPre.getString("bizid", "");
    }

    private void initView() {
        TextView tv_title = (TextView) findViewById(R.id.moudle_back_title_tv_title);
        tv_title.setText("数据写入");
        TextView tv_right = (TextView) findViewById(R.id.moudle_back_title_tv_save);
        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();
            }
        });
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#419DE4"));
        pDialog.setTitleText("数据加载中...");
        pDialog.setCancelable(true);
        pDialog.setCanceledOnTouchOutside(true);
        edt_equ = findViewById(R.id.moudle_nfcequ_edt_equ);
        btn_search = findViewById(R.id.moudle_nfcequ_btn_search);
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkList();
            }
        });
        rc_view = findViewById(R.id.moudle_nfcequ_rc);
        manager = new LinearLayoutManager(NFCEquListActivity.this);
        rc_view.setLayoutManager(manager);
        adapter = new EquNFCAdapter(NFCEquListActivity.this, equs, new EquNFCAdapter.onRecyclerViewItemClick() {
            @Override
            public void onItemClick(View v, int position) {
                EquList aa=equs.get(position);
                String mPPid=aa.getId();
                Intent intent=new Intent();
                intent.putExtra("ppid",mPPid);
                intent.putExtra("class","equ");
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        rc_view.setAdapter(adapter);
    }

    private void showDialog() {
        if (!NFCEquListActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pDialog.show();
                }
            });
        }
    }

    private void hideDialog() {
        if (!NFCEquListActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (pDialog.isShowing()) {
                        pDialog.hide();
                    }
                }
            });
        }
    }

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

    private void checkList() {
        String equ = "";
        if (edt_equ.getText()!=null&&!edt_equ.getText().toString().isEmpty()){
            equ = edt_equ.getText().toString();
        }
        getEquList(equ);
    }

    private void getEquList(String equ) {
        showDialog();
        HashMap<String,String> map = new HashMap<>();
        map.put("unitId",mBizid);
        map.put("search_code",equ);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer, MethodURL.GetALLEquList_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (!NFCEquListActivity.this.isFinishing()) {
                    hideDialog();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(NFCEquListActivity.this,"获取设备信息失败！",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (!NFCEquListActivity.this.isFinishing()) {
                    hideDialog();
                    if(res.isEmpty()){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(NFCEquListActivity.this,"未查询到设备信息！",Toast.LENGTH_SHORT).show();
                            }
                        });

                    }else{
                        equs=getData(res);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                manager = new LinearLayoutManager(NFCEquListActivity.this);
                                rc_view.setLayoutManager(manager);
                                adapter = new EquNFCAdapter(NFCEquListActivity.this, equs, new EquNFCAdapter.onRecyclerViewItemClick() {
                                    @Override
                                    public void onItemClick(View v, int position) {
                                        EquList aa=equs.get(position);
                                        String mPPid=aa.getId();
                                        Intent intent=new Intent();
                                        intent.putExtra("ppid",mPPid);
                                        intent.putExtra("class","equ");
                                        setResult(RESULT_OK, intent);
                                        finish();
                                    }
                                });
                                rc_view.setAdapter(adapter);
                            }
                        });
                    }
                }
            }
        });
    }

    private List<EquList> getData(String response) {
        List<EquList> list = new ArrayList<EquList>();
        try{
            JSONObject jsonObject = new JSONObject(response);
            JSONArray array = new JSONArray(jsonObject.optString("result"));
            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(""));
                item.setAssetnumber(array.getJSONObject(i).optString("assetnumber"));
                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;
    }
}
